diff options
Diffstat (limited to 'dom/indexedDB/test/unit')
147 files changed, 20090 insertions, 0 deletions
diff --git a/dom/indexedDB/test/unit/GlobalObjectsChild.js b/dom/indexedDB/test/unit/GlobalObjectsChild.js new file mode 100644 index 0000000000..2724741350 --- /dev/null +++ b/dom/indexedDB/test/unit/GlobalObjectsChild.js @@ -0,0 +1,37 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* import-globals-from xpcshell-head-parent-process.js */ + +function ok(cond, msg) { + dump("ok(" + cond + ', "' + msg + '")'); + Assert.ok(!!cond, Components.stack.caller); +} + +function finishTest() { + executeSoon(function () { + do_test_finished(); + }); +} + +function run_test() { + const name = "Splendid Test"; + + do_test_pending(); + + let keyRange = IDBKeyRange.only(42); + ok(keyRange, "Got keyRange"); + + let request = indexedDB.open(name, 1); + request.onerror = function (event) { + ok(false, "indexedDB error, '" + event.target.error.name + "'"); + finishTest(); + }; + request.onsuccess = function (event) { + let db = event.target.result; + ok(db, "Got database"); + finishTest(); + }; +} diff --git a/dom/indexedDB/test/unit/GlobalObjectsModule.sys.mjs b/dom/indexedDB/test/unit/GlobalObjectsModule.sys.mjs new file mode 100644 index 0000000000..c8bb420b3d --- /dev/null +++ b/dom/indexedDB/test/unit/GlobalObjectsModule.sys.mjs @@ -0,0 +1,29 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +export function GlobalObjectsModule() {} + +GlobalObjectsModule.prototype = { + runTest() { + const name = "Splendid Test"; + + let ok = this.ok; + let finishTest = this.finishTest; + + let keyRange = IDBKeyRange.only(42); + ok(keyRange, "Got keyRange"); + + let request = indexedDB.open(name, 1); + request.onerror = function (event) { + ok(false, "indexedDB error, '" + event.target.error.name + "'"); + finishTest(); + }; + request.onsuccess = function (event) { + let db = event.target.result; + ok(db, "Got database"); + finishTest(); + }; + }, +}; diff --git a/dom/indexedDB/test/unit/GlobalObjectsSandbox.js b/dom/indexedDB/test/unit/GlobalObjectsSandbox.js new file mode 100644 index 0000000000..480746f5d0 --- /dev/null +++ b/dom/indexedDB/test/unit/GlobalObjectsSandbox.js @@ -0,0 +1,24 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* import-globals-from xpcshell-head-parent-process.js */ + +function runTest() { + const name = "Splendid Test"; + + let keyRange = IDBKeyRange.only(42); + ok(keyRange, "Got keyRange"); + + let request = indexedDB.open(name, 1); + request.onerror = function (event) { + ok(false, "indexedDB error, '" + event.target.error.name + "'"); + finishTest(); + }; + request.onsuccess = function (event) { + let db = event.target.result; + ok(db, "Got database"); + finishTest(); + }; +} diff --git a/dom/indexedDB/test/unit/URLSearchParams_profile.zip b/dom/indexedDB/test/unit/URLSearchParams_profile.zip Binary files differnew file mode 100644 index 0000000000..4d4d1e2ad6 --- /dev/null +++ b/dom/indexedDB/test/unit/URLSearchParams_profile.zip diff --git a/dom/indexedDB/test/unit/bug1056939_profile.zip b/dom/indexedDB/test/unit/bug1056939_profile.zip Binary files differnew file mode 100644 index 0000000000..db3cfe6246 --- /dev/null +++ b/dom/indexedDB/test/unit/bug1056939_profile.zip diff --git a/dom/indexedDB/test/unit/defaultStorageUpgrade_profile.zip b/dom/indexedDB/test/unit/defaultStorageUpgrade_profile.zip Binary files differnew file mode 100644 index 0000000000..2dcc10ffe0 --- /dev/null +++ b/dom/indexedDB/test/unit/defaultStorageUpgrade_profile.zip diff --git a/dom/indexedDB/test/unit/idbSubdirUpgrade1_profile.zip b/dom/indexedDB/test/unit/idbSubdirUpgrade1_profile.zip Binary files differnew file mode 100644 index 0000000000..77f26035bc --- /dev/null +++ b/dom/indexedDB/test/unit/idbSubdirUpgrade1_profile.zip diff --git a/dom/indexedDB/test/unit/idbSubdirUpgrade2_profile.zip b/dom/indexedDB/test/unit/idbSubdirUpgrade2_profile.zip Binary files differnew file mode 100644 index 0000000000..faa95ee843 --- /dev/null +++ b/dom/indexedDB/test/unit/idbSubdirUpgrade2_profile.zip diff --git a/dom/indexedDB/test/unit/make_URLSearchParams.js b/dom/indexedDB/test/unit/make_URLSearchParams.js new file mode 100644 index 0000000000..fc73746807 --- /dev/null +++ b/dom/indexedDB/test/unit/make_URLSearchParams.js @@ -0,0 +1,31 @@ +/* + Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ +*/ + +async function testSteps() { + const name = "URLSearchParams"; + const options = { foo: "bar", baz: "bar" }; + const params = new URLSearchParams(options); + const value = { urlSearchParams: params }; + const key = 42; + + info("Opening database"); + + const request = indexedDB.open(name); + await expectingUpgrade(request); + + const database = request.result; + + const objectStore = database.createObjectStore(name, {}); + + info("Adding value"); + + objectStore.add(value, key); + + await requestSucceeded(request); + + info("Closing database"); + + database.close(); +} diff --git a/dom/indexedDB/test/unit/metadata2Restore_profile.zip b/dom/indexedDB/test/unit/metadata2Restore_profile.zip Binary files differnew file mode 100644 index 0000000000..e5302b36cf --- /dev/null +++ b/dom/indexedDB/test/unit/metadata2Restore_profile.zip diff --git a/dom/indexedDB/test/unit/metadataRestore_profile.zip b/dom/indexedDB/test/unit/metadataRestore_profile.zip Binary files differnew file mode 100644 index 0000000000..a01d49166e --- /dev/null +++ b/dom/indexedDB/test/unit/metadataRestore_profile.zip diff --git a/dom/indexedDB/test/unit/mutableFileUpgrade_profile.zip b/dom/indexedDB/test/unit/mutableFileUpgrade_profile.zip Binary files differnew file mode 100644 index 0000000000..4c89acf0ae --- /dev/null +++ b/dom/indexedDB/test/unit/mutableFileUpgrade_profile.zip diff --git a/dom/indexedDB/test/unit/obsoleteOriginAttributes_profile.zip b/dom/indexedDB/test/unit/obsoleteOriginAttributes_profile.zip Binary files differnew file mode 100644 index 0000000000..01b9cfe118 --- /dev/null +++ b/dom/indexedDB/test/unit/obsoleteOriginAttributes_profile.zip diff --git a/dom/indexedDB/test/unit/oldDirectories_profile.zip b/dom/indexedDB/test/unit/oldDirectories_profile.zip Binary files differnew file mode 100644 index 0000000000..09209d351a --- /dev/null +++ b/dom/indexedDB/test/unit/oldDirectories_profile.zip diff --git a/dom/indexedDB/test/unit/orphaned_files_profile.zip b/dom/indexedDB/test/unit/orphaned_files_profile.zip Binary files differnew file mode 100644 index 0000000000..0256dcfcf9 --- /dev/null +++ b/dom/indexedDB/test/unit/orphaned_files_profile.zip diff --git a/dom/indexedDB/test/unit/schema18upgrade_profile.zip b/dom/indexedDB/test/unit/schema18upgrade_profile.zip Binary files differnew file mode 100644 index 0000000000..e13cce9d2e --- /dev/null +++ b/dom/indexedDB/test/unit/schema18upgrade_profile.zip diff --git a/dom/indexedDB/test/unit/schema21upgrade_profile.zip b/dom/indexedDB/test/unit/schema21upgrade_profile.zip Binary files differnew file mode 100644 index 0000000000..d08f88ea52 --- /dev/null +++ b/dom/indexedDB/test/unit/schema21upgrade_profile.zip diff --git a/dom/indexedDB/test/unit/schema23upgrade_profile.zip b/dom/indexedDB/test/unit/schema23upgrade_profile.zip Binary files differnew file mode 100644 index 0000000000..114d72e6cf --- /dev/null +++ b/dom/indexedDB/test/unit/schema23upgrade_profile.zip diff --git a/dom/indexedDB/test/unit/snappyUpgrade_profile.zip b/dom/indexedDB/test/unit/snappyUpgrade_profile.zip Binary files differnew file mode 100644 index 0000000000..f9635fc9f5 --- /dev/null +++ b/dom/indexedDB/test/unit/snappyUpgrade_profile.zip diff --git a/dom/indexedDB/test/unit/storagePersistentUpgrade_profile.zip b/dom/indexedDB/test/unit/storagePersistentUpgrade_profile.zip Binary files differnew file mode 100644 index 0000000000..74c84ecbfe --- /dev/null +++ b/dom/indexedDB/test/unit/storagePersistentUpgrade_profile.zip diff --git a/dom/indexedDB/test/unit/test_URLSearchParams.js b/dom/indexedDB/test/unit/test_URLSearchParams.js new file mode 100644 index 0000000000..9227898963 --- /dev/null +++ b/dom/indexedDB/test/unit/test_URLSearchParams.js @@ -0,0 +1,51 @@ +/* + Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ +*/ + +/* exported testSteps */ +async function testSteps() { + const name = "URLSearchParams"; + const options = { foo: "bar", baz: "bar" }; + const params = new URLSearchParams(options); + const value = { urlSearchParams: params }; + const key = 42; + + info("Clearing"); + + let request = clearAllDatabases(); + await requestFinished(request); + + info("Installing package"); + + // The profile contains an IndexedDB database containing URLSearchParams. + // The file make_URLSearchParams.js was run locally, specifically it was + // temporarily enabled in xpcshell-parent-process.toml and then executed: + // mach test --interactive dom/indexedDB/test/unit/make_URLSearchParams.js + installPackagedProfile("URLSearchParams_profile"); + + info("Opening database"); + + request = indexedDB.open(name); + await requestSucceeded(request); + + const database = request.result; + + info("Getting value"); + + request = database.transaction([name]).objectStore(name).get(key); + await requestSucceeded(request); + + info("Verifying value"); + + Assert.deepEqual(request.result, value, "Value is correctly structured"); + + ok( + request.result.urlSearchParams instanceof URLSearchParams, + "Value urlSearchParams property is an instance of URLSearchParams" + ); + + info("Closing database"); + + database.close(); +} diff --git a/dom/indexedDB/test/unit/test_abort_deleted_index.js b/dom/indexedDB/test/unit/test_abort_deleted_index.js new file mode 100644 index 0000000000..28bf9cbd5c --- /dev/null +++ b/dom/indexedDB/test/unit/test_abort_deleted_index.js @@ -0,0 +1,95 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const storeName = "test store"; + const indexName_ToBeDeleted = "test index to be deleted"; + + info("Create index in v1."); + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + let event = yield undefined; + + let db = event.target.result; + let txn = event.target.transaction; + + is(db.objectStoreNames.length, 0, "Correct objectStoreNames list"); + + let objectStore = db.createObjectStore(storeName, { keyPath: "foo" }); + is(db.objectStoreNames.length, 1, "Correct objectStoreNames list"); + is( + db.objectStoreNames.item(0), + objectStore.name, + "Correct object store name" + ); + + // create index to be deleted later in v2. + objectStore.createIndex(indexName_ToBeDeleted, "foo"); + ok(objectStore.index(indexName_ToBeDeleted), "Index created."); + + txn.oncomplete = continueToNextStepSync; + yield undefined; + request.onsuccess = continueToNextStep; + yield undefined; + db.close(); + + info("Delete index in v2."); + request = indexedDB.open(name, 2); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + event = yield undefined; + + db = event.target.result; + txn = event.target.transaction; + + objectStore = txn.objectStore(storeName); + let index = objectStore.index(indexName_ToBeDeleted); + ok(index, "index is valid."); + objectStore.deleteIndex(indexName_ToBeDeleted); + + // Aborting the transaction. + request.onerror = expectedErrorHandler("AbortError"); + txn.abort(); + try { + index.get("foo"); + ok( + false, + "TransactionInactiveError shall be thrown right after a deletion of an index is aborted." + ); + } catch (e) { + ok(e instanceof DOMException, "got a database exception"); + is( + e.name, + "TransactionInactiveError", + "TransactionInactiveError shall be thrown right after a deletion of an index is aborted." + ); + } + + yield undefined; + + try { + index.get("foo"); + ok( + false, + "TransactionInactiveError shall be thrown after the transaction is inactive." + ); + } catch (e) { + ok(e instanceof DOMException, "got a database exception"); + is( + e.name, + "TransactionInactiveError", + "TransactionInactiveError shall be thrown after the transaction is inactive." + ); + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_abort_deleted_objectStore.js b/dom/indexedDB/test/unit/test_abort_deleted_objectStore.js new file mode 100644 index 0000000000..88de818e5c --- /dev/null +++ b/dom/indexedDB/test/unit/test_abort_deleted_objectStore.js @@ -0,0 +1,79 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const storeName_ToBeDeleted = "test store to be deleted"; + + info("Create objectStore in v1."); + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + let event = yield undefined; + + let db = event.target.result; + let txn = event.target.transaction; + + is(db.objectStoreNames.length, 0, "Correct objectStoreNames list"); + + // create objectstore to be deleted later in v2. + db.createObjectStore(storeName_ToBeDeleted, { keyPath: "foo" }); + is(db.objectStoreNames.length, 1, "Correct objectStoreNames list"); + ok(db.objectStoreNames.contains(storeName_ToBeDeleted), "Correct name"); + + txn.oncomplete = continueToNextStepSync; + yield undefined; + request.onsuccess = continueToNextStep; + yield undefined; + db.close(); + + info("Delete objectStore in v2."); + request = indexedDB.open(name, 2); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + event = yield undefined; + + db = event.target.result; + txn = event.target.transaction; + + let objectStore = txn.objectStore(storeName_ToBeDeleted); + ok(objectStore, "objectStore is available"); + + db.deleteObjectStore(storeName_ToBeDeleted); + + // Aborting the transaction. + request.onerror = expectedErrorHandler("AbortError"); + txn.abort(); + try { + objectStore.get("foo"); + ok( + false, + "TransactionInactiveError shall be thrown if the transaction is inactive." + ); + } catch (e) { + ok(e instanceof DOMException, "got a database exception"); + is(e.name, "TransactionInactiveError", "correct error"); + } + + yield undefined; + + try { + objectStore.get("foo"); + ok( + false, + "TransactionInactiveError shall be thrown if the transaction is inactive." + ); + } catch (e) { + ok(e instanceof DOMException, "got a database exception"); + is(e.name, "TransactionInactiveError", "correct error"); + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_add_put.js b/dom/indexedDB/test/unit/test_add_put.js new file mode 100644 index 0000000000..ba880957c0 --- /dev/null +++ b/dom/indexedDB/test/unit/test_add_put.js @@ -0,0 +1,190 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + let openRequest = indexedDB.open(name, 1); + openRequest.onerror = errorHandler; + openRequest.onupgradeneeded = grabEventAndContinueHandler; + openRequest.onsuccess = unexpectedSuccessHandler; + let event = yield undefined; + let db = event.target.result; + + for (let autoincrement of [true, false]) { + for (let keypath of [false, true, "missing", "invalid"]) { + for (let method of ["put", "add"]) { + for (let explicit of [true, false, undefined, "invalid"]) { + for (let existing of [true, false]) { + let speccedNoKey = (!keypath || keypath == "missing") && !explicit; + + // We can't do 'existing' checks if we use autogenerated key + if (speccedNoKey && autoincrement && existing) { + continue; + } + + // Create store + if (db.objectStoreNames.contains("mystore")) { + db.deleteObjectStore("mystore"); + } + let store = db.createObjectStore("mystore", { + autoIncrement: autoincrement, + keyPath: keypath ? "id" : null, + }); + + let test = + " for test " + + JSON.stringify({ + autoincrement, + keypath, + method, + explicit: explicit === undefined ? "undefined" : explicit, + existing, + }); + + // Insert "existing" data if needed + if (existing) { + if (keypath) { + store.add({ + existing: "data", + id: 5, + }).onsuccess = grabEventAndContinueHandler; + } else { + store.add({ existing: "data" }, 5).onsuccess = + grabEventAndContinueHandler; + } + + let e = yield undefined; + is(e.type, "success", "success inserting existing" + test); + is(e.target.result, 5, "inserted correct key" + test); + } + + // Set up value to be inserted + let value = { theObj: true }; + if (keypath === true) { + value.id = 5; + } else if (keypath === "invalid") { + value.id = /x/; + } + + // Which arguments are passed to function + let args = [value]; + if (explicit === true) { + args.push(5); + } else if (explicit === undefined) { + args.push(undefined); + } else if (explicit === "invalid") { + args.push(/x/); + } + + let expected = expectedResult( + method, + keypath, + explicit, + autoincrement, + existing + ); + + let valueJSON = JSON.stringify(value); + + ok(true, "making call" + test); + + // Make function call for throwing functions + if (expected === "throw") { + try { + store[method].apply(store, args); + ok(false, "should have thrown" + test); + } catch (ex) { + ok(true, "did throw" + test); + ok(ex instanceof DOMException, "Got a DOMException" + test); + is(ex.name, "DataError", "expect a DataError" + test); + is(ex.code, 0, "expect zero" + test); + is( + JSON.stringify(value), + valueJSON, + "call didn't modify value" + test + ); + } + continue; + } + + // Make non-throwing function call + let req = store[method].apply(store, args); + is( + JSON.stringify(value), + valueJSON, + "call didn't modify value" + test + ); + + req.onsuccess = req.onerror = grabEventAndContinueHandler; + let e = yield undefined; + + // Figure out what key we used + let key = 5; + if (autoincrement && speccedNoKey) { + key = 1; + } + + // Adjust value if expected + if (autoincrement && keypath && speccedNoKey) { + value.id = key; + } + + // Check result + if (expected === "error") { + is(e.type, "error", "write should fail" + test); + e.preventDefault(); + e.stopPropagation(); + continue; + } + + is(e.type, "success", "write should succeed" + test); + is(e.target.result, key, "write should return correct key" + test); + + store.get(key).onsuccess = grabEventAndContinueHandler; + e = yield undefined; + is(e.type, "success", "read back should succeed" + test); + is( + JSON.stringify(e.target.result), + JSON.stringify(value), + "read back should return correct value" + test + ); + } + } + } + } + } + + function expectedResult(method, keypath, explicit, autoincrement, existing) { + if (keypath && explicit) { + return "throw"; + } + if (!keypath && !explicit && !autoincrement) { + return "throw"; + } + if (keypath == "invalid") { + return "throw"; + } + if (keypath == "missing" && !autoincrement) { + return "throw"; + } + if (explicit == "invalid") { + return "throw"; + } + + if (method == "add" && existing) { + return "error"; + } + + return "success"; + } + + openRequest.onsuccess = grabEventAndContinueHandler; + yield undefined; + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_add_twice_failure.js b/dom/indexedDB/test/unit/test_add_twice_failure.js new file mode 100644 index 0000000000..cbc921aa87 --- /dev/null +++ b/dom/indexedDB/test/unit/test_add_twice_failure.js @@ -0,0 +1,41 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = request.result; + + ok(event.target === request, "Good event target"); + + let objectStore = db.createObjectStore("foo", { keyPath: null }); + let key = 10; + + request = objectStore.add({}, key); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(request.result, key, "Correct key"); + + request = objectStore.add({}, key); + request.addEventListener("error", new ExpectError("ConstraintError", true)); + request.onsuccess = unexpectedSuccessHandler; + yield undefined; + + // Wait for success. + yield undefined; + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_advance.js b/dom/indexedDB/test/unit/test_advance.js new file mode 100644 index 0000000000..eb18c68af4 --- /dev/null +++ b/dom/indexedDB/test/unit/test_advance.js @@ -0,0 +1,181 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const dataCount = 30; + + let request = indexedDB.open( + this.window ? window.location.pathname : "Splendid Test", + 1 + ); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + db.onerror = errorHandler; + + event.target.onsuccess = continueToNextStep; + + let objectStore = db.createObjectStore("", { keyPath: "key" }); + objectStore.createIndex("", "index"); + + for (let i = 0; i < dataCount; i++) { + objectStore.add({ key: i, index: i }); + } + yield undefined; + + function getObjectStore() { + return db.transaction("").objectStore(""); + } + + function getIndex() { + return db.transaction("").objectStore("").index(""); + } + + let count = 0; + + getObjectStore().openCursor().onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + continueToNextStep(); + } + }; + yield undefined; + + is(count, dataCount, "Saw all data"); + + count = 0; + + getObjectStore().openCursor().onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is(cursor.primaryKey, count, "Got correct object"); + if (count) { + count++; + cursor.continue(); + } else { + count = 10; + cursor.advance(10); + } + } else { + continueToNextStep(); + } + }; + yield undefined; + + is(count, dataCount, "Saw all data"); + + count = 0; + + getIndex().openCursor().onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is(cursor.primaryKey, count, "Got correct object"); + if (count) { + count++; + cursor.continue(); + } else { + count = 10; + cursor.advance(10); + } + } else { + continueToNextStep(); + } + }; + yield undefined; + + is(count, dataCount, "Saw all data"); + + count = 0; + + getIndex().openKeyCursor().onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is(cursor.primaryKey, count, "Got correct object"); + if (count) { + count++; + cursor.continue(); + } else { + count = 10; + cursor.advance(10); + } + } else { + continueToNextStep(); + } + }; + yield undefined; + + is(count, dataCount, "Saw all data"); + + count = 0; + + getObjectStore().openCursor().onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is(cursor.primaryKey, count, "Got correct object"); + if (count == 0) { + cursor.advance(dataCount + 1); + } else { + ok(false, "Should never get here!"); + cursor.continue(); + } + } else { + continueToNextStep(); + } + }; + yield undefined; + + is(count, 0, "Saw all data"); + + count = dataCount - 1; + + getObjectStore().openCursor(null, "prev").onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is(cursor.primaryKey, count, "Got correct object"); + count--; + if (count == dataCount - 2) { + cursor.advance(10); + count -= 9; + } else { + cursor.continue(); + } + } else { + continueToNextStep(); + } + }; + yield undefined; + + is(count, -1, "Saw all data"); + + count = dataCount - 1; + + getObjectStore().openCursor(null, "prev").onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is(cursor.primaryKey, count, "Got correct object"); + if (count == dataCount - 1) { + cursor.advance(dataCount + 1); + } else { + ok(false, "Should never get here!"); + cursor.continue(); + } + } else { + continueToNextStep(); + } + }; + yield undefined; + + is(count, dataCount - 1, "Saw all data"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_autoIncrement.js b/dom/indexedDB/test/unit/test_autoIncrement.js new file mode 100644 index 0000000000..6f502deaf0 --- /dev/null +++ b/dom/indexedDB/test/unit/test_autoIncrement.js @@ -0,0 +1,588 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator, disableWorkerTest */ +var disableWorkerTest = "Need to implement a gc() function for worker tests"; + +if (!this.window) { + this.runTest = function () { + todo(false, "Test disabled in xpcshell test suite for now"); + finishTest(); + }; +} + +var testGenerator = testSteps(); + +function genCheck(key, value, test, options) { + return function (event) { + is( + JSON.stringify(event.target.result), + JSON.stringify(key), + "correct returned key in " + test + ); + if (options && options.store) { + is(event.target.source, options.store, "correct store in " + test); + } + if (options && options.trans) { + is( + event.target.transaction, + options.trans, + "correct transaction in " + test + ); + } + + event.target.source.get(key).onsuccess = function (event) { + is( + JSON.stringify(event.target.result), + JSON.stringify(value), + "correct stored value in " + test + ); + continueToNextStepSync(); + }; + }; +} + +function* testSteps() { + const dbname = this.window ? window.location.pathname : "Splendid Test"; + const RW = "readwrite"; + let c1 = 1; + let c2 = 1; + + let openRequest = indexedDB.open(dbname, 1); + openRequest.onerror = errorHandler; + openRequest.onupgradeneeded = grabEventAndContinueHandler; + openRequest.onsuccess = unexpectedSuccessHandler; + let event = yield undefined; + let db = event.target.result; + let trans = event.target.transaction; + + // Create test stores + let store1 = db.createObjectStore("store1", { autoIncrement: true }); + let store2 = db.createObjectStore("store2", { + autoIncrement: true, + keyPath: "id", + }); + let store3 = db.createObjectStore("store3", { autoIncrement: false }); + is(store1.autoIncrement, true, "store1 .autoIncrement"); + is(store2.autoIncrement, true, "store2 .autoIncrement"); + is(store3.autoIncrement, false, "store3 .autoIncrement"); + + store1.createIndex("unique1", "unique", { unique: true }); + store2.createIndex("unique1", "unique", { unique: true }); + + // Test simple inserts + let test = " for test simple insert"; + store1.add({ foo: "value1" }).onsuccess = genCheck( + c1++, + { foo: "value1" }, + "first" + test + ); + store1.add({ foo: "value2" }).onsuccess = genCheck( + c1++, + { foo: "value2" }, + "second" + test + ); + + yield undefined; + yield undefined; + + store2.put({ bar: "value1" }).onsuccess = genCheck( + c2, + { bar: "value1", id: c2 }, + "first in store2" + test, + { store: store2 } + ); + c2++; + store1.put({ foo: "value3" }).onsuccess = genCheck( + c1++, + { foo: "value3" }, + "third" + test, + { store: store1 } + ); + + yield undefined; + yield undefined; + + store2.get(IDBKeyRange.lowerBound(c2)).onsuccess = + grabEventAndContinueHandler; + event = yield undefined; + is(event.target.result, undefined, "no such value" + test); + + // Close version_change transaction + openRequest.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target, openRequest, "succeeded to open" + test); + is(event.type, "success", "succeeded to open" + test); + + // Test inserting explicit keys + test = " for test explicit keys"; + trans = db.transaction("store1", RW); + trans.objectStore("store1").add({ explicit: 1 }, 100).onsuccess = genCheck( + 100, + { explicit: 1 }, + "first" + test + ); + c1 = 101; + trans = db.transaction("store1", RW); + trans.objectStore("store1").add({ explicit: 2 }).onsuccess = genCheck( + c1++, + { explicit: 2 }, + "second" + test + ); + yield undefined; + yield undefined; + + trans = db.transaction("store1", RW); + trans.objectStore("store1").add({ explicit: 3 }, 200).onsuccess = genCheck( + 200, + { explicit: 3 }, + "third" + test + ); + c1 = 201; + trans.objectStore("store1").add({ explicit: 4 }).onsuccess = genCheck( + c1++, + { explicit: 4 }, + "fourth" + test + ); + yield undefined; + yield undefined; + + trans = db.transaction("store1", RW); + trans.objectStore("store1").add({ explicit: 5 }, 150).onsuccess = genCheck( + 150, + { explicit: 5 }, + "fifth" + test + ); + yield undefined; + trans.objectStore("store1").add({ explicit: 6 }).onsuccess = genCheck( + c1++, + { explicit: 6 }, + "sixth" + test + ); + yield undefined; + + trans = db.transaction("store1", RW); + trans.objectStore("store1").add({ explicit: 7 }, "key").onsuccess = genCheck( + "key", + { explicit: 7 }, + "seventh" + test + ); + yield undefined; + trans.objectStore("store1").add({ explicit: 8 }).onsuccess = genCheck( + c1++, + { explicit: 8 }, + "eighth" + test + ); + yield undefined; + + trans = db.transaction("store1", RW); + trans.objectStore("store1").add({ explicit: 7 }, [100000]).onsuccess = + genCheck([100000], { explicit: 7 }, "seventh" + test); + yield undefined; + trans.objectStore("store1").add({ explicit: 8 }).onsuccess = genCheck( + c1++, + { explicit: 8 }, + "eighth" + test + ); + yield undefined; + + trans = db.transaction("store1", RW); + trans.objectStore("store1").add({ explicit: 9 }, -100000).onsuccess = + genCheck(-100000, { explicit: 9 }, "ninth" + test); + yield undefined; + trans.objectStore("store1").add({ explicit: 10 }).onsuccess = genCheck( + c1++, + { explicit: 10 }, + "tenth" + test + ); + yield undefined; + + trans = db.transaction("store2", RW); + trans.objectStore("store2").add({ explicit2: 1, id: 300 }).onsuccess = + genCheck(300, { explicit2: 1, id: 300 }, "first store2" + test); + c2 = 301; + trans = db.transaction("store2", RW); + trans.objectStore("store2").add({ explicit2: 2 }).onsuccess = genCheck( + c2, + { explicit2: 2, id: c2 }, + "second store2" + test + ); + c2++; + yield undefined; + yield undefined; + + trans = db.transaction("store2", RW); + trans.objectStore("store2").add({ explicit2: 3, id: 400 }).onsuccess = + genCheck(400, { explicit2: 3, id: 400 }, "third store2" + test); + c2 = 401; + trans.objectStore("store2").add({ explicit2: 4 }).onsuccess = genCheck( + c2, + { explicit2: 4, id: c2 }, + "fourth store2" + test + ); + c2++; + yield undefined; + yield undefined; + + trans = db.transaction("store2", RW); + trans.objectStore("store2").add({ explicit: 5, id: 150 }).onsuccess = + genCheck(150, { explicit: 5, id: 150 }, "fifth store2" + test); + yield undefined; + trans.objectStore("store2").add({ explicit: 6 }).onsuccess = genCheck( + c2, + { explicit: 6, id: c2 }, + "sixth store2" + test + ); + c2++; + yield undefined; + + trans = db.transaction("store2", RW); + trans.objectStore("store2").add({ explicit: 7, id: "key" }).onsuccess = + genCheck("key", { explicit: 7, id: "key" }, "seventh store2" + test); + yield undefined; + trans.objectStore("store2").add({ explicit: 8 }).onsuccess = genCheck( + c2, + { explicit: 8, id: c2 }, + "eighth store2" + test + ); + c2++; + yield undefined; + + trans = db.transaction("store2", RW); + trans.objectStore("store2").add({ explicit: 7, id: [100000] }).onsuccess = + genCheck([100000], { explicit: 7, id: [100000] }, "seventh store2" + test); + yield undefined; + trans.objectStore("store2").add({ explicit: 8 }).onsuccess = genCheck( + c2, + { explicit: 8, id: c2 }, + "eighth store2" + test + ); + c2++; + yield undefined; + + trans = db.transaction("store2", RW); + trans.objectStore("store2").add({ explicit: 9, id: -100000 }).onsuccess = + genCheck(-100000, { explicit: 9, id: -100000 }, "ninth store2" + test); + yield undefined; + trans.objectStore("store2").add({ explicit: 10 }).onsuccess = genCheck( + c2, + { explicit: 10, id: c2 }, + "tenth store2" + test + ); + c2++; + yield undefined; + + // Test separate transactions doesn't generate overlapping numbers + test = " for test non-overlapping counts"; + trans = db.transaction("store1", RW); + let trans2 = db.transaction("store1", RW); + trans2.objectStore("store1").put({ over: 2 }).onsuccess = genCheck( + c1 + 1, + { over: 2 }, + "first" + test, + { trans: trans2 } + ); + trans.objectStore("store1").put({ over: 1 }).onsuccess = genCheck( + c1, + { over: 1 }, + "second" + test, + { trans } + ); + c1 += 2; + yield undefined; + yield undefined; + + trans = db.transaction("store2", RW); + trans2 = db.transaction("store2", RW); + trans2.objectStore("store2").put({ over: 2 }).onsuccess = genCheck( + c2 + 1, + { over: 2, id: c2 + 1 }, + "third" + test, + { trans: trans2 } + ); + trans.objectStore("store2").put({ over: 1 }).onsuccess = genCheck( + c2, + { over: 1, id: c2 }, + "fourth" + test, + { trans } + ); + c2 += 2; + yield undefined; + yield undefined; + + // Test that error inserts doesn't increase generator + test = " for test error inserts"; + trans = db.transaction(["store1", "store2"], RW); + trans.objectStore("store1").add({ unique: 1 }, -1); + trans.objectStore("store2").add({ unique: 1, id: "unique" }); + + trans + .objectStore("store1") + .add({ error: 1, unique: 1 }) + .addEventListener("error", new ExpectError("ConstraintError", true)); + trans.objectStore("store1").add({ error: 2 }).onsuccess = genCheck( + c1++, + { error: 2 }, + "first" + test + ); + yield undefined; + yield undefined; + + trans + .objectStore("store2") + .add({ error: 3, unique: 1 }) + .addEventListener("error", new ExpectError("ConstraintError", true)); + trans.objectStore("store2").add({ error: 4 }).onsuccess = genCheck( + c2, + { error: 4, id: c2 }, + "second" + test + ); + c2++; + yield undefined; + yield undefined; + + trans + .objectStore("store1") + .add({ error: 5, unique: 1 }, 100000) + .addEventListener("error", new ExpectError("ConstraintError", true)); + trans.objectStore("store1").add({ error: 6 }).onsuccess = genCheck( + c1++, + { error: 6 }, + "third" + test + ); + yield undefined; + yield undefined; + + trans + .objectStore("store2") + .add({ error: 7, unique: 1, id: 100000 }) + .addEventListener("error", new ExpectError("ConstraintError", true)); + trans.objectStore("store2").add({ error: 8 }).onsuccess = genCheck( + c2, + { error: 8, id: c2 }, + "fourth" + test + ); + c2++; + yield undefined; + yield undefined; + + // Test that aborts doesn't increase generator + test = " for test aborted transaction"; + trans = db.transaction(["store1", "store2"], RW); + trans.objectStore("store1").add({ abort: 1 }).onsuccess = genCheck( + c1, + { abort: 1 }, + "first" + test + ); + trans.objectStore("store2").put({ abort: 2 }).onsuccess = genCheck( + c2, + { abort: 2, id: c2 }, + "second" + test + ); + yield undefined; + yield undefined; + + trans.objectStore("store1").add({ abort: 3 }, 500).onsuccess = genCheck( + 500, + { abort: 3 }, + "third" + test + ); + trans.objectStore("store2").put({ abort: 4, id: 600 }).onsuccess = genCheck( + 600, + { abort: 4, id: 600 }, + "fourth" + test + ); + yield undefined; + yield undefined; + + trans.objectStore("store1").add({ abort: 5 }).onsuccess = genCheck( + 501, + { abort: 5 }, + "fifth" + test + ); + trans.objectStore("store2").put({ abort: 6 }).onsuccess = genCheck( + 601, + { abort: 6, id: 601 }, + "sixth" + test + ); + yield undefined; + yield undefined; + + trans.abort(); + trans.onabort = grabEventAndContinueHandler; + event = yield; + is(event.type, "abort", "transaction aborted"); + is(event.target, trans, "correct transaction aborted"); + + trans = db.transaction(["store1", "store2"], RW); + trans.objectStore("store1").add({ abort: 1 }).onsuccess = genCheck( + c1++, + { abort: 1 }, + "re-first" + test + ); + trans.objectStore("store2").put({ abort: 2 }).onsuccess = genCheck( + c2, + { abort: 2, id: c2 }, + "re-second" + test + ); + c2++; + yield undefined; + yield undefined; + + // Test that delete doesn't decrease generator + test = " for test delete items"; + trans = db.transaction(["store1", "store2"], RW); + trans.objectStore("store1").add({ delete: 1 }).onsuccess = genCheck( + c1++, + { delete: 1 }, + "first" + test + ); + trans.objectStore("store2").put({ delete: 2 }).onsuccess = genCheck( + c2, + { delete: 2, id: c2 }, + "second" + test + ); + c2++; + yield undefined; + yield undefined; + + trans.objectStore("store1").delete(c1 - 1).onsuccess = + grabEventAndContinueHandler; + trans.objectStore("store2").delete(c2 - 1).onsuccess = + grabEventAndContinueHandler; + yield undefined; + yield undefined; + + trans.objectStore("store1").add({ delete: 3 }).onsuccess = genCheck( + c1++, + { delete: 3 }, + "first" + test + ); + trans.objectStore("store2").put({ delete: 4 }).onsuccess = genCheck( + c2, + { delete: 4, id: c2 }, + "second" + test + ); + c2++; + yield undefined; + yield undefined; + + trans.objectStore("store1").delete(c1 - 1).onsuccess = + grabEventAndContinueHandler; + trans.objectStore("store2").delete(c2 - 1).onsuccess = + grabEventAndContinueHandler; + yield undefined; + yield undefined; + + trans = db.transaction(["store1", "store2"], RW); + trans.objectStore("store1").add({ delete: 5 }).onsuccess = genCheck( + c1++, + { delete: 5 }, + "first" + test + ); + trans.objectStore("store2").put({ delete: 6 }).onsuccess = genCheck( + c2, + { delete: 6, id: c2 }, + "second" + test + ); + c2++; + yield undefined; + yield undefined; + + // Test that clears doesn't decrease generator + test = " for test clear stores"; + trans = db.transaction(["store1", "store2"], RW); + trans.objectStore("store1").add({ clear: 1 }).onsuccess = genCheck( + c1++, + { clear: 1 }, + "first" + test + ); + trans.objectStore("store2").put({ clear: 2 }).onsuccess = genCheck( + c2, + { clear: 2, id: c2 }, + "second" + test + ); + c2++; + yield undefined; + yield undefined; + + trans.objectStore("store1").clear().onsuccess = grabEventAndContinueHandler; + trans.objectStore("store2").clear().onsuccess = grabEventAndContinueHandler; + yield undefined; + yield undefined; + + trans.objectStore("store1").add({ clear: 3 }).onsuccess = genCheck( + c1++, + { clear: 3 }, + "third" + test + ); + trans.objectStore("store2").put({ clear: 4 }).onsuccess = genCheck( + c2, + { clear: 4, id: c2 }, + "forth" + test + ); + c2++; + yield undefined; + yield undefined; + + trans.objectStore("store1").clear().onsuccess = grabEventAndContinueHandler; + trans.objectStore("store2").clear().onsuccess = grabEventAndContinueHandler; + yield undefined; + yield undefined; + + trans = db.transaction(["store1", "store2"], RW); + trans.objectStore("store1").add({ clear: 5 }).onsuccess = genCheck( + c1++, + { clear: 5 }, + "fifth" + test + ); + trans.objectStore("store2").put({ clear: 6 }).onsuccess = genCheck( + c2, + { clear: 6, id: c2 }, + "sixth" + test + ); + c2++; + yield undefined; + yield undefined; + + // Test that close/reopen doesn't decrease generator + test = " for test clear stores"; + trans = db.transaction(["store1", "store2"], RW); + trans.objectStore("store1").clear().onsuccess = grabEventAndContinueHandler; + trans.objectStore("store2").clear().onsuccess = grabEventAndContinueHandler; + yield undefined; + yield undefined; + db.close(); + + gc(); + + openRequest = indexedDB.open(dbname, 2); + openRequest.onerror = errorHandler; + openRequest.onupgradeneeded = grabEventAndContinueHandler; + openRequest.onsuccess = unexpectedSuccessHandler; + event = yield undefined; + db = event.target.result; + trans = event.target.transaction; + + trans.objectStore("store1").add({ reopen: 1 }).onsuccess = genCheck( + c1++, + { reopen: 1 }, + "first" + test + ); + trans.objectStore("store2").put({ reopen: 2 }).onsuccess = genCheck( + c2, + { reopen: 2, id: c2 }, + "second" + test + ); + c2++; + yield undefined; + yield undefined; + + openRequest.onsuccess = grabEventAndContinueHandler; + yield undefined; + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_autoIncrement_indexes.js b/dom/indexedDB/test/unit/test_autoIncrement_indexes.js new file mode 100644 index 0000000000..64de7f4efb --- /dev/null +++ b/dom/indexedDB/test/unit/test_autoIncrement_indexes.js @@ -0,0 +1,60 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + let request = indexedDB.open( + this.window ? window.location.pathname : "Splendid Test", + 1 + ); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + let event = yield undefined; + + let db = request.result; + db.onerror = errorHandler; + + let objectStore = db.createObjectStore("foo", { + keyPath: "id", + autoIncrement: true, + }); + objectStore.createIndex("first", "first"); + objectStore.createIndex("second", "second"); + objectStore.createIndex("third", "third"); + + let data = { first: "foo", second: "foo", third: "foo" }; + + objectStore.add(data).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, 1, "Added entry"); + request.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + objectStore = db.transaction("foo").objectStore("foo"); + let first = objectStore.index("first"); + let second = objectStore.index("second"); + let third = objectStore.index("third"); + + first.get("foo").onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result.id, 1, "Entry in first"); + + second.get("foo").onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result.id, 1, "Entry in second"); + + third.get("foo").onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result.id, 1, "Entry in third"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_bad_origin_directory.js b/dom/indexedDB/test/unit/test_bad_origin_directory.js new file mode 100644 index 0000000000..65943d0546 --- /dev/null +++ b/dom/indexedDB/test/unit/test_bad_origin_directory.js @@ -0,0 +1,29 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const url = "ws://ws.example.com"; + const name = "test_bad_origin_directory.js"; + + let uri = Services.io.newURI(url); + + let principal = Services.scriptSecurityManager.createContentPrincipal( + uri, + {} + ); + + info("Opening database"); + + let request = indexedDB.openForPrincipal(principal, name); + request.onerror = continueToNextStepSync; + request.onsuccess = unexpectedSuccessHandler; + yield undefined; + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_blob_file_backed.js b/dom/indexedDB/test/unit/test_blob_file_backed.js new file mode 100644 index 0000000000..ba973d63d5 --- /dev/null +++ b/dom/indexedDB/test/unit/test_blob_file_backed.js @@ -0,0 +1,79 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator, disableWorkerTest */ +var disableWorkerTest = "This test uses SpecialPowers"; + +var testGenerator = testSteps(); + +function* testSteps() { + const fileData = "abcdefghijklmnopqrstuvwxyz"; + const fileType = "text/plain"; + + const databaseName = "window" in this ? window.location.pathname : "Test"; + const objectStoreName = "foo"; + const objectStoreKey = "10"; + + info("Creating temp file"); + + SpecialPowers.createFiles( + [{ data: fileData, options: { type: fileType } }], + function (files) { + testGenerator.next(files[0]); + } + ); + + let file = yield undefined; + + ok(file instanceof File, "Got a File object"); + is(file.size, fileData.length, "Correct size"); + is(file.type, fileType, "Correct type"); + + let fileReader = new FileReader(); + fileReader.onload = grabEventAndContinueHandler; + fileReader.readAsText(file); + + let event = yield undefined; + + is(fileReader.result, fileData, "Correct data"); + + let request = indexedDB.open(databaseName, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + let db = event.target.result; + let objectStore = db.createObjectStore(objectStoreName); + objectStore.put(file, objectStoreKey); + + event = yield undefined; + + db = event.target.result; + + file = null; + + objectStore = db.transaction(objectStoreName).objectStore(objectStoreName); + objectStore.get(objectStoreKey).onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + file = event.target.result; + + ok(file instanceof File, "Got a File object"); + is(file.size, fileData.length, "Correct size"); + is(file.type, fileType, "Correct type"); + + fileReader = new FileReader(); + fileReader.onload = grabEventAndContinueHandler; + fileReader.readAsText(file); + + event = yield undefined; + + is(fileReader.result, fileData, "Correct data"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_blocked_order.js b/dom/indexedDB/test/unit/test_blocked_order.js new file mode 100644 index 0000000000..212b1b3254 --- /dev/null +++ b/dom/indexedDB/test/unit/test_blocked_order.js @@ -0,0 +1,177 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const databaseName = "window" in this ? window.location.pathname : "Test"; + const databaseCount = 10; + + // Test 1: Make sure basic versionchange events work and that they don't + // trigger blocked events. + info("Opening " + databaseCount + " databases with version 1"); + + let databases = []; + + for (let i = 0; i < databaseCount; i++) { + let thisIndex = i; + + info("Opening database " + thisIndex); + + let request = indexedDB.open(databaseName, 1); + request.onerror = errorHandler; + request.onblocked = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + let event = yield undefined; + + is(event.type, "success", "Got success event"); + + let db = request.result; + is(db.version, 1, "Got version 1"); + + db.onversionchange = function (event) { + info("Closing database " + thisIndex); + db.close(); + + databases.splice(databases.indexOf(db), 1); + }; + + databases.push(db); + } + + is(databases.length, databaseCount, "Created all databases with version 1"); + + info("Opening database with version 2"); + + let request = indexedDB.open(databaseName, 2); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + request.onblocked = function (event) { + ok(false, "Should not receive a blocked event"); + }; + + let event = yield undefined; + + is(event.type, "success", "Got success event"); + is(databases.length, 0, "All databases with version 1 were closed"); + + let db = request.result; + is(db.version, 2, "Got version 2"); + + info("Deleting database with version 2"); + db.close(); + + request = indexedDB.deleteDatabase(databaseName); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + is(event.type, "success", "Got success event"); + + // Test 2: Make sure blocked events aren't delivered until all versionchange + // events have been delivered. + info("Opening " + databaseCount + " databases with version 1"); + + for (let i = 0; i < databaseCount; i++) { + let thisIndex = i; + + info("Opening database " + thisIndex); + + let request = indexedDB.open(databaseName, 1); + request.onerror = errorHandler; + request.onblocked = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + let event = yield undefined; + + is(event.type, "success", "Got success event"); + + let db = request.result; + is(db.version, 1, "Got version 1"); + + db.onversionchange = function (event) { + if (thisIndex == databaseCount - 1) { + info("Closing all databases with version 1"); + + for (let j = 0; j < databases.length; j++) { + databases[j].close(); + } + + databases = []; + info("Done closing all databases with version 1"); + } else { + info("Not closing database " + thisIndex); + } + }; + + databases.push(db); + } + + is(databases.length, databaseCount, "Created all databases with version 1"); + + info("Opening database with version 2"); + + request = indexedDB.open(databaseName, 2); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + request.onblocked = function (event) { + ok(false, "Should not receive a blocked event"); + }; + + event = yield undefined; + + is(event.type, "success", "Got success event"); + is(databases.length, 0, "All databases with version 1 were closed"); + + db = request.result; + is(db.version, 2, "Got version 2"); + + info("Deleting database with version 2"); + db.close(); + + request = indexedDB.deleteDatabase(databaseName); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + is(event.type, "success", "Got success event"); + + // Test 3: A blocked database left in that state should not hang shutdown. + info("Opening 1 database with version 1"); + + request = indexedDB.open(databaseName, 1); + request.onerror = errorHandler; + request.onblocked = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + is(event.type, "success", "Got success event"); + + db = request.result; + is(db.version, 1, "Got version 1"); + + info("Opening database with version 2"); + + request = indexedDB.open(databaseName, 2); + request.onerror = function (e) { + e.preventDefault(); + }; + request.onsuccess = errorHandler; + + request.onblocked = grabEventAndContinueHandler; + + event = yield undefined; + ok(true, "Got blocked"); + // Just allow this to remain blocked ... + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_bug1056939.js b/dom/indexedDB/test/unit/test_bug1056939.js new file mode 100644 index 0000000000..531a5df94d --- /dev/null +++ b/dom/indexedDB/test/unit/test_bug1056939.js @@ -0,0 +1,73 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const dbName1 = "upgrade_test"; + const dbName2 = "testing.foobar"; + const dbName3 = "xxxxxxx.xxxxxx"; + + clearAllDatabases(continueToNextStepSync); + yield undefined; + + installPackagedProfile("bug1056939_profile"); + + let request = indexedDB.open(dbName1, 1); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + is(event.type, "success", "Correct event type"); + + request = indexedDB.open(dbName2, 1); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.type, "success", "Got correct event type"); + + request = indexedDB.open(dbName3, 1); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.type, "success", "Got correct event type"); + + clearAllDatabases(continueToNextStepSync); + yield undefined; + + request = indexedDB.open(dbName3, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + event = yield undefined; + + is(event.type, "upgradeneeded", "Got correct event type"); + + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.type, "success", "Got correct event type"); + + resetAllDatabases(continueToNextStepSync); + yield undefined; + + request = indexedDB.open(dbName3, 1); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.type, "success", "Got correct event type"); + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_cleanup_transaction.js b/dom/indexedDB/test/unit/test_cleanup_transaction.js new file mode 100644 index 0000000000..cac3c9bf60 --- /dev/null +++ b/dom/indexedDB/test/unit/test_cleanup_transaction.js @@ -0,0 +1,155 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator, disableWorkerTest */ +var disableWorkerTest = "Need a way to set temporary prefs from a worker"; + +var testGenerator = testSteps(); + +function* testSteps() { + const spec = "http://foo.com"; + const name = this.window + ? window.location.pathname + : "test_quotaExceeded_recovery"; + const objectStoreName = "foo"; + + // We want 32 MB database, but there's the group limit so we need to + // multiply by 5. + const tempStorageLimitKB = 32 * 1024 * 5; + + // Store in 1 MB chunks. + const dataSize = 1024 * 1024; + + for (let blobs of [false, true]) { + setTemporaryStorageLimit(tempStorageLimitKB); + + clearAllDatabases(continueToNextStepSync); + yield undefined; + + info("Opening database"); + + let request = indexedDB.openForPrincipal(getPrincipal(spec), name); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + + yield undefined; + + // upgradeneeded + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + + info("Creating objectStore"); + + request.result.createObjectStore(objectStoreName); + + yield undefined; + + // success + let db = request.result; + db.onerror = errorHandler; + + ok(true, "Adding data until quota is reached"); + + let obj = { + name: "foo", + }; + + if (!blobs) { + obj.data = getRandomView(dataSize); + } + + let i = 1; + let j = 1; + while (true) { + if (blobs) { + obj.data = getBlob(getView(dataSize)); + } + + let trans = db.transaction(objectStoreName, "readwrite"); + request = trans.objectStore(objectStoreName).add(obj, i); + request.onerror = function (event) { + event.stopPropagation(); + }; + + trans.oncomplete = function (event) { + i++; + j++; + testGenerator.next(true); + }; + trans.onabort = function (event) { + is(trans.error.name, "QuotaExceededError", "Reached quota limit"); + testGenerator.next(false); + }; + + let completeFired = yield undefined; + if (completeFired) { + ok(true, "Got complete event"); + } else { + ok(true, "Got abort event"); + + if (j == 1) { + // Plain cleanup transaction (just vacuuming and checkpointing) + // couldn't shrink database any further. + break; + } + + j = 1; + + trans = db.transaction(objectStoreName, "cleanup"); + trans.onabort = unexpectedSuccessHandler; + trans.oncomplete = grabEventAndContinueHandler; + + yield undefined; + } + } + + info("Reopening database"); + + db.close(); + + request = indexedDB.openForPrincipal(getPrincipal(spec), name); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + yield undefined; + + db = request.result; + db.onerror = errorHandler; + + info("Deleting some data"); + + let trans = db.transaction(objectStoreName, "cleanup"); + trans.objectStore(objectStoreName).delete(1); + + trans.onabort = unexpectedSuccessHandler; + trans.oncomplete = grabEventAndContinueHandler; + + yield undefined; + + info("Adding data again"); + + trans = db.transaction(objectStoreName, "readwrite"); + trans.objectStore(objectStoreName).add(obj, 1); + + trans.onabort = unexpectedSuccessHandler; + trans.oncomplete = grabEventAndContinueHandler; + + yield undefined; + + info("Deleting database"); + + db.close(); + + request = indexedDB.deleteForPrincipal(getPrincipal(spec), name); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + yield undefined; + } + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_clear.js b/dom/indexedDB/test/unit/test_clear.js new file mode 100644 index 0000000000..d504ff8851 --- /dev/null +++ b/dom/indexedDB/test/unit/test_clear.js @@ -0,0 +1,90 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const entryCount = 1000; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + let event = yield undefined; + + let db = request.result; + + event.target.onsuccess = continueToNextStep; + + let objectStore = db.createObjectStore("foo", { autoIncrement: true }); + + let firstKey; + for (let i = 0; i < entryCount; i++) { + request = objectStore.add({}); + request.onerror = errorHandler; + if (!i) { + request.onsuccess = function (event) { + firstKey = event.target.result; + }; + } + } + yield undefined; + + isnot(firstKey, undefined, "got first key"); + + let seenEntryCount = 0; + + request = db.transaction("foo").objectStore("foo").openCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + seenEntryCount++; + cursor.continue(); + } else { + continueToNextStep(); + } + }; + yield undefined; + + is(seenEntryCount, entryCount, "Correct entry count"); + + try { + db.transaction("foo").objectStore("foo").clear(); + ok(false, "clear should throw on READ_ONLY transactions"); + } catch (e) { + ok(true, "clear should throw on READ_ONLY transactions"); + } + + request = db.transaction("foo", "readwriteflush").objectStore("foo").clear(); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + ok(event.target.result === undefined, "Correct event.target.result"); + ok(request.result === undefined, "Correct request.result"); + ok(request === event.target, "Correct event.target"); + + request = db.transaction("foo").objectStore("foo").openCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = request.result; + if (cursor) { + ok(false, "Shouldn't have any entries"); + } + continueToNextStep(); + }; + yield undefined; + + request = db.transaction("foo", "readwrite").objectStore("foo").add({}); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + isnot(event.target.result, firstKey, "Got a different key"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_clear_object_store_with_indexes.js b/dom/indexedDB/test/unit/test_clear_object_store_with_indexes.js new file mode 100644 index 0000000000..a6e15cc15c --- /dev/null +++ b/dom/indexedDB/test/unit/test_clear_object_store_with_indexes.js @@ -0,0 +1,206 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +const isInChaosMode = () => { + return !!parseInt(Services.env.get("MOZ_CHAOSMODE"), 16); +}; + +// Reduce the amount of data on slow platforms. +const getDataBlockSize = () => { + if (mozinfo.os == "android") { + // Android is much slower than desktop. + if (mozinfo.verify) { + return 54; // Chaos mode on android + } + + return 3333; + } + + if (isInChaosMode()) { + return 333; + } + + return 33333; +}; + +/* exported testSteps */ +async function testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const request = indexedDB.open(name, 1); + + (ev => { + const os = ev.target.result.createObjectStore("testObjectStore", { + keyPath: "id", + autoIncrement: false, + }); + + os.createIndex("testObjectStoreIndexA", "indexA", { unique: true }); + os.createIndex("testObjectStoreIndexB", "indexB", { unique: false }); + os.createIndex("testObjectStoreIndexC", "indexC", { unique: false }); + })(await expectingUpgrade(request)); + + const db = (await expectingSuccess(request)).target.result; + + const objectStore = db + .transaction(["testObjectStore"], "readwrite") + .objectStore("testObjectStore"); + + const dataBlock = getDataBlockSize(); + const lastIndex = 3 * dataBlock; + + info("We will now add " + lastIndex + " blobs to our object store"); + + const addSegment = async (from, dataValue) => { + for (let i = from; i <= from + dataBlock - 1; ++i) { + await objectStore.add({ + id: i, + indexA: i, + indexB: lastIndex + 1 - i, + indexC: i % 3, + value: dataValue, + }); + } + }; + + const expectedBegin = getRandomView(512); + const expectedMiddle = getRandomView(512); + const expectedEnd = getRandomView(512); + ok( + !compareBuffers(expectedBegin, expectedMiddle), + "Are all buffers different?" + ); + ok(!compareBuffers(expectedBegin, expectedEnd), "Are all buffers different?"); + ok( + !compareBuffers(expectedMiddle, expectedEnd), + "Are all buffers different?" + ); + + const dataValueBegin = getBlob(expectedBegin); + await addSegment(1, dataValueBegin); + + const dataValueMiddle = getBlob(expectedMiddle); + await addSegment(dataBlock + 1, dataValueMiddle); + + const dataValueEnd = getBlob(expectedEnd); + await addSegment(2 * dataBlock + 1, dataValueEnd); + + // Performance issue of 1860486 occurs here + await new Promise((res, rej) => { + let isDone = false; + const deleteReq = objectStore.delete( + IDBKeyRange.bound(6, lastIndex - 5, false, false) + ); + deleteReq.onsuccess = () => { + isDone = true; + res(); + }; + deleteReq.onerror = err => { + isDone = true; + rej(err); + }; + + /** + * The deletion should be over in 20 seconds or less on desktop. With the + * regression, the operation can take more than 30 minutes. We use one + * minute to reduce intermittent failures due to the CI environment. + * + * Note that this is not a magical timeout for the completion of an + * asynchronous request: we are testing a hang and using an explicit timeout + * will avoid the much longer default timeout which is way too long to be + * acceptable in real use cases. + * + * Maintenance plan: If disk contention and slow hardware lead to too many + * intermittent failures, the regression cutoff could be increased to 2-3 + * minutes or the test could be turned into a raptor performance test. + */ + const minutes = 60 * 1000; + const performance_regression_cutoff = 1 * minutes; + do_timeout(performance_regression_cutoff, () => { + if (!isDone) { + rej(Error("Performance regression detected")); + } + }); + }); + + const getIndexedItems = async indexName => { + let actuals = []; + return new Promise(res => { + db + .transaction(["testObjectStore"], "readonly") + .objectStore("testObjectStore") + .index(indexName) + .openCursor().onsuccess = ev => { + const cursor = ev.target.result; + if (!cursor) { + res(actuals); + } else { + actuals.push(cursor.value.value); + cursor.continue(); + } + }; + }); + }; + + const checkValuesEqualTo = async (actuals, from, to, expected) => { + for (let i = from; i < to; ++i) { + const actual = new Uint8Array(await actuals[i].arrayBuffer()); + if (!compareBuffers(actual, expected)) { + return i; + } + } + return undefined; + }; + + const itemsA = await getIndexedItems("testObjectStoreIndexA"); + equal(itemsA.length, 10); + + const mismatchABegin = await checkValuesEqualTo(itemsA, 0, 5, expectedBegin); + equal( + mismatchABegin, + undefined, + "First index with value mismatch is " + mismatchABegin + ); + const mismatchAEnd = await checkValuesEqualTo(itemsA, 5, 10, expectedEnd); + equal( + mismatchAEnd, + undefined, + "First index with value mismatch is " + mismatchAEnd + ); + + const itemsB = await getIndexedItems("testObjectStoreIndexB"); + + equal(itemsB.length, 10); + const mismatchBEnd = await checkValuesEqualTo(itemsB, 0, 5, expectedEnd); + equal( + mismatchBEnd, + undefined, + "First index with value mismatch is " + mismatchBEnd + ); + const mismatchBBegin = await checkValuesEqualTo(itemsB, 5, 10, expectedBegin); + equal( + mismatchBBegin, + undefined, + "First index with value mismatch is " + mismatchBBegin + ); + + const actualsC = await getIndexedItems("testObjectStoreIndexC"); + + equal(actualsC.length, 10); + let countBegin = 0; + let countEnd = 0; + for (let i = 0; i < 10; ++i) { + const actual = new Uint8Array(await actualsC[i].arrayBuffer()); + if (compareBuffers(actual, expectedBegin)) { + ++countBegin; + } else if (compareBuffers(actual, expectedEnd)) { + ++countEnd; + } + } + + equal(countBegin, 5); + equal(countEnd, 5); + + await db.close(); +} diff --git a/dom/indexedDB/test/unit/test_complex_keyPaths.js b/dom/indexedDB/test/unit/test_complex_keyPaths.js new file mode 100644 index 0000000000..87fd191d8f --- /dev/null +++ b/dom/indexedDB/test/unit/test_complex_keyPaths.js @@ -0,0 +1,329 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + // Test object stores + + const name = "test_complex_keyPaths"; + const keyPaths = [ + { keyPath: "id", value: { id: 5 }, key: 5 }, + { keyPath: "id", value: { id: "14", iid: 12 }, key: "14" }, + { keyPath: "id", value: { iid: "14", id: 12 }, key: 12 }, + { keyPath: "id", value: {} }, + { keyPath: "id", value: { id: {} } }, + { keyPath: "id", value: { id: /x/ } }, + { keyPath: "id", value: 2 }, + { keyPath: "id", value: undefined }, + { keyPath: "foo.id", value: { foo: { id: 7 } }, key: 7 }, + { keyPath: "foo.id", value: { id: 7, foo: { id: "asdf" } }, key: "asdf" }, + { keyPath: "foo.id", value: { foo: { id: undefined } } }, + { keyPath: "foo.id", value: { foo: 47 } }, + { keyPath: "foo.id", value: {} }, + { keyPath: "", value: "foopy", key: "foopy" }, + { keyPath: "", value: 2, key: 2 }, + { keyPath: "", value: undefined }, + { keyPath: "", value: { id: 12 } }, + { keyPath: "", value: /x/ }, + { + keyPath: "foo.bar", + value: { baz: 1, foo: { baz2: 2, bar: "xo" } }, + key: "xo", + }, + { + keyPath: "foo.bar.baz", + value: { foo: { bar: { bazz: 16, baz: 17 } } }, + key: 17, + }, + { keyPath: "foo..id", exception: true }, + { keyPath: "foo.", exception: true }, + { keyPath: "fo o", exception: true }, + { keyPath: "foo ", exception: true }, + { keyPath: "foo[bar]", exception: true }, + { keyPath: "foo[1]", exception: true }, + { keyPath: "$('id').stuff", exception: true }, + { keyPath: "foo.2.bar", exception: true }, + { keyPath: "foo. .bar", exception: true }, + { keyPath: ".bar", exception: true }, + { keyPath: [], exception: true }, + + { keyPath: ["foo", "bar"], value: { foo: 1, bar: 2 }, key: [1, 2] }, + { keyPath: ["foo"], value: { foo: 1, bar: 2 }, key: [1] }, + { + keyPath: ["foo", "bar", "bar"], + value: { foo: 1, bar: "x" }, + key: [1, "x", "x"], + }, + { keyPath: ["x", "y"], value: { x: [], y: "x" }, key: [[], "x"] }, + { keyPath: ["x", "y"], value: { x: [[1]], y: "x" }, key: [[[1]], "x"] }, + { + keyPath: ["x", "y"], + value: { x: [[1]], y: new Date(1) }, + key: [[[1]], new Date(1)], + }, + { + keyPath: ["x", "y"], + value: { x: [[1]], y: [new Date(3)] }, + key: [[[1]], [new Date(3)]], + }, + { + keyPath: ["x", "y.bar"], + value: { x: "hi", y: { bar: "x" } }, + key: ["hi", "x"], + }, + { + keyPath: ["x.y", "y.bar"], + value: { x: { y: "hello" }, y: { bar: "nurse" } }, + key: ["hello", "nurse"], + }, + { keyPath: ["", ""], value: 5, key: [5, 5] }, + { keyPath: ["x", "y"], value: { x: 1 } }, + { keyPath: ["x", "y"], value: { y: 1 } }, + { keyPath: ["x", "y"], value: { x: 1, y: undefined } }, + { keyPath: ["x", "y"], value: { x: null, y: 1 } }, + { keyPath: ["x", "y.bar"], value: { x: null, y: { bar: "x" } } }, + { keyPath: ["x", "y"], value: { x: 1, y: false } }, + { keyPath: ["x", "y", "z"], value: { x: 1, y: false, z: "a" } }, + { keyPath: [".x", "y", "z"], exception: true }, + { keyPath: ["x", "y ", "z"], exception: true }, + ]; + + let openRequest = indexedDB.open(name, 1); + openRequest.onerror = errorHandler; + openRequest.onupgradeneeded = grabEventAndContinueHandler; + openRequest.onsuccess = unexpectedSuccessHandler; + let event = yield undefined; + let db = event.target.result; + + let stores = {}; + + // Test creating object stores and inserting data + for (let i = 0; i < keyPaths.length; i++) { + let info = keyPaths[i]; + + let test = " for objectStore test " + JSON.stringify(info); + let indexName = JSON.stringify(info.keyPath); + if (!stores[indexName]) { + try { + let objectStore = db.createObjectStore(indexName, { + keyPath: info.keyPath, + }); + ok(!("exception" in info), "shouldn't throw" + test); + is( + JSON.stringify(objectStore.keyPath), + JSON.stringify(info.keyPath), + "correct keyPath property" + test + ); + ok( + // eslint-disable-next-line no-self-compare + objectStore.keyPath === objectStore.keyPath, + "object identity should be preserved" + ); + stores[indexName] = objectStore; + } catch (e) { + ok("exception" in info, "should throw" + test); + is(e.name, "SyntaxError", "expect a SyntaxError" + test); + ok(e instanceof DOMException, "Got a DOM Exception" + test); + is(e.code, DOMException.SYNTAX_ERR, "expect a syntax error" + test); + continue; + } + } + + let store = stores[indexName]; + + try { + var request = store.add(info.value); + ok("key" in info, "successfully created request to insert value" + test); + } catch (e) { + ok(!("key" in info), "threw when attempted to insert" + test); + ok(e instanceof DOMException, "Got a DOMException" + test); + is(e.name, "DataError", "expect a DataError" + test); + is(e.code, 0, "expect zero" + test); + continue; + } + + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + let e = yield undefined; + is(e.type, "success", "inserted successfully" + test); + is(e.target, request, "expected target" + test); + ok(compareKeys(request.result, info.key), "found correct key" + test); + is( + indexedDB.cmp(request.result, info.key), + 0, + "returned key compares correctly" + test + ); + + store.get(info.key).onsuccess = grabEventAndContinueHandler; + e = yield undefined; + isnot(e.target.result, undefined, "Did find entry"); + + // Check that cursor.update work as expected + request = store.openCursor(); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + e = yield undefined; + let cursor = e.target.result; + request = cursor.update(info.value); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + yield undefined; + ok(true, "Successfully updated cursor" + test); + + // Check that cursor.update throws as expected when key is changed + let newValue = cursor.value; + let destProp = Array.isArray(info.keyPath) ? info.keyPath[0] : info.keyPath; + if (destProp) { + let splitDestProp = destProp.split("."); + if (splitDestProp.length == 1) { + newValue[splitDestProp[0]] = "newKeyValue"; + } else if (splitDestProp.length == 2) { + newValue[splitDestProp[0]][splitDestProp[1]] = "newKeyValue"; + } else { + newValue[splitDestProp[0]][splitDestProp[1]][splitDestProp[2]] = + "newKeyValue"; + } + } else { + newValue = "newKeyValue"; + } + let didThrow; + try { + cursor.update(newValue); + } catch (ex) { + didThrow = ex; + } + ok(didThrow instanceof DOMException, "Got a DOMException" + test); + is(didThrow.name, "DataError", "expect a DataError" + test); + is(didThrow.code, 0, "expect zero" + test); + + // Clear object store to prepare for next test + store.clear().onsuccess = grabEventAndContinueHandler; + yield undefined; + } + + // Attempt to create indexes and insert data + let store = db.createObjectStore("indexStore"); + let indexes = {}; + for (let i = 0; i < keyPaths.length; i++) { + let info = keyPaths[i]; + let test = " for index test " + JSON.stringify(info); + let indexName = JSON.stringify(info.keyPath); + if (!indexes[indexName]) { + try { + let index = store.createIndex(indexName, info.keyPath); + ok(!("exception" in info), "shouldn't throw" + test); + is( + JSON.stringify(index.keyPath), + JSON.stringify(info.keyPath), + "index has correct keyPath property" + test + ); + ok( + // eslint-disable-next-line no-self-compare + index.keyPath === index.keyPath, + "object identity should be preserved" + ); + indexes[indexName] = index; + } catch (e) { + ok("exception" in info, "should throw" + test); + is(e.name, "SyntaxError", "expect a SyntaxError" + test); + ok(e instanceof DOMException, "Got a DOM Exception" + test); + is(e.code, DOMException.SYNTAX_ERR, "expect a syntax error" + test); + continue; + } + } + + let index = indexes[indexName]; + + request = store.add(info.value, 1); + if ("key" in info) { + index.getKey(info.key).onsuccess = grabEventAndContinueHandler; + let e = yield undefined; + is(e.target.result, 1, "found value when reading" + test); + } else { + index.count().onsuccess = grabEventAndContinueHandler; + let e = yield undefined; + is(e.target.result, 0, "should be empty" + test); + } + + store.clear().onsuccess = grabEventAndContinueHandler; + yield undefined; + } + + // Autoincrement and complex key paths + let aitests = [ + { v: {}, k: 1, res: { foo: { id: 1 } } }, + { v: { value: "x" }, k: 2, res: { value: "x", foo: { id: 2 } } }, + { v: { value: "x", foo: {} }, k: 3, res: { value: "x", foo: { id: 3 } } }, + { + v: { v: "x", foo: { x: "y" } }, + k: 4, + res: { v: "x", foo: { x: "y", id: 4 } }, + }, + { v: { value: 2, foo: { id: 10 } }, k: 10 }, + { v: { value: 2 }, k: 11, res: { value: 2, foo: { id: 11 } } }, + { v: true }, + { v: { value: 2, foo: 12 } }, + { v: { foo: { id: true } } }, + { v: { foo: { x: 5, id: {} } } }, + { v: undefined }, + { v: { foo: undefined } }, + { v: { foo: { id: undefined } } }, + { v: null }, + { v: { foo: null } }, + { v: { foo: { id: null } } }, + ]; + + store = db.createObjectStore("gen", { + keyPath: "foo.id", + autoIncrement: true, + }); + for (let i = 0; i < aitests.length; ++i) { + let info = aitests[i]; + let test = " for autoIncrement test " + JSON.stringify(info); + + let preValue = JSON.stringify(info.v); + if ("k" in info) { + store.add(info.v).onsuccess = grabEventAndContinueHandler; + is(JSON.stringify(info.v), preValue, "put didn't modify value" + test); + } else { + try { + store.add(info.v); + ok(false, "should throw" + test); + } catch (e) { + ok(true, "did throw" + test); + ok(e instanceof DOMException, "Got a DOMException" + test); + is(e.name, "DataError", "expect a DataError" + test); + is(e.code, 0, "expect zero" + test); + + is( + JSON.stringify(info.v), + preValue, + "failing put didn't modify value" + test + ); + + continue; + } + } + + let e = yield undefined; + is(e.target.result, info.k, "got correct return key" + test); + + store.get(info.k).onsuccess = grabEventAndContinueHandler; + e = yield undefined; + is( + JSON.stringify(e.target.result), + JSON.stringify(info.res || info.v), + "expected value stored" + test + ); + } + + openRequest.onsuccess = grabEventAndContinueHandler; + yield undefined; + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_constraint_error_messages.js b/dom/indexedDB/test/unit/test_constraint_error_messages.js new file mode 100644 index 0000000000..b77431e71a --- /dev/null +++ b/dom/indexedDB/test/unit/test_constraint_error_messages.js @@ -0,0 +1,64 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testSteps */ +async function testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const objectStoreName = "foo"; + const indexName = "bar", + keyPath = "bar"; + + info("Opening database"); + + let request = indexedDB.open(name); + let event = await expectingUpgrade(request); + + let db = event.target.result; + + info("Creating objectStore"); + + let objectStore = db.createObjectStore(objectStoreName); + + info("Creating a duplicated object store to get an error"); + + try { + db.createObjectStore(objectStoreName); + ok( + false, + "ConstraintError should be thrown if object store already exists" + ); + } catch (e) { + ok(true, "ConstraintError should be thrown if object store already exists"); + is( + e.message, + "IDBDatabase.createObjectStore: Object store named '" + + objectStoreName + + "' already exists at index '0'", + "Threw with correct error message" + ); + } + + info("Creating an index"); + + objectStore.createIndex(indexName, keyPath); + + info("Creating a duplicated indexes to verify the error message"); + + try { + objectStore.createIndex(indexName, keyPath); + + ok(false, "ConstraintError should be thrown if index already exists"); + } catch (e) { + ok(true, "ConstraintError should be thrown if index already exists"); + is( + e.message, + `IDBObjectStore.createIndex: Index named '${indexName}' already exists at index '0'`, + "Threw with correct error message" + ); + } + + await expectingSuccess(request); + db.close(); +} diff --git a/dom/indexedDB/test/unit/test_count.js b/dom/indexedDB/test/unit/test_count.js new file mode 100644 index 0000000000..c2a756c52f --- /dev/null +++ b/dom/indexedDB/test/unit/test_count.js @@ -0,0 +1,507 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const objectStoreName = "People"; + + const objectStoreData = [ + { key: "237-23-7732", value: { name: "Bob", height: 60, weight: 120 } }, + { key: "237-23-7733", value: { name: "Ann", height: 52, weight: 110 } }, + { key: "237-23-7734", value: { name: "Ron", height: 73, weight: 180 } }, + { key: "237-23-7735", value: { name: "Sue", height: 58, weight: 130 } }, + { key: "237-23-7736", value: { name: "Joe", height: 65, weight: 150 } }, + { key: "237-23-7737", value: { name: "Pat", height: 65 } }, + { key: "237-23-7738", value: { name: "Mel", height: 66, weight: {} } }, + { key: "237-23-7739", value: { name: "Tom", height: 62, weight: 130 } }, + ]; + + const indexData = { + name: "weight", + keyPath: "weight", + options: { unique: false }, + }; + + const weightSort = [1, 0, 3, 7, 4, 2]; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + is(event.type, "upgradeneeded", "Got correct event type"); + + let db = event.target.result; + db.onerror = errorHandler; + + let objectStore = db.createObjectStore(objectStoreName, {}); + objectStore.createIndex(indexData.name, indexData.keyPath, indexData.options); + + for (let data of objectStoreData) { + objectStore.add(data.value, data.key); + } + + event = yield undefined; + + is(event.type, "success", "Got correct event type"); + + objectStore = db + .transaction(db.objectStoreNames) + .objectStore(objectStoreName); + + objectStore.count().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + objectStoreData.length, + "Correct number of object store entries for all keys" + ); + + objectStore.count(null).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + objectStoreData.length, + "Correct number of object store entries for null key" + ); + + objectStore.count(objectStoreData[2].key).onsuccess = + grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + 1, + "Correct number of object store entries for single existing key" + ); + + objectStore.count("foo").onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + 0, + "Correct number of object store entries for single non-existing key" + ); + + let keyRange = IDBKeyRange.only(objectStoreData[2].key); + objectStore.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + 1, + "Correct number of object store entries for existing only keyRange" + ); + + keyRange = IDBKeyRange.only("foo"); + objectStore.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + 0, + "Correct number of object store entries for non-existing only keyRange" + ); + + keyRange = IDBKeyRange.lowerBound(objectStoreData[2].key); + objectStore.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + objectStoreData.length - 2, + "Correct number of object store entries for lowerBound keyRange" + ); + + keyRange = IDBKeyRange.lowerBound(objectStoreData[2].key, true); + objectStore.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + objectStoreData.length - 3, + "Correct number of object store entries for lowerBound keyRange" + ); + + keyRange = IDBKeyRange.lowerBound("foo"); + objectStore.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + 0, + "Correct number of object store entries for lowerBound keyRange" + ); + + keyRange = IDBKeyRange.upperBound(objectStoreData[2].key, false); + objectStore.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + 3, + "Correct number of object store entries for upperBound keyRange" + ); + + keyRange = IDBKeyRange.upperBound(objectStoreData[2].key, true); + objectStore.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + 2, + "Correct number of object store entries for upperBound keyRange" + ); + + keyRange = IDBKeyRange.upperBound("foo", true); + objectStore.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + objectStoreData.length, + "Correct number of object store entries for upperBound keyRange" + ); + + keyRange = IDBKeyRange.bound( + objectStoreData[0].key, + objectStoreData[objectStoreData.length - 1].key + ); + objectStore.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + objectStoreData.length, + "Correct number of object store entries for bound keyRange" + ); + + keyRange = IDBKeyRange.bound( + objectStoreData[0].key, + objectStoreData[objectStoreData.length - 1].key, + true + ); + objectStore.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + objectStoreData.length - 1, + "Correct number of object store entries for bound keyRange" + ); + + keyRange = IDBKeyRange.bound( + objectStoreData[0].key, + objectStoreData[objectStoreData.length - 1].key, + true, + true + ); + objectStore.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + objectStoreData.length - 2, + "Correct number of object store entries for bound keyRange" + ); + + keyRange = IDBKeyRange.bound("foo", "foopy", true, true); + objectStore.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + 0, + "Correct number of object store entries for bound keyRange" + ); + + keyRange = IDBKeyRange.bound(objectStoreData[0].key, "foo", true, true); + objectStore.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + objectStoreData.length - 1, + "Correct number of object store entries for bound keyRange" + ); + + let index = objectStore.index(indexData.name); + + index.count().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + weightSort.length, + "Correct number of index entries for no key" + ); + + index.count(objectStoreData[7].value.weight).onsuccess = + grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + 2, + "Correct number of index entries for duplicate key" + ); + + index.count(objectStoreData[0].value.weight).onsuccess = + grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, 1, "Correct number of index entries for single key"); + + keyRange = IDBKeyRange.only(objectStoreData[0].value.weight); + index.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + 1, + "Correct number of index entries for only existing keyRange" + ); + + keyRange = IDBKeyRange.only("foo"); + index.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + 0, + "Correct number of index entries for only non-existing keyRange" + ); + + keyRange = IDBKeyRange.only(objectStoreData[7].value.weight); + index.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + 2, + "Correct number of index entries for only duplicate keyRange" + ); + + keyRange = IDBKeyRange.lowerBound( + objectStoreData[weightSort[0]].value.weight + ); + index.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + weightSort.length, + "Correct number of index entries for lowerBound keyRange" + ); + + keyRange = IDBKeyRange.lowerBound( + objectStoreData[weightSort[1]].value.weight + ); + index.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + weightSort.length - 1, + "Correct number of index entries for lowerBound keyRange" + ); + + keyRange = IDBKeyRange.lowerBound( + objectStoreData[weightSort[0]].value.weight - 1 + ); + index.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + weightSort.length, + "Correct number of index entries for lowerBound keyRange" + ); + + keyRange = IDBKeyRange.lowerBound( + objectStoreData[weightSort[0]].value.weight, + true + ); + index.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + weightSort.length - 1, + "Correct number of index entries for lowerBound keyRange" + ); + + keyRange = IDBKeyRange.lowerBound( + objectStoreData[weightSort[weightSort.length - 1]].value.weight + ); + index.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + 1, + "Correct number of index entries for lowerBound keyRange" + ); + + keyRange = IDBKeyRange.lowerBound( + objectStoreData[weightSort[weightSort.length - 1]].value.weight, + true + ); + index.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + 0, + "Correct number of index entries for lowerBound keyRange" + ); + + keyRange = IDBKeyRange.lowerBound( + objectStoreData[weightSort[weightSort.length - 1]].value.weight + 1, + true + ); + index.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + 0, + "Correct number of index entries for lowerBound keyRange" + ); + + keyRange = IDBKeyRange.upperBound( + objectStoreData[weightSort[0]].value.weight + ); + index.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + 1, + "Correct number of index entries for upperBound keyRange" + ); + + keyRange = IDBKeyRange.upperBound( + objectStoreData[weightSort[0]].value.weight, + true + ); + index.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + 0, + "Correct number of index entries for upperBound keyRange" + ); + + keyRange = IDBKeyRange.upperBound( + objectStoreData[weightSort[weightSort.length - 1]].value.weight + ); + index.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + weightSort.length, + "Correct number of index entries for upperBound keyRange" + ); + + keyRange = IDBKeyRange.upperBound( + objectStoreData[weightSort[weightSort.length - 1]].value.weight, + true + ); + index.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + weightSort.length - 1, + "Correct number of index entries for upperBound keyRange" + ); + + keyRange = IDBKeyRange.upperBound( + objectStoreData[weightSort[weightSort.length - 1]].value.weight, + true + ); + index.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + weightSort.length - 1, + "Correct number of index entries for upperBound keyRange" + ); + + keyRange = IDBKeyRange.upperBound("foo"); + index.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + weightSort.length, + "Correct number of index entries for upperBound keyRange" + ); + + keyRange = IDBKeyRange.bound("foo", "foopy"); + index.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + 0, + "Correct number of index entries for bound keyRange" + ); + + keyRange = IDBKeyRange.bound( + objectStoreData[weightSort[0]].value.weight, + objectStoreData[weightSort[weightSort.length - 1]].value.weight + ); + index.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + weightSort.length, + "Correct number of index entries for bound keyRange" + ); + + keyRange = IDBKeyRange.bound( + objectStoreData[weightSort[0]].value.weight, + objectStoreData[weightSort[weightSort.length - 1]].value.weight, + true + ); + index.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + weightSort.length - 1, + "Correct number of index entries for bound keyRange" + ); + + keyRange = IDBKeyRange.bound( + objectStoreData[weightSort[0]].value.weight, + objectStoreData[weightSort[weightSort.length - 1]].value.weight, + true, + true + ); + index.count(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + weightSort.length - 2, + "Correct number of index entries for bound keyRange" + ); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_create_index.js b/dom/indexedDB/test/unit/test_create_index.js new file mode 100644 index 0000000000..a925bd79d6 --- /dev/null +++ b/dom/indexedDB/test/unit/test_create_index.js @@ -0,0 +1,127 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const objectStoreInfo = [ + { name: "a", options: { keyPath: "id", autoIncrement: true } }, + { name: "b", options: { keyPath: "id", autoIncrement: false } }, + ]; + const indexInfo = [ + { name: "1", keyPath: "unique_value", options: { unique: true } }, + { name: "2", keyPath: "value", options: { unique: false } }, + { name: "3", keyPath: "value", options: { unique: false } }, + { name: "", keyPath: "value", options: { unique: false } }, + { name: null, keyPath: "value", options: { unique: false } }, + { name: undefined, keyPath: "value", options: { unique: false } }, + ]; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + let event = yield undefined; + let db = event.target.result; + + for (let i = 0; i < objectStoreInfo.length; i++) { + let info = objectStoreInfo[i]; + let objectStore = info.hasOwnProperty("options") + ? db.createObjectStore(info.name, info.options) + : db.createObjectStore(info.name); + + try { + request = objectStore.createIndex("Hola"); + ok(false, "createIndex with no keyPath should throw"); + } catch (e) { + ok(true, "createIndex with no keyPath should throw"); + } + + let ex; + try { + objectStore.createIndex("Hola", ["foo"], { multiEntry: true }); + } catch (e) { + ex = e; + } + ok(ex, "createIndex with array keyPath and multiEntry should throw"); + is(ex.name, "InvalidAccessError", "should throw right exception"); + ok(ex instanceof DOMException, "should throw right exception"); + is( + ex.code, + DOMException.INVALID_ACCESS_ERR, + "should throw right exception" + ); + + try { + objectStore.createIndex("foo", "bar", 10); + ok(false, "createIndex with bad options should throw"); + } catch (e) { + ok(true, "createIndex with bad options threw"); + } + + ok( + objectStore.createIndex("foo", "bar", { foo: "" }), + "createIndex with unknown options should not throw" + ); + objectStore.deleteIndex("foo"); + + // Test index creation, and that it ends up in indexNames. + let objectStoreName = info.name; + for (let j = 0; j < indexInfo.length; j++) { + let info = indexInfo[j]; + let count = objectStore.indexNames.length; + let index = info.hasOwnProperty("options") + ? objectStore.createIndex(info.name, info.keyPath, info.options) + : objectStore.createIndex(info.name, info.keyPath); + + let name = info.name; + if (name === null) { + name = "null"; + } else if (name === undefined) { + name = "undefined"; + } + + is(index.name, name, "correct name"); + is(index.keyPath, info.keyPath, "correct keyPath"); + is(index.unique, info.options.unique, "correct uniqueness"); + + is(objectStore.indexNames.length, count + 1, "indexNames grew in size"); + let found = false; + for (let k = 0; k < objectStore.indexNames.length; k++) { + if (objectStore.indexNames.item(k) == name) { + found = true; + break; + } + } + ok(found, "Name is on objectStore.indexNames"); + + ok(event.target.transaction, "event has a transaction"); + ok(event.target.transaction.db === db, "transaction has the right db"); + is( + event.target.transaction.mode, + "versionchange", + "transaction has the correct mode" + ); + is( + event.target.transaction.objectStoreNames.length, + i + 1, + "transaction only has one object store" + ); + ok( + event.target.transaction.objectStoreNames.contains(objectStoreName), + "transaction has the correct object store" + ); + } + } + + request.onsuccess = grabEventAndContinueHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + + event = yield undefined; + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_create_index_with_integer_keys.js b/dom/indexedDB/test/unit/test_create_index_with_integer_keys.js new file mode 100644 index 0000000000..5af2873ae6 --- /dev/null +++ b/dom/indexedDB/test/unit/test_create_index_with_integer_keys.js @@ -0,0 +1,74 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const data = { + id: new Date().getTime(), + num: parseInt(Math.random() * 1000), + }; + + let request = indexedDB.open( + this.window ? window.location.pathname : "Splendid Test", + 1 + ); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + db.onerror = errorHandler; + + event.target.onsuccess = continueToNextStep; + + // Make object store, add data. + let objectStore = db.createObjectStore("foo", { keyPath: "id" }); + objectStore.add(data); + yield undefined; + db.close(); + + request = indexedDB.open( + this.window ? window.location.pathname : "Splendid Test", + 2 + ); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + event = yield undefined; + + let db2 = event.target.result; + db2.onerror = errorHandler; + + event.target.onsuccess = continueToNextStep; + + // Create index. + event.target.transaction.objectStore("foo").createIndex("foo", "num"); + yield undefined; + + // Make sure our object made it into the index. + let seenCount = 0; + + db2 + .transaction("foo") + .objectStore("foo") + .index("foo") + .openKeyCursor().onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is(cursor.key, data.num, "Good key"); + is(cursor.primaryKey, data.id, "Good value"); + seenCount++; + cursor.continue(); + } else { + continueToNextStep(); + } + }; + yield undefined; + + is(seenCount, 1, "Saw our entry"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_create_locale_aware_index.js b/dom/indexedDB/test/unit/test_create_locale_aware_index.js new file mode 100644 index 0000000000..df85de3187 --- /dev/null +++ b/dom/indexedDB/test/unit/test_create_locale_aware_index.js @@ -0,0 +1,153 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const objectStoreInfo = [ + { name: "a", options: { keyPath: "id", autoIncrement: true } }, + { name: "b", options: { keyPath: "id", autoIncrement: false } }, + ]; + const indexInfo = [ + { + name: "1", + keyPath: "unique_value", + options: { unique: true, locale: "es-ES" }, + }, + { + name: "2", + keyPath: "unique_value", + options: { unique: true, locale: null }, + }, + { + name: "3", + keyPath: "value", + options: { unique: false, locale: "es-ES" }, + }, + { + name: "4", + keyPath: "value", + options: { unique: false, locale: "es-ES" }, + }, + { name: "", keyPath: "value", options: { unique: false, locale: "es-ES" } }, + { + name: null, + keyPath: "value", + options: { unique: false, locale: "es-ES" }, + }, + { + name: undefined, + keyPath: "value", + options: { unique: false, locale: "es-ES" }, + }, + ]; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + let event = yield undefined; + let db = event.target.result; + + for (let i = 0; i < objectStoreInfo.length; i++) { + let info = objectStoreInfo[i]; + let objectStore = info.hasOwnProperty("options") + ? db.createObjectStore(info.name, info.options) + : db.createObjectStore(info.name); + + try { + request = objectStore.createIndex("Hola"); + ok(false, "createIndex with no keyPath should throw"); + } catch (e) { + ok(true, "createIndex with no keyPath should throw"); + } + + let ex; + try { + objectStore.createIndex("Hola", ["foo"], { multiEntry: true }); + } catch (e) { + ex = e; + } + ok(ex, "createIndex with array keyPath and multiEntry should throw"); + is(ex.name, "InvalidAccessError", "should throw right exception"); + ok(ex instanceof DOMException, "should throw right exception"); + is( + ex.code, + DOMException.INVALID_ACCESS_ERR, + "should throw right exception" + ); + + try { + objectStore.createIndex("foo", "bar", 10); + ok(false, "createIndex with bad options should throw"); + } catch (e) { + ok(true, "createIndex with bad options threw"); + } + + ok( + objectStore.createIndex("foo", "bar", { foo: "" }), + "createIndex with unknown options should not throw" + ); + objectStore.deleteIndex("foo"); + + // Test index creation, and that it ends up in indexNames. + let objectStoreName = info.name; + for (let j = 0; j < indexInfo.length; j++) { + let info = indexInfo[j]; + let count = objectStore.indexNames.length; + let index = info.hasOwnProperty("options") + ? objectStore.createIndex(info.name, info.keyPath, info.options) + : objectStore.createIndex(info.name, info.keyPath); + + let name = info.name; + if (name === null) { + name = "null"; + } else if (name === undefined) { + name = "undefined"; + } + + is(index.name, name, "correct name"); + is(index.keyPath, info.keyPath, "correct keyPath"); + is(index.unique, info.options.unique, "correct uniqueness"); + is(index.locale, info.options.locale, "correct locale"); + + is(objectStore.indexNames.length, count + 1, "indexNames grew in size"); + let found = false; + for (let k = 0; k < objectStore.indexNames.length; k++) { + if (objectStore.indexNames.item(k) == name) { + found = true; + break; + } + } + ok(found, "Name is on objectStore.indexNames"); + + ok(event.target.transaction, "event has a transaction"); + ok(event.target.transaction.db === db, "transaction has the right db"); + is( + event.target.transaction.mode, + "versionchange", + "transaction has the correct mode" + ); + is( + event.target.transaction.objectStoreNames.length, + i + 1, + "transaction only has one object store" + ); + ok( + event.target.transaction.objectStoreNames.contains(objectStoreName), + "transaction has the correct object store" + ); + } + } + + request.onsuccess = grabEventAndContinueHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + + event = yield undefined; + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_create_objectStore.js b/dom/indexedDB/test/unit/test_create_objectStore.js new file mode 100644 index 0000000000..fcdfb8642e --- /dev/null +++ b/dom/indexedDB/test/unit/test_create_objectStore.js @@ -0,0 +1,137 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const objectStoreInfo = [ + { name: "1", options: { keyPath: null } }, + { name: "2", options: { keyPath: null, autoIncrement: true } }, + { name: "3", options: { keyPath: null, autoIncrement: false } }, + { name: "4", options: { keyPath: null } }, + { name: "5", options: { keyPath: "foo" } }, + { name: "6" }, + { name: "7", options: null }, + { name: "8", options: { autoIncrement: true } }, + { name: "9", options: { autoIncrement: false } }, + { name: "10", options: { keyPath: "foo", autoIncrement: false } }, + { name: "11", options: { keyPath: "foo", autoIncrement: true } }, + { name: "" }, + { name: null }, + { name: undefined }, + ]; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + let event = yield undefined; + + let db = event.target.result; + + let count = db.objectStoreNames.length; + is(count, 0, "correct objectStoreNames length"); + + try { + db.createObjectStore("foo", "bar"); + ok(false, "createObjectStore with bad options should throw"); + } catch (e) { + ok(true, "createObjectStore with bad options"); + } + + ok( + db.createObjectStore("foo", { foo: "" }), + "createObjectStore with unknown options should not throw" + ); + db.deleteObjectStore("foo"); + + for (let index in objectStoreInfo) { + index = parseInt(index); + const info = objectStoreInfo[index]; + + let objectStore = info.hasOwnProperty("options") + ? db.createObjectStore(info.name, info.options) + : db.createObjectStore(info.name); + + is(db.objectStoreNames.length, index + 1, "updated objectStoreNames list"); + + let name = info.name; + if (name === null) { + name = "null"; + } else if (name === undefined) { + name = "undefined"; + } + + let found = false; + for (let i = 0; i <= index; i++) { + if (db.objectStoreNames.item(i) == name) { + found = true; + break; + } + } + is(found, true, "objectStoreNames contains name"); + + is(objectStore.name, name, "Bad name"); + is( + objectStore.keyPath, + info.options && info.options.keyPath ? info.options.keyPath : null, + "Bad keyPath" + ); + is(objectStore.indexNames.length, 0, "Bad indexNames"); + + ok(event.target.transaction, "event has a transaction"); + ok(event.target.transaction.db === db, "transaction has the right db"); + is( + event.target.transaction.mode, + "versionchange", + "transaction has the correct mode" + ); + is( + event.target.transaction.objectStoreNames.length, + index + 1, + "transaction has correct objectStoreNames list" + ); + found = false; + for (let j = 0; j < event.target.transaction.objectStoreNames.length; j++) { + if (event.target.transaction.objectStoreNames.item(j) == name) { + found = true; + break; + } + } + is(found, true, "transaction has correct objectStoreNames list"); + } + + // Can't handle autoincrement and empty keypath + let ex; + try { + db.createObjectStore("storefail", { keyPath: "", autoIncrement: true }); + } catch (e) { + ex = e; + } + ok(ex, "createObjectStore with empty keyPath and autoIncrement should throw"); + is(ex.name, "InvalidAccessError", "should throw right exception"); + ok(ex instanceof DOMException, "should throw right exception"); + is(ex.code, DOMException.INVALID_ACCESS_ERR, "should throw right exception"); + + // Can't handle autoincrement and array keypath + try { + db.createObjectStore("storefail", { keyPath: ["a"], autoIncrement: true }); + } catch (e) { + ex = e; + } + ok(ex, "createObjectStore with array keyPath and autoIncrement should throw"); + is(ex.name, "InvalidAccessError", "should throw right exception"); + ok(ex instanceof DOMException, "should throw right exception"); + is(ex.code, DOMException.INVALID_ACCESS_ERR, "should throw right exception"); + + request.onsuccess = grabEventAndContinueHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + + event = yield undefined; + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_cursor_cycle.js b/dom/indexedDB/test/unit/test_cursor_cycle.js new file mode 100644 index 0000000000..09099387f3 --- /dev/null +++ b/dom/indexedDB/test/unit/test_cursor_cycle.js @@ -0,0 +1,48 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const Bob = { ss: "237-23-7732", name: "Bob" }; + + let request = indexedDB.open( + this.window ? window.location.pathname : "Splendid Test", + 1 + ); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + event.target.onsuccess = continueToNextStep; + + let objectStore = db.createObjectStore("foo", { keyPath: "ss" }); + objectStore.createIndex("name", "name", { unique: true }); + objectStore.add(Bob); + yield undefined; + + db + .transaction("foo", "readwrite") + .objectStore("foo") + .index("name") + .openCursor().onsuccess = function (event) { + event.target.transaction.oncomplete = continueToNextStep; + let cursor = event.target.result; + if (cursor) { + let objectStore = event.target.transaction.objectStore("foo"); + objectStore.delete(Bob.ss).onsuccess = function (event) { + cursor.continue(); + }; + } + }; + yield undefined; + finishTest(); + + objectStore = null; // Bug 943409 workaround. + + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_cursor_mutation.js b/dom/indexedDB/test/unit/test_cursor_mutation.js new file mode 100644 index 0000000000..6af7df5c9b --- /dev/null +++ b/dom/indexedDB/test/unit/test_cursor_mutation.js @@ -0,0 +1,125 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const objectStoreData = [ + // This one will be removed. + { ss: "237-23-7732", name: "Bob" }, + + // These will always be included. + { ss: "237-23-7733", name: "Ann" }, + { ss: "237-23-7734", name: "Ron" }, + { ss: "237-23-7735", name: "Sue" }, + { ss: "237-23-7736", name: "Joe" }, + + // This one will be added. + { ss: "237-23-7737", name: "Pat" }, + ]; + + // Post-add and post-remove data ordered by name. + const objectStoreDataNameSort = [1, 4, 5, 2, 3]; + + let request = indexedDB.open( + this.window ? window.location.pathname : "Splendid Test", + 1 + ); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + event.target.onsuccess = continueToNextStep; + + let objectStore = db.createObjectStore("foo", { keyPath: "ss" }); + objectStore.createIndex("name", "name", { unique: true }); + + for (let i = 0; i < objectStoreData.length - 1; i++) { + objectStore.add(objectStoreData[i]); + } + yield undefined; + + let count = 0; + + let sawAdded = false; + let sawRemoved = false; + + db.transaction("foo").objectStore("foo").openCursor().onsuccess = function ( + event + ) { + event.target.transaction.oncomplete = continueToNextStep; + let cursor = event.target.result; + if (cursor) { + if (cursor.value.name == objectStoreData[0].name) { + sawRemoved = true; + } + if ( + cursor.value.name == objectStoreData[objectStoreData.length - 1].name + ) { + sawAdded = true; + } + cursor.continue(); + count++; + } + }; + yield undefined; + + is(count, objectStoreData.length - 1, "Good initial count"); + is(sawAdded, false, "Didn't see item that is about to be added"); + is(sawRemoved, true, "Saw item that is about to be removed"); + + count = 0; + sawAdded = false; + sawRemoved = false; + + db + .transaction("foo", "readwrite") + .objectStore("foo") + .index("name") + .openCursor().onsuccess = function (event) { + event.target.transaction.oncomplete = continueToNextStep; + let cursor = event.target.result; + if (cursor) { + if (cursor.value.name == objectStoreData[0].name) { + sawRemoved = true; + } + if ( + cursor.value.name == objectStoreData[objectStoreData.length - 1].name + ) { + sawAdded = true; + } + + is( + cursor.value.name, + objectStoreData[objectStoreDataNameSort[count++]].name, + "Correct name" + ); + + if (count == 1) { + let objectStore = event.target.transaction.objectStore("foo"); + objectStore.delete(objectStoreData[0].ss).onsuccess = function (event) { + objectStore.add( + objectStoreData[objectStoreData.length - 1] + ).onsuccess = function (event) { + cursor.continue(); + }; + }; + } else { + cursor.continue(); + } + } + }; + yield undefined; + + is(count, objectStoreData.length - 1, "Good final count"); + is(sawAdded, true, "Saw item that was added"); + is(sawRemoved, false, "Didn't see item that was removed"); + + finishTest(); + + objectStore = null; // Bug 943409 workaround. +} diff --git a/dom/indexedDB/test/unit/test_cursor_update_updates_indexes.js b/dom/indexedDB/test/unit/test_cursor_update_updates_indexes.js new file mode 100644 index 0000000000..338ea7f3a5 --- /dev/null +++ b/dom/indexedDB/test/unit/test_cursor_update_updates_indexes.js @@ -0,0 +1,118 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const START_DATA = "hi"; + const END_DATA = "bye"; + const objectStoreInfo = [ + { + name: "1", + options: { keyPath: null }, + key: 1, + entry: { data: START_DATA }, + }, + { + name: "2", + options: { keyPath: "foo" }, + entry: { foo: 1, data: START_DATA }, + }, + { + name: "3", + options: { keyPath: null, autoIncrement: true }, + entry: { data: START_DATA }, + }, + { + name: "4", + options: { keyPath: "foo", autoIncrement: true }, + entry: { data: START_DATA }, + }, + ]; + + for (let i = 0; i < objectStoreInfo.length; i++) { + // Create our object stores. + let info = objectStoreInfo[i]; + + ok(true, "1"); + let request = indexedDB.open(name, i + 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + + ok(true, "2"); + let objectStore = info.hasOwnProperty("options") + ? db.createObjectStore(info.name, info.options) + : db.createObjectStore(info.name); + + // Create the indexes on 'data' on the object store. + let index = objectStore.createIndex("data_index", "data", { + unique: false, + }); + let uniqueIndex = objectStore.createIndex("unique_data_index", "data", { + unique: true, + }); + // Populate the object store with one entry of data. + request = info.hasOwnProperty("key") + ? objectStore.add(info.entry, info.key) + : objectStore.add(info.entry); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + ok(true, "3"); + + // Use a cursor to update 'data' to END_DATA. + request = objectStore.openCursor(); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + ok(true, "4"); + + let cursor = request.result; + let obj = cursor.value; + obj.data = END_DATA; + request = cursor.update(obj); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + ok(true, "5"); + + // Check both indexes to make sure that they were updated. + request = index.get(END_DATA); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + ok(true, "6"); + is( + obj.data, + event.target.result.data, + "Non-unique index was properly updated." + ); + + request = uniqueIndex.get(END_DATA); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + ok(true, "7"); + is( + obj.data, + event.target.result.data, + "Unique index was properly updated." + ); + + // Wait for success + yield undefined; + + db.close(); + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_cursors.js b/dom/indexedDB/test/unit/test_cursors.js new file mode 100644 index 0000000000..15e3d94355 --- /dev/null +++ b/dom/indexedDB/test/unit/test_cursors.js @@ -0,0 +1,357 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + function checkCursor(cursor, expectedKey) { + is(cursor.key, expectedKey, "Correct key"); + is(cursor.primaryKey, expectedKey, "Correct primary key"); + is(cursor.value, "foo", "Correct value"); + } + + const name = this.window ? window.location.pathname : "Splendid Test"; + const keys = [1, -1, 0, 10, 2000, "q", "z", "two", "b", "a"]; + const sortedKeys = [-1, 0, 1, 10, 2000, "a", "b", "q", "two", "z"]; + + is(keys.length, sortedKeys.length, "Good key setup"); + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + + let objectStore = db.createObjectStore("autoIncrement", { + autoIncrement: true, + }); + + request = objectStore.openCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + ok(!event.target.result, "No results"); + testGenerator.next(); + }; + yield undefined; + + objectStore = db.createObjectStore("autoIncrementKeyPath", { + keyPath: "foo", + autoIncrement: true, + }); + + request = objectStore.openCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + ok(!event.target.result, "No results"); + testGenerator.next(); + }; + yield undefined; + + objectStore = db.createObjectStore("keyPath", { keyPath: "foo" }); + + request = objectStore.openCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + ok(!event.target.result, "No results"); + testGenerator.next(); + }; + yield undefined; + + objectStore = db.createObjectStore("foo"); + + request = objectStore.openCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + ok(!event.target.result, "No results"); + testGenerator.next(); + }; + yield undefined; + + let keyIndex = 0; + + for (let i in keys) { + request = objectStore.add("foo", keys[i]); + request.onerror = errorHandler; + request.onsuccess = function (event) { + if (++keyIndex == keys.length) { + testGenerator.next(); + } + }; + } + yield undefined; + + keyIndex = 0; + + request = objectStore.openCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + checkCursor(cursor, sortedKeys[keyIndex]); + + cursor.continue(); + + try { + cursor.continue(); + ok(false, "continue twice should throw"); + } catch (e) { + ok(e instanceof DOMException, "got a database exception"); + is(e.name, "InvalidStateError", "correct error"); + is(e.code, DOMException.INVALID_STATE_ERR, "correct code"); + } + + checkCursor(cursor, sortedKeys[keyIndex]); + + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, keys.length, "Saw all added items"); + + keyIndex = 4; + + let range = IDBKeyRange.bound(2000, "q"); + request = objectStore.openCursor(range); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + checkCursor(cursor, sortedKeys[keyIndex]); + + cursor.continue(); + + checkCursor(cursor, sortedKeys[keyIndex]); + + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, 8, "Saw all the expected keys"); + + keyIndex = 0; + + request = objectStore.openCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + checkCursor(cursor, sortedKeys[keyIndex]); + + if (keyIndex) { + cursor.continue(); + } else { + cursor.continue("b"); + } + + checkCursor(cursor, sortedKeys[keyIndex]); + + keyIndex += keyIndex ? 1 : 6; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, keys.length, "Saw all the expected keys"); + + keyIndex = 0; + + request = objectStore.openCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + checkCursor(cursor, sortedKeys[keyIndex]); + + if (keyIndex) { + cursor.continue(); + } else { + cursor.continue(10); + } + + checkCursor(cursor, sortedKeys[keyIndex]); + + keyIndex += keyIndex ? 1 : 3; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, keys.length, "Saw all the expected keys"); + + keyIndex = 0; + + request = objectStore.openCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + checkCursor(cursor, sortedKeys[keyIndex]); + + if (keyIndex) { + cursor.continue(); + } else { + cursor.continue("c"); + } + + checkCursor(cursor, sortedKeys[keyIndex]); + + keyIndex += keyIndex ? 1 : 7; + } else { + ok(cursor === null, "The request result should be null."); + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, keys.length, "Saw all the expected keys"); + + keyIndex = 0; + + request = objectStore.openCursor(); + request.onerror = errorHandler; + let storedCursor = null; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + storedCursor = cursor; + + checkCursor(cursor, sortedKeys[keyIndex]); + + if (keyIndex == 4) { + request = cursor.update("bar"); + request.onerror = errorHandler; + request.onsuccess = function (event) { + keyIndex++; + cursor.continue(); + }; + } else { + keyIndex++; + cursor.continue(); + } + } else { + ok(cursor === null, "The request result should be null."); + ok( + storedCursor.value === undefined, + "The cursor's value should be undefined." + ); + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, keys.length, "Saw all the expected keys"); + + request = objectStore.get(sortedKeys[4]); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, "bar", "Update succeeded"); + + request = objectStore.put("foo", sortedKeys[4]); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + keyIndex = 0; + + let gotRemoveEvent = false; + + request = objectStore.openCursor(null, "next"); + request.onerror = errorHandler; + storedCursor = null; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + storedCursor = cursor; + + checkCursor(cursor, sortedKeys[keyIndex]); + + if (keyIndex == 4) { + request = cursor.delete(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + ok(event.target.result === undefined, "Should be undefined"); + is(keyIndex, 5, "Got result of delete before next continue"); + gotRemoveEvent = true; + }; + } + + keyIndex++; + cursor.continue(); + } else { + ok(cursor === null, "The request result should be null."); + ok( + storedCursor.value === undefined, + "The cursor's value should be undefined." + ); + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, keys.length, "Saw all the expected keys"); + is(gotRemoveEvent, true, "Saw the remove event"); + + request = objectStore.get(sortedKeys[4]); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, undefined, "Entry was deleted"); + + request = objectStore.add("foo", sortedKeys[4]); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + keyIndex = sortedKeys.length - 1; + + request = objectStore.openCursor(null, "prev"); + request.onerror = errorHandler; + storedCursor = null; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + storedCursor = cursor; + + checkCursor(cursor, sortedKeys[keyIndex]); + + cursor.continue(); + + checkCursor(cursor, sortedKeys[keyIndex]); + + keyIndex--; + } else { + ok(cursor === null, "The request result should be null."); + ok( + storedCursor.value === undefined, + "The cursor's value should be undefined." + ); + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, -1, "Saw all added items"); + + // Wait for success + yield undefined; + + db.close(); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_database_close_without_onclose.js b/dom/indexedDB/test/unit/test_database_close_without_onclose.js new file mode 100644 index 0000000000..7d4225fb33 --- /dev/null +++ b/dom/indexedDB/test/unit/test_database_close_without_onclose.js @@ -0,0 +1,51 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ +/* eslint-disable mozilla/no-arbitrary-setTimeout */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window + ? window.location.pathname + : "test_database_close_without_onclose.js"; + + const checkpointSleepTimeSec = 10; + + let openRequest = indexedDB.open(name, 1); + openRequest.onerror = errorHandler; + openRequest.onsuccess = unexpectedSuccessHandler; + openRequest.onupgradeneeded = grabEventAndContinueHandler; + + ok(openRequest instanceof IDBOpenDBRequest, "Expect an IDBOpenDBRequest"); + + let event = yield undefined; + + is(event.type, "upgradeneeded", "Expect an upgradeneeded event"); + ok(event instanceof IDBVersionChangeEvent, "Expect a versionchange event"); + + let db = event.target.result; + db.createObjectStore("store"); + + openRequest.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + is(event.type, "success", "Expect a success event"); + is(event.target, openRequest, "Event has right target"); + ok(event.target.result instanceof IDBDatabase, "Result should be a database"); + is(db.objectStoreNames.length, 1, "Expect an objectStore here"); + + db.onclose = errorHandler; + + db.close(); + setTimeout(continueToNextStepSync, checkpointSleepTimeSec * 1000); + yield undefined; + + ok(true, "The close event should not be fired after closed normally!"); + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_database_onclose.js b/dom/indexedDB/test/unit/test_database_onclose.js new file mode 100644 index 0000000000..0162ffc3ab --- /dev/null +++ b/dom/indexedDB/test/unit/test_database_onclose.js @@ -0,0 +1,258 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +var testGenerator = testSteps(); + +function* testSteps() { + function testInvalidStateError(aDb, aTxn) { + try { + info("The db shall become invalid after closed."); + aDb.transaction("store"); + ok(false, "InvalidStateError shall be thrown."); + } catch (e) { + ok(e instanceof DOMException, "got a database exception"); + is(e.name, "InvalidStateError", "correct error"); + } + + try { + info("The txn shall become invalid after closed."); + aTxn.objectStore("store"); + ok(false, "InvalidStateError shall be thrown."); + } catch (e) { + ok(e instanceof DOMException, "got a database exception"); + is(e.name, "InvalidStateError", "correct error"); + } + } + + const name = this.window + ? window.location.pathname + : "test_database_onclose.js"; + + info("#1: Verifying IDBDatabase.onclose after cleared by the agent."); + let openRequest = indexedDB.open(name, 1); + openRequest.onerror = errorHandler; + openRequest.onsuccess = unexpectedSuccessHandler; + openRequest.onupgradeneeded = grabEventAndContinueHandler; + + ok(openRequest instanceof IDBOpenDBRequest, "Expect an IDBOpenDBRequest"); + + let event = yield undefined; + + is(event.type, "upgradeneeded", "Expect an upgradeneeded event"); + ok(event instanceof IDBVersionChangeEvent, "Expect a versionchange event"); + + let db = event.target.result; + db.createObjectStore("store"); + + openRequest.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + is(event.type, "success", "Expect a success event"); + is(event.target, openRequest, "Event has right target"); + ok(event.target.result instanceof IDBDatabase, "Result should be a database"); + is(db.objectStoreNames.length, 1, "Expect an objectStore here"); + + let txn = db.transaction("store", "readwrite"); + let objectStore = txn.objectStore("store"); + + clearAllDatabases(continueToNextStep); + + db.onclose = grabEventAndContinueHandler; + event = yield undefined; + is(event.type, "close", "Expect a close event"); + is(event.target, db, "Correct target"); + + info("Wait for callback of clearAllDatabases()."); + yield undefined; + + testInvalidStateError(db, txn); + + info( + "#2: Verifying IDBDatabase.onclose && IDBTransaction.onerror " + + "in *write* operation after cleared by the agent." + ); + openRequest = indexedDB.open(name, 1); + openRequest.onerror = errorHandler; + openRequest.onsuccess = unexpectedSuccessHandler; + openRequest.onupgradeneeded = grabEventAndContinueHandler; + + ok(openRequest instanceof IDBOpenDBRequest, "Expect an IDBOpenDBRequest"); + + event = yield undefined; + + is(event.type, "upgradeneeded", "Expect an upgradeneeded event"); + ok(event instanceof IDBVersionChangeEvent, "Expect a versionchange event"); + + db = event.target.result; + db.createObjectStore("store"); + + openRequest.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + is(event.type, "success", "Expect a success event"); + is(event.target, openRequest, "Event has right target"); + ok(event.target.result instanceof IDBDatabase, "Result should be a database"); + is(db.objectStoreNames.length, 1, "Expect an objectStore here"); + + txn = db.transaction("store", "readwrite"); + objectStore = txn.objectStore("store"); + + let objectId = 0; + while (true) { + let addRequest = objectStore.add({ foo: "foo" }, objectId); + addRequest.onerror = function (event) { + info("addRequest.onerror, objectId: " + objectId); + txn.onerror = grabEventAndContinueHandler; + testGenerator.next(true); + }; + addRequest.onsuccess = function () { + testGenerator.next(false); + }; + + if (objectId == 0) { + clearAllDatabases(() => { + info("clearAllDatabases is done."); + continueToNextStep(); + }); + } + + objectId++; + + let aborted = yield undefined; + if (aborted) { + break; + } + } + + event = yield undefined; + is(event.type, "error", "Got an error event"); + is(event.target.error.name, "AbortError", "Expected AbortError was thrown."); + event.preventDefault(); + + txn.onabort = grabEventAndContinueHandler; + event = yield undefined; + is(event.type, "abort", "Got an abort event"); + is(event.target.error.name, "AbortError", "Expected AbortError was thrown."); + + db.onclose = grabEventAndContinueHandler; + event = yield undefined; + is(event.type, "close", "Expect a close event"); + is(event.target, db, "Correct target"); + testInvalidStateError(db, txn); + + info("Wait for the callback of clearAllDatabases()."); + yield undefined; + + info( + "#3: Verifying IDBDatabase.onclose && IDBTransaction.onerror " + + "in *read* operation after cleared by the agent." + ); + openRequest = indexedDB.open(name, 1); + openRequest.onerror = errorHandler; + openRequest.onsuccess = unexpectedSuccessHandler; + openRequest.onupgradeneeded = grabEventAndContinueHandler; + + ok(openRequest instanceof IDBOpenDBRequest, "Expect an IDBOpenDBRequest"); + + event = yield undefined; + + is(event.type, "upgradeneeded", "Expect an upgradeneeded event"); + ok(event instanceof IDBVersionChangeEvent, "Expect a versionchange event"); + + db = event.target.result; + objectStore = db.createObjectStore("store", { + keyPath: "id", + autoIncrement: true, + }); + // The number of read records varies between 1~2000 before the db is cleared + // during testing. + let numberOfObjects = 3000; + objectId = 0; + while (true) { + let addRequest = objectStore.add({ foo: "foo" }); + addRequest.onsuccess = function () { + objectId++; + testGenerator.next(objectId == numberOfObjects); + }; + addRequest.onerror = errorHandler; + + let done = yield undefined; + if (done) { + break; + } + } + + openRequest.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + is(event.type, "success", "Expect a success event"); + is(event.target, openRequest, "Event has right target"); + ok(event.target.result instanceof IDBDatabase, "Result should be a database"); + is(db.objectStoreNames.length, 1, "Expect an objectStore here"); + + txn = db.transaction("store"); + objectStore = txn.objectStore("store"); + + let numberOfReadObjects = 0; + let readRequest = objectStore.openCursor(); + readRequest.onerror = function (event) { + info("readRequest.onerror, numberOfReadObjects: " + numberOfReadObjects); + testGenerator.next(true); + }; + readRequest.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + numberOfReadObjects++; + event.target.result.continue(); + } else { + info("Cursor is invalid, numberOfReadObjects: " + numberOfReadObjects); + todo(false, "All records are iterated before database is cleared!"); + testGenerator.next(false); + } + }; + + clearAllDatabases(() => { + info("clearAllDatabases is done."); + continueToNextStep(); + }); + + let readRequestError = yield undefined; + if (readRequestError) { + txn.onerror = grabEventAndContinueHandler; + + event = yield undefined; + is(event.type, "error", "Got an error event"); + is( + event.target.error.name, + "AbortError", + "Expected AbortError was thrown." + ); + event.preventDefault(); + + txn.onabort = grabEventAndContinueHandler; + event = yield undefined; + is(event.type, "abort", "Got an abort event"); + is( + event.target.error.name, + "AbortError", + "Expected AbortError was thrown." + ); + + db.onclose = grabEventAndContinueHandler; + event = yield undefined; + is(event.type, "close", "Expect a close event"); + is(event.target, db, "Correct target"); + + testInvalidStateError(db, txn); + } + + info("Wait for the callback of clearAllDatabases()."); + yield undefined; + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_deleteDatabase.js b/dom/indexedDB/test/unit/test_deleteDatabase.js new file mode 100644 index 0000000000..51e33ad974 --- /dev/null +++ b/dom/indexedDB/test/unit/test_deleteDatabase.js @@ -0,0 +1,108 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + ok(indexedDB.deleteDatabase, "deleteDatabase function should exist!"); + + let request = indexedDB.open(name, 10); + request.onerror = errorHandler; + request.onsuccess = unexpectedSuccessHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + + ok(request instanceof IDBOpenDBRequest, "Expect an IDBOpenDBRequest"); + + let event = yield undefined; + + is(event.type, "upgradeneeded", "Expect an upgradeneeded event"); + ok(event instanceof IDBVersionChangeEvent, "Expect a versionchange event"); + + let db = event.target.result; + db.createObjectStore("stuff"); + + request.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + is(event.type, "success", "Expect a success event"); + is(event.target, request, "Event has right target"); + ok(event.target.result instanceof IDBDatabase, "Result should be a database"); + is(db.objectStoreNames.length, 1, "Expect an objectStore here"); + + request = indexedDB.open(name, 10); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + is(event.type, "success", "Expect a success event"); + is(event.target, request, "Event has right target"); + ok(event.target.result instanceof IDBDatabase, "Result should be a database"); + let db2 = event.target.result; + is(db2.objectStoreNames.length, 1, "Expect an objectStore here"); + + var onversionchangecalled = false; + + function closeDBs(event) { + onversionchangecalled = true; + ok(event instanceof IDBVersionChangeEvent, "expect a versionchange event"); + is(event.oldVersion, 10, "oldVersion should be 10"); + ok(event.newVersion === null, "newVersion should be null"); + ok(!(event.newVersion === undefined), "newVersion should be null"); + ok(!(event.newVersion === 0), "newVersion should be null"); + db.close(); + db2.close(); + db.onversionchange = unexpectedSuccessHandler; + db2.onversionchange = unexpectedSuccessHandler; + } + + // The IDB spec doesn't guarantee the order that onversionchange will fire + // on the dbs. + db.onversionchange = closeDBs; + db2.onversionchange = closeDBs; + + request = indexedDB.deleteDatabase(name); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + ok(request instanceof IDBOpenDBRequest, "Expect an IDBOpenDBRequest"); + + event = yield undefined; + ok(onversionchangecalled, "Expected versionchange events"); + is(event.type, "success", "expect a success event"); + is(event.target, request, "event has right target"); + ok(event.target.result === undefined, "event should have no result"); + + request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + is(event.target.result.version, 1, "DB has proper version"); + is( + event.target.result.objectStoreNames.length, + 0, + "DB should have no object stores" + ); + + request = indexedDB.deleteDatabase("thisDatabaseHadBetterNotExist"); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + ok(true, "deleteDatabase on a non-existent database succeeded"); + + request = indexedDB.open("thisDatabaseHadBetterNotExist"); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + ok(true, "after deleting a non-existent database, open should work"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_deleteDatabase_interactions.js b/dom/indexedDB/test/unit/test_deleteDatabase_interactions.js new file mode 100644 index 0000000000..3b26f2a4ef --- /dev/null +++ b/dom/indexedDB/test/unit/test_deleteDatabase_interactions.js @@ -0,0 +1,65 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + let request = indexedDB.open(name, 10); + request.onerror = errorHandler; + request.onsuccess = unexpectedSuccessHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + + ok(request instanceof IDBOpenDBRequest, "Expect an IDBOpenDBRequest"); + + let event = yield undefined; + + is(event.type, "upgradeneeded", "Expect an upgradeneeded event"); + ok(event instanceof IDBVersionChangeEvent, "Expect a versionchange event"); + + let db = event.target.result; + db.createObjectStore("stuff"); + + request.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + is(event.type, "success", "Expect a success event"); + is(event.target, request, "Event has right target"); + ok(event.target.result instanceof IDBDatabase, "Result should be a database"); + is(db.objectStoreNames.length, 1, "Expect an objectStore here"); + + db.close(); + + request = indexedDB.deleteDatabase(name); + + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + ok(request instanceof IDBOpenDBRequest, "Expect an IDBOpenDBRequest"); + + let openRequest = indexedDB.open(name, 1); + openRequest.onerror = errorHandler; + openRequest.onsuccess = unexpectedSuccessHandler; + + event = yield undefined; + is(event.type, "success", "expect a success event"); + is(event.target, request, "event has right target"); + is(event.target.result, undefined, "event should have no result"); + + openRequest.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + is(event.target.result.version, 1, "DB has proper version"); + is( + event.target.result.objectStoreNames.length, + 0, + "DB should have no object stores" + ); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_deleteDatabase_onblocked.js b/dom/indexedDB/test/unit/test_deleteDatabase_onblocked.js new file mode 100644 index 0000000000..1b70fb113f --- /dev/null +++ b/dom/indexedDB/test/unit/test_deleteDatabase_onblocked.js @@ -0,0 +1,82 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const dbVersion = 10; + + let openRequest = indexedDB.open(name, dbVersion); + openRequest.onerror = errorHandler; + openRequest.onblocked = errorHandler; + openRequest.onsuccess = unexpectedSuccessHandler; + openRequest.onupgradeneeded = grabEventAndContinueHandler; + + let event = yield undefined; + + is(event.type, "upgradeneeded", "Expect an upgradeneeded event"); + ok(event instanceof IDBVersionChangeEvent, "Expect a versionchange event"); + + let db = event.target.result; + db.onversionchange = errorHandler; + db.createObjectStore("stuff"); + + openRequest.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + is(event.type, "success", "Expect a success event"); + is(event.target, openRequest, "Event has right target"); + ok(event.target.result instanceof IDBDatabase, "Result should be a database"); + is(db.objectStoreNames.length, 1, "Expect an objectStore here"); + + db.onversionchange = grabEventAndContinueHandler; + let deletingRequest = indexedDB.deleteDatabase(name); + deletingRequest.onerror = errorHandler; + deletingRequest.onsuccess = errorHandler; + deletingRequest.onblocked = errorHandler; + + event = yield undefined; + + is(event.type, "versionchange", "Expect an versionchange event"); + is(event.target, db, "Event has right target"); + ok(event instanceof IDBVersionChangeEvent, "Expect a versionchange event"); + is(event.oldVersion, dbVersion, "Correct old version"); + is(event.newVersion, null, "Correct new version"); + + deletingRequest.onblocked = grabEventAndContinueHandler; + + event = yield undefined; + + is(event.type, "blocked", "Expect an blocked event"); + is(event.target, deletingRequest, "Event has right target"); + ok(event instanceof IDBVersionChangeEvent, "Expect a versionchange event"); + is(event.oldVersion, dbVersion, "Correct old version"); + is(event.newVersion, null, "Correct new version"); + + deletingRequest.onsuccess = grabEventAndContinueHandler; + db.close(); + + event = yield undefined; + + is(event.type, "success", "expect a success event"); + is(event.target, deletingRequest, "event has right target"); + is(event.target.result, undefined, "event should have no result"); + + openRequest = indexedDB.open(name, 1); + openRequest.onerror = errorHandler; + openRequest.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + db = event.target.result; + is(db.version, 1, "DB has proper version"); + is(db.objectStoreNames.length, 0, "DB should have no object stores"); + + db.close(); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_deleteDatabase_onblocked_duringVersionChange.js b/dom/indexedDB/test/unit/test_deleteDatabase_onblocked_duringVersionChange.js new file mode 100644 index 0000000000..5e3321188d --- /dev/null +++ b/dom/indexedDB/test/unit/test_deleteDatabase_onblocked_duringVersionChange.js @@ -0,0 +1,83 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const dbVersion = 10; + + let openRequest = indexedDB.open(name, dbVersion); + openRequest.onerror = errorHandler; + openRequest.onblocked = errorHandler; + openRequest.onsuccess = unexpectedSuccessHandler; + openRequest.onupgradeneeded = grabEventAndContinueHandler; + + let event = yield undefined; + + is(event.type, "upgradeneeded", "Expect an upgradeneeded event"); + ok(event instanceof IDBVersionChangeEvent, "Expect a versionchange event"); + + let db = event.target.result; + db.onversionchange = errorHandler; + db.createObjectStore("stuff"); + + let deletingRequest = indexedDB.deleteDatabase(name); + deletingRequest.onerror = errorHandler; + deletingRequest.onsuccess = errorHandler; + deletingRequest.onblocked = errorHandler; + + openRequest.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + is(event.type, "success", "Expect a success event"); + is(event.target, openRequest, "Event has right target"); + ok(event.target.result instanceof IDBDatabase, "Result should be a database"); + is(db.objectStoreNames.length, 1, "Expect an objectStore here"); + + db.onversionchange = grabEventAndContinueHandler; + + event = yield undefined; + + is(event.type, "versionchange", "Expect an versionchange event"); + is(event.target, db, "Event has right target"); + ok(event instanceof IDBVersionChangeEvent, "Expect a versionchange event"); + is(event.oldVersion, dbVersion, "Correct old version"); + is(event.newVersion, null, "Correct new version"); + + deletingRequest.onblocked = grabEventAndContinueHandler; + + event = yield undefined; + + is(event.type, "blocked", "Expect an blocked event"); + is(event.target, deletingRequest, "Event has right target"); + ok(event instanceof IDBVersionChangeEvent, "Expect a versionchange event"); + is(event.oldVersion, dbVersion, "Correct old version"); + is(event.newVersion, null, "Correct new version"); + + deletingRequest.onsuccess = grabEventAndContinueHandler; + db.close(); + + event = yield undefined; + + is(event.type, "success", "expect a success event"); + is(event.target, deletingRequest, "event has right target"); + is(event.target.result, undefined, "event should have no result"); + + openRequest = indexedDB.open(name, 1); + openRequest.onerror = errorHandler; + openRequest.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + db = event.target.result; + is(db.version, 1, "DB has proper version"); + is(db.objectStoreNames.length, 0, "DB should have no object stores"); + + db.close(); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_event_source.js b/dom/indexedDB/test/unit/test_event_source.js new file mode 100644 index 0000000000..f51d75edbb --- /dev/null +++ b/dom/indexedDB/test/unit/test_event_source.js @@ -0,0 +1,36 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const objectStoreName = "Objects"; + + var request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + var event = yield undefined; + + is(event.target.source, null, "correct event.target.source"); + + var db = event.target.result; + var objectStore = db.createObjectStore(objectStoreName, { + autoIncrement: true, + }); + request = objectStore.add({}); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + ok(event.target.source === objectStore, "correct event.source"); + + // Wait for success + yield undefined; + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_file_copy_failure.js b/dom/indexedDB/test/unit/test_file_copy_failure.js new file mode 100644 index 0000000000..5d4299a387 --- /dev/null +++ b/dom/indexedDB/test/unit/test_file_copy_failure.js @@ -0,0 +1,75 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = "test_file_copy_failure.js"; + const objectStoreName = "Blobs"; + const blob = getBlob(getView(1024)); + + info("Opening database"); + + let request = indexedDB.open(name); + request.onerror = errorHandler; + request.onupgradeneeded = continueToNextStepSync; + request.onsuccess = unexpectedSuccessHandler; + yield undefined; + + // upgradeneeded + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = continueToNextStepSync; + + info("Creating objectStore"); + + request.result.createObjectStore(objectStoreName); + + yield undefined; + + // success + let db = request.result; + db.onerror = errorHandler; + + info("Creating orphaned file"); + + let filesDir = getChromeFilesDir(); + + let journalFile = filesDir.clone(); + journalFile.append("journals"); + journalFile.append("1"); + + let exists = journalFile.exists(); + ok(!exists, "Journal file doesn't exist"); + + journalFile.create(Ci.nsIFile.NORMAL_FILE_TYPE, parseInt("0644", 8)); + + let file = filesDir.clone(); + file.append("1"); + + exists = file.exists(); + ok(!exists, "File doesn't exist"); + + file.create(Ci.nsIFile.NORMAL_FILE_TYPE, parseInt("0644", 8)); + + info("Storing blob"); + + let trans = db.transaction(objectStoreName, "readwrite"); + + request = trans.objectStore(objectStoreName).add(blob, 1); + request.onsuccess = continueToNextStepSync; + + yield undefined; + + trans.oncomplete = continueToNextStepSync; + + yield undefined; + + exists = journalFile.exists(); + ok(!exists, "Journal file doesn't exist"); + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_getAll.js b/dom/indexedDB/test/unit/test_getAll.js new file mode 100644 index 0000000000..6ada30d845 --- /dev/null +++ b/dom/indexedDB/test/unit/test_getAll.js @@ -0,0 +1,198 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + const values = ["a", "1", 1, "foo", 300, true, false, 4.5, null]; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + + let objectStore = db.createObjectStore("foo", { autoIncrement: true }); + + request.onsuccess = grabEventAndContinueHandler; + request = objectStore.mozGetAll(); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 0, "No elements"); + + let addedCount = 0; + + for (let i in values) { + request = objectStore.add(values[i]); + request.onerror = errorHandler; + request.onsuccess = function (event) { + if (++addedCount == values.length) { + executeSoon(function () { + testGenerator.next(); + }); + } + }; + } + yield undefined; + yield undefined; + + request = db.transaction("foo").objectStore("foo").mozGetAll(); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, values.length, "Same length"); + + for (let i in event.target.result) { + is(event.target.result[i], values[i], "Same value"); + } + + request = db.transaction("foo").objectStore("foo").mozGetAll(null, 5); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 5, "Correct length"); + + for (let i in event.target.result) { + is(event.target.result[i], values[i], "Same value"); + } + + let keyRange = IDBKeyRange.bound(1, 9); + + request = db.transaction("foo").objectStore("foo").mozGetAll(keyRange); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, values.length, "Correct length"); + + for (let i in event.target.result) { + is(event.target.result[i], values[i], "Same value"); + } + + request = db.transaction("foo").objectStore("foo").mozGetAll(keyRange, 0); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, values.length, "Correct length"); + + for (let i in event.target.result) { + is(event.target.result[i], values[i], "Same value"); + } + + request = db.transaction("foo").objectStore("foo").mozGetAll(keyRange, null); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, values.length, "Correct length"); + + for (let i in event.target.result) { + is(event.target.result[i], values[i], "Same value"); + } + + request = db + .transaction("foo") + .objectStore("foo") + .mozGetAll(keyRange, undefined); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, values.length, "Correct length"); + + for (let i in event.target.result) { + is(event.target.result[i], values[i], "Same value"); + } + + keyRange = IDBKeyRange.bound(4, 7); + + request = db.transaction("foo").objectStore("foo").mozGetAll(keyRange); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 4, "Correct length"); + + for (let i in event.target.result) { + is(event.target.result[i], values[parseInt(i) + 3], "Same value"); + } + + // Get should take a key range also but it doesn't return an array. + request = db.transaction("foo").objectStore("foo").get(keyRange); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, false, "Not an array object"); + is(event.target.result, values[3], "Correct value"); + + request = db.transaction("foo").objectStore("foo").mozGetAll(keyRange, 2); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 2, "Correct length"); + + for (let i in event.target.result) { + is(event.target.result[i], values[parseInt(i) + 3], "Same value"); + } + + keyRange = IDBKeyRange.bound(4, 7); + + request = db.transaction("foo").objectStore("foo").mozGetAll(keyRange, 50); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 4, "Correct length"); + + for (let i in event.target.result) { + is(event.target.result[i], values[parseInt(i) + 3], "Same value"); + } + + keyRange = IDBKeyRange.bound(4, 7); + + request = db.transaction("foo").objectStore("foo").mozGetAll(keyRange, 0); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 4, "Correct length"); + + keyRange = IDBKeyRange.bound(4, 7, true, true); + + request = db.transaction("foo").objectStore("foo").mozGetAll(keyRange); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 2, "Correct length"); + + for (let i in event.target.result) { + is(event.target.result[i], values[parseInt(i) + 4], "Same value"); + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_globalObjects_ipc.js b/dom/indexedDB/test/unit/test_globalObjects_ipc.js new file mode 100644 index 0000000000..8f3489773f --- /dev/null +++ b/dom/indexedDB/test/unit/test_globalObjects_ipc.js @@ -0,0 +1,19 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + // Test for IDBKeyRange and indexedDB availability in ipcshell. + run_test_in_child("./GlobalObjectsChild.js", function () { + do_test_finished(); + continueToNextStep(); + }); + yield undefined; + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_globalObjects_other.js b/dom/indexedDB/test/unit/test_globalObjects_other.js new file mode 100644 index 0000000000..2687675689 --- /dev/null +++ b/dom/indexedDB/test/unit/test_globalObjects_other.js @@ -0,0 +1,54 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +var testGenerator = testSteps(); + +function* testSteps() { + function getSpec(filename) { + let file = do_get_file(filename); + let uri = Services.io.newFileURI(file); + return uri.spec; + } + + // Test for IDBKeyRange and indexedDB availability in JS modules. + const { GlobalObjectsModule } = ChromeUtils.importESModule( + "resource://test/GlobalObjectsModule.sys.mjs" + ); + let test = new GlobalObjectsModule(); + test.ok = ok; + test.finishTest = continueToNextStep; + test.runTest(); + yield undefined; + + // Test for IDBKeyRange and indexedDB availability in JS sandboxes. + let principal = Cc["@mozilla.org/systemprincipal;1"].createInstance( + Ci.nsIPrincipal + ); + let sandbox = new Cu.Sandbox(principal, { + wantGlobalProperties: ["indexedDB"], + }); + sandbox.__SCRIPT_URI_SPEC__ = getSpec("GlobalObjectsSandbox.js"); + Cu.evalInSandbox( + "Components.classes['@mozilla.org/moz/jssubscript-loader;1'] \ + .createInstance(Components.interfaces.mozIJSSubScriptLoader) \ + .loadSubScript(__SCRIPT_URI_SPEC__);", + sandbox, + "1.7" + ); + sandbox.ok = ok; + sandbox.finishTest = continueToNextStep; + Cu.evalInSandbox("runTest();", sandbox); + yield undefined; + + finishTest(); + yield undefined; +} + +this.runTest = function () { + do_get_profile(); + + do_test_pending(); + testGenerator.next(); +}; diff --git a/dom/indexedDB/test/unit/test_globalObjects_xpc.js b/dom/indexedDB/test/unit/test_globalObjects_xpc.js new file mode 100644 index 0000000000..98bb7b600f --- /dev/null +++ b/dom/indexedDB/test/unit/test_globalObjects_xpc.js @@ -0,0 +1,26 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = "Splendid Test"; + + // Test for IDBKeyRange and indexedDB availability in xpcshell. + let keyRange = IDBKeyRange.only(42); + ok(keyRange, "Got keyRange"); + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + ok(db, "Got database"); + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_global_data.js b/dom/indexedDB/test/unit/test_global_data.js new file mode 100644 index 0000000000..8cbc3fbef8 --- /dev/null +++ b/dom/indexedDB/test/unit/test_global_data.js @@ -0,0 +1,60 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const objectStore = { + name: "Objects", + options: { keyPath: "id", autoIncrement: true }, + }; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + let event = yield undefined; + + let db1 = event.target.result; + + is(db1.objectStoreNames.length, 0, "No objectStores in db1"); + + db1.createObjectStore(objectStore.name, objectStore.options); + + continueToNextStep(); + yield undefined; + + request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + let db2 = event.target.result; + + ok(db1 !== db2, "Databases are not the same object"); + + is(db1.objectStoreNames.length, 1, "1 objectStore in db1"); + is(db1.objectStoreNames.item(0), objectStore.name, "Correct name"); + + is(db2.objectStoreNames.length, 1, "1 objectStore in db2"); + is(db2.objectStoreNames.item(0), objectStore.name, "Correct name"); + + let objectStore1 = db1 + .transaction(objectStore.name) + .objectStore(objectStore.name); + is(objectStore1.name, objectStore.name, "Same name"); + is(objectStore1.keyPath, objectStore.options.keyPath, "Same keyPath"); + + let objectStore2 = db2 + .transaction(objectStore.name) + .objectStore(objectStore.name); + + ok(objectStore1 !== objectStore2, "Different objectStores"); + is(objectStore1.name, objectStore2.name, "Same name"); + is(objectStore1.keyPath, objectStore2.keyPath, "Same keyPath"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_idbSubdirUpgrade.js b/dom/indexedDB/test/unit/test_idbSubdirUpgrade.js new file mode 100644 index 0000000000..5a6cf7686e --- /dev/null +++ b/dom/indexedDB/test/unit/test_idbSubdirUpgrade.js @@ -0,0 +1,55 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const openParams = [ + // This one lives in storage/default/http+++www.mozilla.org + { url: "http://www.mozilla.org", dbName: "dbB", dbVersion: 1 }, + ]; + + for (let i = 1; i <= 2; i++) { + clearAllDatabases(continueToNextStepSync); + yield undefined; + + installPackagedProfile("idbSubdirUpgrade" + i + "_profile"); + + for (let params of openParams) { + let request = indexedDB.openForPrincipal( + getPrincipal(params.url), + params.dbName, + params.dbVersion + ); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + is(event.type, "success", "Correct event type"); + } + + resetAllDatabases(continueToNextStepSync); + yield undefined; + + for (let params of openParams) { + let request = indexedDB.openForPrincipal( + getPrincipal(params.url), + params.dbName, + params.dbVersion + ); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + is(event.type, "success", "Correct event type"); + } + } + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_idle_maintenance.js b/dom/indexedDB/test/unit/test_idle_maintenance.js new file mode 100644 index 0000000000..b73dfb9848 --- /dev/null +++ b/dom/indexedDB/test/unit/test_idle_maintenance.js @@ -0,0 +1,178 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ +/* eslint-disable mozilla/no-arbitrary-setTimeout */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + let uri = Services.io.newURI("https://www.example.com"); + let principal = Services.scriptSecurityManager.createContentPrincipal( + uri, + {} + ); + + info("Setting permissions"); + + Services.perms.addFromPrincipal( + principal, + "indexedDB", + Ci.nsIPermissionManager.ALLOW_ACTION + ); + + // The idle-daily notification is disabled in xpchsell tests, so we don't + // need to do anything special to disable it for this test. + + info("Activating real idle service"); + + do_get_idle(); + + info("Creating databases"); + + // Keep at least one database open. + let req = indexedDB.open("foo-a", 1); + req.onerror = errorHandler; + req.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + // Keep at least one factory operation alive by deleting a database that is + // stil open. + req = indexedDB.open("foo-b", 1); + req.onerror = errorHandler; + req.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + indexedDB.deleteDatabase("foo-b"); + + // Create a database which we will later try to open while maintenance is + // performed. + req = indexedDB.open("foo-c", 1); + req.onerror = errorHandler; + req.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + let dbC = event.target.result; + dbC.close(); + + let dbCount = 0; + + for (let persistence of ["persistent", "temporary", "default"]) { + for (let i = 1; i <= 5; i++) { + let dbName = "foo-" + i; + let dbPersistence = persistence; + let req = indexedDB.openForPrincipal(principal, dbName, { + version: 1, + storage: dbPersistence, + }); + req.onerror = event => { + if (dbPersistence != "persistent") { + errorHandler(event); + return; + } + + // Explicit persistence is currently blocked on mobile. + info( + "Failed to create persistent database '" + + dbPersistence + + "/" + + dbName + + "', hopefully this is on mobile!" + ); + + event.preventDefault(); + + if (!--dbCount) { + continueToNextStep(); + } + }; + req.onupgradeneeded = event => { + let db = event.target.result; + let objectStore = db.createObjectStore("foo"); + + // Add lots of data... + for (let j = 0; j < 100; j++) { + objectStore.add("abcdefghijklmnopqrstuvwxyz0123456789", j); + } + + // And then clear it so that maintenance has some space to reclaim. + objectStore.clear(); + }; + req.onsuccess = event => { + let db = event.target.result; + ok(db, "Created database '" + dbPersistence + "/" + dbName + "'"); + + db.close(); + + if (!--dbCount) { + continueToNextStep(); + } + }; + dbCount++; + } + } + yield undefined; + + info("Getting usage before maintenance"); + + let usageBeforeMaintenance; + + Services.qms.getUsageForPrincipal(principal, request => { + let usage = request.result.usage; + ok(usage > 0, "Usage is non-zero"); + usageBeforeMaintenance = usage; + continueToNextStep(); + }); + yield undefined; + + info("Sending fake 'idle-daily' notification to QuotaManager"); + + let observer = Services.qms.QueryInterface(Ci.nsIObserver); + observer.observe(null, "idle-daily", ""); + + info("Opening database while maintenance is performed"); + + req = indexedDB.open("foo-c", 1); + req.onerror = errorHandler; + req.onsuccess = grabEventAndContinueHandler; + yield undefined; + + info("Waiting for maintenance to start"); + + // This time is totally arbitrary. Most likely directory scanning will have + // completed, QuotaManager locks will be acquired, and maintenance tasks will + // be scheduled before this time has elapsed, so we will be testing the + // maintenance code. However, if something is slow then this will test + // shutting down in the middle of maintenance. + setTimeout(continueToNextStep, 10000); + yield undefined; + + info("Getting usage after maintenance"); + + let usageAfterMaintenance; + + Services.qms.getUsageForPrincipal(principal, request => { + let usage = request.result.usage; + ok(usage > 0, "Usage is non-zero"); + usageAfterMaintenance = usage; + continueToNextStep(); + }); + yield undefined; + + info( + "Usage before: " + + usageBeforeMaintenance + + ". " + + "Usage after: " + + usageAfterMaintenance + ); + + ok( + usageAfterMaintenance <= usageBeforeMaintenance, + "Maintenance decreased file sizes or left them the same" + ); + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_index_empty_keyPath.js b/dom/indexedDB/test/unit/test_index_empty_keyPath.js new file mode 100644 index 0000000000..1e13f4d824 --- /dev/null +++ b/dom/indexedDB/test/unit/test_index_empty_keyPath.js @@ -0,0 +1,80 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + const objectStoreData = [ + { key: "1", value: "foo" }, + { key: "2", value: "bar" }, + { key: "3", value: "baz" }, + ]; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; // upgradeneeded + + let db = event.target.result; + + let objectStore = db.createObjectStore("data", { keyPath: null }); + + // First, add all our data to the object store. + let addedData = 0; + for (let i in objectStoreData) { + request = objectStore.add(objectStoreData[i].value, objectStoreData[i].key); + request.onerror = errorHandler; + request.onsuccess = function (event) { + if (++addedData == objectStoreData.length) { + testGenerator.next(event); + } + }; + } + event = yield undefined; // testGenerator.send + + // Now create the index. + objectStore.createIndex("set", "", { unique: true }); + yield undefined; // success + + let trans = db.transaction("data", "readwrite"); + objectStore = trans.objectStore("data"); + let index = objectStore.index("set"); + + request = index.get("bar"); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + is(event.target.result, "bar", "Got correct result"); + + request = objectStore.add("foopy", 4); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + yield undefined; + + request = index.get("foopy"); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + is(event.target.result, "foopy", "Got correct result"); + + request = objectStore.add("foopy", 5); + request.addEventListener("error", new ExpectError("ConstraintError", true)); + request.onsuccess = unexpectedSuccessHandler; + + trans.oncomplete = grabEventAndContinueHandler; + + yield undefined; + yield undefined; + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_index_getAll.js b/dom/indexedDB/test/unit/test_index_getAll.js new file mode 100644 index 0000000000..95e4e70c95 --- /dev/null +++ b/dom/indexedDB/test/unit/test_index_getAll.js @@ -0,0 +1,191 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const objectStoreName = "People"; + + const objectStoreData = [ + { key: "237-23-7732", value: { name: "Bob", height: 60, weight: 120 } }, + { key: "237-23-7733", value: { name: "Ann", height: 52, weight: 110 } }, + { key: "237-23-7734", value: { name: "Ron", height: 73, weight: 180 } }, + { key: "237-23-7735", value: { name: "Sue", height: 58, weight: 130 } }, + { key: "237-23-7736", value: { name: "Joe", height: 65, weight: 150 } }, + { key: "237-23-7737", value: { name: "Pat", height: 65 } }, + ]; + + const indexData = [ + { name: "name", keyPath: "name", options: { unique: true } }, + { name: "height", keyPath: "height", options: { unique: false } }, + { name: "weight", keyPath: "weight", options: { unique: false } }, + ]; + + const objectStoreDataHeightSort = [ + { key: "237-23-7733", value: { name: "Ann", height: 52, weight: 110 } }, + { key: "237-23-7735", value: { name: "Sue", height: 58, weight: 130 } }, + { key: "237-23-7732", value: { name: "Bob", height: 60, weight: 120 } }, + { key: "237-23-7736", value: { name: "Joe", height: 65, weight: 150 } }, + { key: "237-23-7737", value: { name: "Pat", height: 65 } }, + { key: "237-23-7734", value: { name: "Ron", height: 73, weight: 180 } }, + ]; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + + let objectStore = db.createObjectStore(objectStoreName); + + // First, add all our data to the object store. + let addedData = 0; + for (let i in objectStoreData) { + request = objectStore.add(objectStoreData[i].value, objectStoreData[i].key); + request.onerror = errorHandler; + request.onsuccess = function (event) { + if (++addedData == objectStoreData.length) { + testGenerator.next(event); + } + }; + } + yield undefined; + ok(true, "1"); + + // Now create the indexes. + for (let i in indexData) { + objectStore.createIndex( + indexData[i].name, + indexData[i].keyPath, + indexData[i].options + ); + } + + is(objectStore.indexNames.length, indexData.length, "Good index count"); + yield undefined; + + ok(true, "2"); + objectStore = db.transaction(objectStoreName).objectStore(objectStoreName); + + request = objectStore.index("height").mozGetAllKeys(65); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + ok(true, "3"); + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 2, "Correct length"); + + for (let i in event.target.result) { + is( + event.target.result[i], + objectStoreDataHeightSort[parseInt(i) + 3].key, + "Correct key" + ); + } + + request = objectStore.index("height").mozGetAllKeys(65, 0); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + ok(true, "3"); + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 2, "Correct length"); + + for (let i in event.target.result) { + is( + event.target.result[i], + objectStoreDataHeightSort[parseInt(i) + 3].key, + "Correct key" + ); + } + + request = objectStore.index("height").mozGetAllKeys(65, null); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + ok(true, "3"); + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 2, "Correct length"); + + for (let i in event.target.result) { + is( + event.target.result[i], + objectStoreDataHeightSort[parseInt(i) + 3].key, + "Correct key" + ); + } + + request = objectStore.index("height").mozGetAllKeys(65, undefined); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + ok(true, "3"); + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 2, "Correct length"); + + for (let i in event.target.result) { + is( + event.target.result[i], + objectStoreDataHeightSort[parseInt(i) + 3].key, + "Correct key" + ); + } + + request = objectStore.index("height").mozGetAllKeys(); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + ok(true, "4"); + + is(event.target.result instanceof Array, true, "Got an array object"); + is( + event.target.result.length, + objectStoreDataHeightSort.length, + "Correct length" + ); + + for (let i in event.target.result) { + is(event.target.result[i], objectStoreDataHeightSort[i].key, "Correct key"); + } + + request = objectStore.index("height").mozGetAllKeys(null, 4); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + ok(true, "5"); + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 4, "Correct length"); + + for (let i in event.target.result) { + is(event.target.result[i], objectStoreDataHeightSort[i].key, "Correct key"); + } + + request = objectStore.index("height").mozGetAllKeys(65, 1); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + ok(true, "6"); + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 1, "Correct length"); + + for (let i in event.target.result) { + is( + event.target.result[i], + objectStoreDataHeightSort[parseInt(i) + 3].key, + "Correct key" + ); + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_index_getAllObjects.js b/dom/indexedDB/test/unit/test_index_getAllObjects.js new file mode 100644 index 0000000000..9459cd4de6 --- /dev/null +++ b/dom/indexedDB/test/unit/test_index_getAllObjects.js @@ -0,0 +1,218 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const objectStoreName = "People"; + + const objectStoreData = [ + { key: "237-23-7732", value: { name: "Bob", height: 60, weight: 120 } }, + { key: "237-23-7733", value: { name: "Ann", height: 52, weight: 110 } }, + { key: "237-23-7734", value: { name: "Ron", height: 73, weight: 180 } }, + { key: "237-23-7735", value: { name: "Sue", height: 58, weight: 130 } }, + { key: "237-23-7736", value: { name: "Joe", height: 65, weight: 150 } }, + { key: "237-23-7737", value: { name: "Pat", height: 65 } }, + ]; + + const indexData = [ + { name: "name", keyPath: "name", options: { unique: true } }, + { name: "height", keyPath: "height", options: { unique: false } }, + { name: "weight", keyPath: "weight", options: { unique: false } }, + ]; + + const objectStoreDataHeightSort = [ + { key: "237-23-7733", value: { name: "Ann", height: 52, weight: 110 } }, + { key: "237-23-7735", value: { name: "Sue", height: 58, weight: 130 } }, + { key: "237-23-7732", value: { name: "Bob", height: 60, weight: 120 } }, + { key: "237-23-7736", value: { name: "Joe", height: 65, weight: 150 } }, + { key: "237-23-7737", value: { name: "Pat", height: 65 } }, + { key: "237-23-7734", value: { name: "Ron", height: 73, weight: 180 } }, + ]; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + + let objectStore = db.createObjectStore(objectStoreName, {}); + + // First, add all our data to the object store. + let addedData = 0; + for (let i in objectStoreData) { + request = objectStore.add(objectStoreData[i].value, objectStoreData[i].key); + request.onerror = errorHandler; + request.onsuccess = function (event) { + if (++addedData == objectStoreData.length) { + testGenerator.next(event); + } + }; + } + event = yield undefined; + + // Now create the indexes. + for (let i in indexData) { + objectStore.createIndex( + indexData[i].name, + indexData[i].keyPath, + indexData[i].options + ); + } + + is(objectStore.indexNames.length, indexData.length, "Good index count"); + yield undefined; + + objectStore = db.transaction(objectStoreName).objectStore(objectStoreName); + + request = objectStore.index("height").mozGetAll(65); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 2, "Correct length"); + + for (let i in event.target.result) { + let result = event.target.result[i]; + let testObj = objectStoreDataHeightSort[parseInt(i) + 3].value; + + is(result.name, testObj.name, "Correct name"); + is(result.height, testObj.height, "Correct height"); + + if (testObj.hasOwnProperty("weight")) { + is(result.weight, testObj.weight, "Correct weight"); + } + } + + request = objectStore.index("height").mozGetAll(65, 0); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 2, "Correct length"); + + for (let i in event.target.result) { + let result = event.target.result[i]; + let testObj = objectStoreDataHeightSort[parseInt(i) + 3].value; + + is(result.name, testObj.name, "Correct name"); + is(result.height, testObj.height, "Correct height"); + + if (testObj.hasOwnProperty("weight")) { + is(result.weight, testObj.weight, "Correct weight"); + } + } + + request = objectStore.index("height").mozGetAll(65, null); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 2, "Correct length"); + + for (let i in event.target.result) { + let result = event.target.result[i]; + let testObj = objectStoreDataHeightSort[parseInt(i) + 3].value; + + is(result.name, testObj.name, "Correct name"); + is(result.height, testObj.height, "Correct height"); + + if (testObj.hasOwnProperty("weight")) { + is(result.weight, testObj.weight, "Correct weight"); + } + } + + request = objectStore.index("height").mozGetAll(65, undefined); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 2, "Correct length"); + + for (let i in event.target.result) { + let result = event.target.result[i]; + let testObj = objectStoreDataHeightSort[parseInt(i) + 3].value; + + is(result.name, testObj.name, "Correct name"); + is(result.height, testObj.height, "Correct height"); + + if (testObj.hasOwnProperty("weight")) { + is(result.weight, testObj.weight, "Correct weight"); + } + } + + request = objectStore.index("height").mozGetAll(); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is( + event.target.result.length, + objectStoreDataHeightSort.length, + "Correct length" + ); + + for (let i in event.target.result) { + let result = event.target.result[i]; + let testObj = objectStoreDataHeightSort[i].value; + + is(result.name, testObj.name, "Correct name"); + is(result.height, testObj.height, "Correct height"); + + if (testObj.hasOwnProperty("weight")) { + is(result.weight, testObj.weight, "Correct weight"); + } + } + + request = objectStore.index("height").mozGetAll(null, 4); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 4, "Correct length"); + + for (let i in event.target.result) { + let result = event.target.result[i]; + let testObj = objectStoreDataHeightSort[i].value; + + is(result.name, testObj.name, "Correct name"); + is(result.height, testObj.height, "Correct height"); + + if (testObj.hasOwnProperty("weight")) { + is(result.weight, testObj.weight, "Correct weight"); + } + } + + request = objectStore.index("height").mozGetAll(65, 1); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 1, "Correct length"); + + for (let i in event.target.result) { + let result = event.target.result[i]; + let testObj = objectStoreDataHeightSort[parseInt(i) + 3].value; + + is(result.name, testObj.name, "Correct name"); + is(result.height, testObj.height, "Correct height"); + + if (testObj.hasOwnProperty("weight")) { + is(result.weight, testObj.weight, "Correct weight"); + } + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_index_object_cursors.js b/dom/indexedDB/test/unit/test_index_object_cursors.js new file mode 100644 index 0000000000..850e1c6007 --- /dev/null +++ b/dom/indexedDB/test/unit/test_index_object_cursors.js @@ -0,0 +1,158 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const objectStoreData = [ + { name: "", options: { keyPath: "id", autoIncrement: true } }, + { name: null, options: { keyPath: "ss" } }, + { name: undefined, options: {} }, + { name: "4", options: { autoIncrement: true } }, + ]; + + const indexData = [ + { name: "", keyPath: "name", options: { unique: true } }, + { name: null, keyPath: "height", options: {} }, + ]; + + const data = [ + { ss: "237-23-7732", name: "Ann", height: 60 }, + { ss: "237-23-7733", name: "Bob", height: 65 }, + ]; + + let request = indexedDB.open( + this.window ? window.location.pathname : "Splendid Test", + 1 + ); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + db.onerror = errorHandler; + + event.target.onsuccess = continueToNextStep; + + for (let objectStoreIndex in objectStoreData) { + const objectStoreInfo = objectStoreData[objectStoreIndex]; + let objectStore = db.createObjectStore( + objectStoreInfo.name, + objectStoreInfo.options + ); + for (let indexIndex in indexData) { + const indexInfo = indexData[indexIndex]; + objectStore.createIndex( + indexInfo.name, + indexInfo.keyPath, + indexInfo.options + ); + } + } + yield undefined; + + ok(true, "Initial setup"); + + for (let objectStoreIndex in objectStoreData) { + const info = objectStoreData[objectStoreIndex]; + + for (let indexIndex in indexData) { + const objectStoreName = objectStoreData[objectStoreIndex].name; + const indexName = indexData[indexIndex].name; + + let objectStore = db + .transaction(objectStoreName, "readwrite") + .objectStore(objectStoreName); + ok(true, "Got objectStore " + objectStoreName); + + for (let dataIndex in data) { + const obj = data[dataIndex]; + let key; + if (!info.options.keyPath && !info.options.autoIncrement) { + key = obj.ss; + } + objectStore.add(obj, key); + } + + let index = objectStore.index(indexName); + ok(true, "Got index " + indexName); + + let keyIndex = 0; + + index.openCursor().onsuccess = function (event) { + let cursor = event.target.result; + if (!cursor) { + continueToNextStep(); + return; + } + + is( + cursor.key, + data[keyIndex][indexData[indexIndex].keyPath], + "Good key" + ); + is(cursor.value.ss, data[keyIndex].ss, "Correct ss"); + is(cursor.value.name, data[keyIndex].name, "Correct name"); + is(cursor.value.height, data[keyIndex].height, "Correct height"); + + if (!keyIndex) { + let obj = cursor.value; + obj.updated = true; + + cursor.update(obj).onsuccess = function (event) { + ok(true, "Object updated"); + cursor.continue(); + keyIndex++; + }; + return; + } + + cursor.delete().onsuccess = function (event) { + ok(true, "Object deleted"); + cursor.continue(); + keyIndex++; + }; + }; + yield undefined; + + is(keyIndex, 2, "Saw all the items"); + + keyIndex = 0; + + db + .transaction(objectStoreName) + .objectStore(objectStoreName) + .openCursor().onsuccess = function (event) { + let cursor = event.target.result; + if (!cursor) { + continueToNextStep(); + return; + } + + is(cursor.value.ss, data[keyIndex].ss, "Correct ss"); + is(cursor.value.name, data[keyIndex].name, "Correct name"); + is(cursor.value.height, data[keyIndex].height, "Correct height"); + is(cursor.value.updated, true, "Correct updated flag"); + + cursor.continue(); + keyIndex++; + }; + yield undefined; + + is(keyIndex, 1, "Saw all the items"); + + db + .transaction(objectStoreName, "readwrite") + .objectStore(objectStoreName) + .clear().onsuccess = continueToNextStep; + yield undefined; + + objectStore = index = null; // Bug 943409 workaround. + } + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_index_update_delete.js b/dom/indexedDB/test/unit/test_index_update_delete.js new file mode 100644 index 0000000000..da43feb3b9 --- /dev/null +++ b/dom/indexedDB/test/unit/test_index_update_delete.js @@ -0,0 +1,172 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + let name = this.window ? window.location.pathname : "Splendid Test"; + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + + let event = yield undefined; + + let db = event.target.result; + db.onerror = errorHandler; + + for (let autoIncrement of [false, true]) { + let objectStore = db.createObjectStore(autoIncrement, { + keyPath: "id", + autoIncrement, + }); + + for (let i = 0; i < 10; i++) { + objectStore.add({ id: i, index: i }); + } + + for (let unique of [false, true]) { + objectStore.createIndex(unique, "index", { unique }); + } + + for (let i = 10; i < 20; i++) { + objectStore.add({ id: i, index: i }); + } + } + + event = yield undefined; + is(event.type, "success", "expect a success event"); + + for (let autoIncrement of [false, true]) { + let objectStore = db.transaction(autoIncrement).objectStore(autoIncrement); + + objectStore.count().onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + is(event.target.result, 20, "Correct number of entries in objectStore"); + + let objectStoreCount = event.target.result; + let indexCount = event.target.result; + + for (let unique of [false, true]) { + let index = db + .transaction(autoIncrement, "readwrite") + .objectStore(autoIncrement) + .index(unique); + + index.count().onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + is(event.target.result, indexCount, "Correct number of entries in index"); + + let modifiedEntry = unique ? 5 : 10; + let keyRange = IDBKeyRange.only(modifiedEntry); + + let sawEntry = false; + index.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + sawEntry = true; + is(cursor.key, modifiedEntry, "Correct key"); + + cursor.value.index = unique ? 30 : 35; + cursor.update(cursor.value).onsuccess = function (event) { + cursor.continue(); + }; + } else { + continueToNextStep(); + } + }; + yield undefined; + + is(sawEntry, true, "Saw entry for key value " + modifiedEntry); + + // Recount index. Shouldn't change. + index = db + .transaction(autoIncrement, "readwrite") + .objectStore(autoIncrement) + .index(unique); + + index.count().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, indexCount, "Correct number of entries in index"); + + modifiedEntry = unique ? 30 : 35; + keyRange = IDBKeyRange.only(modifiedEntry); + + sawEntry = false; + index.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + sawEntry = true; + is(cursor.key, modifiedEntry, "Correct key"); + + delete cursor.value.index; + cursor.update(cursor.value).onsuccess = function (event) { + indexCount--; + cursor.continue(); + }; + } else { + continueToNextStep(); + } + }; + yield undefined; + + is(sawEntry, true, "Saw entry for key value " + modifiedEntry); + + // Recount objectStore. Should be unchanged. + objectStore = db + .transaction(autoIncrement, "readwrite") + .objectStore(autoIncrement); + + objectStore.count().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + objectStoreCount, + "Correct number of entries in objectStore" + ); + + // Recount index. Should be one item less. + index = objectStore.index(unique); + + index.count().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, indexCount, "Correct number of entries in index"); + + modifiedEntry = objectStoreCount - 1; + + objectStore.delete(modifiedEntry).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + objectStoreCount--; + indexCount--; + + objectStore.count().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result, + objectStoreCount, + "Correct number of entries in objectStore" + ); + + index.count().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, indexCount, "Correct number of entries in index"); + + index = event = null; // Bug 943409 workaround. + } + objectStore = event = null; // Bug 943409 workaround. + } + + finishTest(); + event = db = request = null; // Bug 943409 workaround. +} diff --git a/dom/indexedDB/test/unit/test_indexes.js b/dom/indexedDB/test/unit/test_indexes.js new file mode 100644 index 0000000000..7adb57f77a --- /dev/null +++ b/dom/indexedDB/test/unit/test_indexes.js @@ -0,0 +1,1649 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + const objectStoreName = "People"; + + const objectStoreData = [ + { key: "237-23-7732", value: { name: "Bob", height: 60, weight: 120 } }, + { key: "237-23-7733", value: { name: "Ann", height: 52, weight: 110 } }, + { key: "237-23-7734", value: { name: "Ron", height: 73, weight: 180 } }, + { key: "237-23-7735", value: { name: "Sue", height: 58, weight: 130 } }, + { key: "237-23-7736", value: { name: "Joe", height: 65, weight: 150 } }, + { key: "237-23-7737", value: { name: "Pat", height: 65 } }, + ]; + + const indexData = [ + { name: "name", keyPath: "name", options: { unique: true } }, + { name: "height", keyPath: "height", options: {} }, + { name: "weight", keyPath: "weight", options: { unique: false } }, + ]; + + const objectStoreDataNameSort = [ + { key: "237-23-7733", value: { name: "Ann", height: 52, weight: 110 } }, + { key: "237-23-7732", value: { name: "Bob", height: 60, weight: 120 } }, + { key: "237-23-7736", value: { name: "Joe", height: 65, weight: 150 } }, + { key: "237-23-7737", value: { name: "Pat", height: 65 } }, + { key: "237-23-7734", value: { name: "Ron", height: 73, weight: 180 } }, + { key: "237-23-7735", value: { name: "Sue", height: 58, weight: 130 } }, + ]; + + const objectStoreDataWeightSort = [ + { key: "237-23-7733", value: { name: "Ann", height: 52, weight: 110 } }, + { key: "237-23-7732", value: { name: "Bob", height: 60, weight: 120 } }, + { key: "237-23-7735", value: { name: "Sue", height: 58, weight: 130 } }, + { key: "237-23-7736", value: { name: "Joe", height: 65, weight: 150 } }, + { key: "237-23-7734", value: { name: "Ron", height: 73, weight: 180 } }, + ]; + + const objectStoreDataHeightSort = [ + { key: "237-23-7733", value: { name: "Ann", height: 52, weight: 110 } }, + { key: "237-23-7735", value: { name: "Sue", height: 58, weight: 130 } }, + { key: "237-23-7732", value: { name: "Bob", height: 60, weight: 120 } }, + { key: "237-23-7736", value: { name: "Joe", height: 65, weight: 150 } }, + { key: "237-23-7737", value: { name: "Pat", height: 65 } }, + { key: "237-23-7734", value: { name: "Ron", height: 73, weight: 180 } }, + ]; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + let db = event.target.result; + + let objectStore = db.createObjectStore(objectStoreName, { keyPath: null }); + + // First, add all our data to the object store. + let addedData = 0; + for (let i in objectStoreData) { + request = objectStore.add(objectStoreData[i].value, objectStoreData[i].key); + request.onerror = errorHandler; + request.onsuccess = function (event) { + if (++addedData == objectStoreData.length) { + testGenerator.next(event); + } + }; + } + event = yield undefined; + // Now create the indexes. + for (let i in indexData) { + objectStore.createIndex( + indexData[i].name, + indexData[i].keyPath, + indexData[i].options + ); + } + is(objectStore.indexNames.length, indexData.length, "Good index count"); + yield undefined; + objectStore = db.transaction(objectStoreName).objectStore(objectStoreName); + + // Check global properties to make sure they are correct. + is(objectStore.indexNames.length, indexData.length, "Good index count"); + for (let i in indexData) { + let found = false; + for (let j = 0; j < objectStore.indexNames.length; j++) { + if (objectStore.indexNames.item(j) == indexData[i].name) { + found = true; + break; + } + } + is(found, true, "objectStore has our index"); + let index = objectStore.index(indexData[i].name); + is(index.name, indexData[i].name, "Correct name"); + is(index.objectStore.name, objectStore.name, "Correct store name"); + is(index.keyPath, indexData[i].keyPath, "Correct keyPath"); + is(index.unique, !!indexData[i].options.unique, "Correct unique value"); + } + + request = objectStore.index("name").getKey("Bob"); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, "237-23-7732", "Correct key returned!"); + + request = objectStore.index("name").get("Bob"); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result.name, "Bob", "Correct name returned!"); + is(event.target.result.height, 60, "Correct height returned!"); + is(event.target.result.weight, 120, "Correct weight returned!"); + + ok(true, "Test group 1"); + + let keyIndex = 0; + + request = objectStore.index("name").openKeyCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct primary key" + ); + ok(!("value" in cursor), "No value"); + + cursor.continue(); + + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct value" + ); + ok(!("value" in cursor), "No value"); + + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, objectStoreData.length, "Saw all the expected keys"); + + ok(true, "Test group 2"); + + keyIndex = 0; + + request = objectStore.index("weight").openKeyCursor(null, "next"); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataWeightSort[keyIndex].value.weight, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataWeightSort[keyIndex].key, + "Correct value" + ); + + cursor.continue(); + + is( + cursor.key, + objectStoreDataWeightSort[keyIndex].value.weight, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataWeightSort[keyIndex].key, + "Correct value" + ); + + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, objectStoreData.length - 1, "Saw all the expected keys"); + + // Check that the name index enforces its unique constraint. + objectStore = db + .transaction(objectStoreName, "readwrite") + .objectStore(objectStoreName); + request = objectStore.add( + { name: "Bob", height: 62, weight: 170 }, + "237-23-7738" + ); + request.addEventListener("error", new ExpectError("ConstraintError", true)); + request.onsuccess = unexpectedSuccessHandler; + event = yield undefined; + + ok(true, "Test group 3"); + + keyIndex = objectStoreDataNameSort.length - 1; + + request = objectStore.index("name").openKeyCursor(null, "prev"); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct value" + ); + + cursor.continue(); + + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct value" + ); + + keyIndex--; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, -1, "Saw all the expected keys"); + + ok(true, "Test group 4"); + + keyIndex = 1; + let keyRange = IDBKeyRange.bound("Bob", "Ron"); + + request = objectStore.index("name").openKeyCursor(keyRange); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct value" + ); + + cursor.continue(); + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, 5, "Saw all the expected keys"); + + ok(true, "Test group 5"); + + keyIndex = 2; + keyRange = IDBKeyRange.bound("Bob", "Ron", true); + + request = objectStore.index("name").openKeyCursor(keyRange); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct value" + ); + + cursor.continue(); + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, 5, "Saw all the expected keys"); + + ok(true, "Test group 6"); + + keyIndex = 1; + keyRange = IDBKeyRange.bound("Bob", "Ron", false, true); + + request = objectStore.index("name").openKeyCursor(keyRange); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct value" + ); + + cursor.continue(); + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, 4, "Saw all the expected keys"); + + ok(true, "Test group 7"); + + keyIndex = 2; + keyRange = IDBKeyRange.bound("Bob", "Ron", true, true); + + request = objectStore.index("name").openKeyCursor(keyRange); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct value" + ); + + cursor.continue(); + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, 4, "Saw all the expected keys"); + + ok(true, "Test group 8"); + + keyIndex = 1; + keyRange = IDBKeyRange.lowerBound("Bob"); + + request = objectStore.index("name").openKeyCursor(keyRange); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct value" + ); + + cursor.continue(); + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, objectStoreDataNameSort.length, "Saw all the expected keys"); + + ok(true, "Test group 9"); + + keyIndex = 2; + keyRange = IDBKeyRange.lowerBound("Bob", true); + + request = objectStore.index("name").openKeyCursor(keyRange); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct value" + ); + + cursor.continue(); + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, objectStoreDataNameSort.length, "Saw all the expected keys"); + + ok(true, "Test group 10"); + + keyIndex = 0; + keyRange = IDBKeyRange.upperBound("Joe"); + + request = objectStore.index("name").openKeyCursor(keyRange); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct value" + ); + + cursor.continue(); + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, 3, "Saw all the expected keys"); + + ok(true, "Test group 11"); + + keyIndex = 0; + keyRange = IDBKeyRange.upperBound("Joe", true); + + request = objectStore.index("name").openKeyCursor(keyRange); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct value" + ); + + cursor.continue(); + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, 2, "Saw all the expected keys"); + + ok(true, "Test group 12"); + + keyIndex = 3; + keyRange = IDBKeyRange.only("Pat"); + + request = objectStore.index("name").openKeyCursor(keyRange); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct value" + ); + + cursor.continue(); + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, 4, "Saw all the expected keys"); + + ok(true, "Test group 13"); + + keyIndex = 0; + + request = objectStore.index("name").openCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataNameSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataNameSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataNameSort[keyIndex].value.weight, + "Correct weight" + ); + } + + cursor.continue(); + + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataNameSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataNameSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataNameSort[keyIndex].value.weight, + "Correct weight" + ); + } + + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, objectStoreDataNameSort.length, "Saw all the expected keys"); + + ok(true, "Test group 14"); + + keyIndex = objectStoreDataNameSort.length - 1; + + request = objectStore.index("name").openCursor(null, "prev"); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataNameSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataNameSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataNameSort[keyIndex].value.weight, + "Correct weight" + ); + } + + cursor.continue(); + + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataNameSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataNameSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataNameSort[keyIndex].value.weight, + "Correct weight" + ); + } + + keyIndex--; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, -1, "Saw all the expected keys"); + + ok(true, "Test group 15"); + + keyIndex = 1; + keyRange = IDBKeyRange.bound("Bob", "Ron"); + + request = objectStore.index("name").openCursor(keyRange); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataNameSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataNameSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataNameSort[keyIndex].value.weight, + "Correct weight" + ); + } + + cursor.continue(); + + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataNameSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataNameSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataNameSort[keyIndex].value.weight, + "Correct weight" + ); + } + + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, 5, "Saw all the expected keys"); + + ok(true, "Test group 16"); + + keyIndex = 2; + keyRange = IDBKeyRange.bound("Bob", "Ron", true); + + request = objectStore.index("name").openCursor(keyRange); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataNameSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataNameSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataNameSort[keyIndex].value.weight, + "Correct weight" + ); + } + + cursor.continue(); + + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataNameSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataNameSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataNameSort[keyIndex].value.weight, + "Correct weight" + ); + } + + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, 5, "Saw all the expected keys"); + + ok(true, "Test group 17"); + + keyIndex = 1; + keyRange = IDBKeyRange.bound("Bob", "Ron", false, true); + + request = objectStore.index("name").openCursor(keyRange); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataNameSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataNameSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataNameSort[keyIndex].value.weight, + "Correct weight" + ); + } + + cursor.continue(); + + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataNameSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataNameSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataNameSort[keyIndex].value.weight, + "Correct weight" + ); + } + + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, 4, "Saw all the expected keys"); + + ok(true, "Test group 18"); + + keyIndex = 2; + keyRange = IDBKeyRange.bound("Bob", "Ron", true, true); + + request = objectStore.index("name").openCursor(keyRange); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataNameSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataNameSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataNameSort[keyIndex].value.weight, + "Correct weight" + ); + } + + cursor.continue(); + + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataNameSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataNameSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataNameSort[keyIndex].value.weight, + "Correct weight" + ); + } + + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, 4, "Saw all the expected keys"); + + ok(true, "Test group 19"); + + keyIndex = 4; + keyRange = IDBKeyRange.bound("Bob", "Ron"); + + request = objectStore.index("name").openCursor(keyRange, "prev"); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataNameSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataNameSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataNameSort[keyIndex].value.weight, + "Correct weight" + ); + } + + cursor.continue(); + + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataNameSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataNameSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataNameSort[keyIndex].value.weight, + "Correct weight" + ); + } + + keyIndex--; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, 0, "Saw all the expected keys"); + + ok(true, "Test group 20"); + + // Test "nextunique" + keyIndex = 3; + keyRange = IDBKeyRange.only(65); + + request = objectStore.index("height").openKeyCursor(keyRange, "next"); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataHeightSort[keyIndex].value.height, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataHeightSort[keyIndex].key, + "Correct value" + ); + + cursor.continue(); + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, 5, "Saw all the expected keys"); + + ok(true, "Test group 21"); + + keyIndex = 3; + keyRange = IDBKeyRange.only(65); + + request = objectStore.index("height").openKeyCursor(keyRange, "nextunique"); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataHeightSort[keyIndex].value.height, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataHeightSort[keyIndex].key, + "Correct value" + ); + + cursor.continue(); + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, 4, "Saw all the expected keys"); + + ok(true, "Test group 21.5"); + + keyIndex = 5; + + request = objectStore.index("height").openKeyCursor(null, "prev"); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataHeightSort[keyIndex].value.height, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataHeightSort[keyIndex].key, + "Correct value" + ); + + cursor.continue(); + keyIndex--; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, -1, "Saw all the expected keys"); + + ok(true, "Test group 22"); + + keyIndex = 5; + + request = objectStore.index("height").openKeyCursor(null, "prevunique"); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataHeightSort[keyIndex].value.height, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataHeightSort[keyIndex].key, + "Correct value" + ); + + cursor.continue(); + if (keyIndex == 5) { + keyIndex--; + } + keyIndex--; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, -1, "Saw all the expected keys"); + + ok(true, "Test group 23"); + + keyIndex = 3; + keyRange = IDBKeyRange.only(65); + + request = objectStore.index("height").openCursor(keyRange, "next"); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataHeightSort[keyIndex].value.height, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataHeightSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataHeightSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataHeightSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataHeightSort[keyIndex].value.weight, + "Correct weight" + ); + } + + cursor.continue(); + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, 5, "Saw all the expected keys"); + + ok(true, "Test group 24"); + + keyIndex = 3; + keyRange = IDBKeyRange.only(65); + + request = objectStore.index("height").openCursor(keyRange, "nextunique"); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataHeightSort[keyIndex].value.height, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataHeightSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataHeightSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataHeightSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataHeightSort[keyIndex].value.weight, + "Correct weight" + ); + } + + cursor.continue(); + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, 4, "Saw all the expected keys"); + + ok(true, "Test group 24.5"); + + keyIndex = 5; + + request = objectStore.index("height").openCursor(null, "prev"); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataHeightSort[keyIndex].value.height, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataHeightSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataHeightSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataHeightSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataHeightSort[keyIndex].value.weight, + "Correct weight" + ); + } + + cursor.continue(); + keyIndex--; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, -1, "Saw all the expected keys"); + + ok(true, "Test group 25"); + + keyIndex = 5; + + request = objectStore.index("height").openCursor(null, "prevunique"); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataHeightSort[keyIndex].value.height, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataHeightSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataHeightSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataHeightSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataHeightSort[keyIndex].value.weight, + "Correct weight" + ); + } + + cursor.continue(); + if (keyIndex == 5) { + keyIndex--; + } + keyIndex--; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, -1, "Saw all the expected keys"); + + ok(true, "Test group 26"); + + keyIndex = 0; + + request = objectStore.index("name").openKeyCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct value" + ); + + let nextKey = !keyIndex ? "Pat" : undefined; + + cursor.continue(nextKey); + + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct value" + ); + + if (!keyIndex) { + keyIndex = 3; + } else { + keyIndex++; + } + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, objectStoreData.length, "Saw all the expected keys"); + + ok(true, "Test group 27"); + + keyIndex = 0; + + request = objectStore.index("name").openKeyCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct value" + ); + + let nextKey = !keyIndex ? "Flo" : undefined; + + cursor.continue(nextKey); + + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct value" + ); + + keyIndex += keyIndex ? 1 : 2; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, objectStoreData.length, "Saw all the expected keys"); + + ok(true, "Test group 28"); + + keyIndex = 0; + + request = objectStore.index("name").openCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataNameSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataNameSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataNameSort[keyIndex].value.weight, + "Correct weight" + ); + } + + let nextKey = !keyIndex ? "Pat" : undefined; + + cursor.continue(nextKey); + + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataNameSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataNameSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataNameSort[keyIndex].value.weight, + "Correct weight" + ); + } + + if (!keyIndex) { + keyIndex = 3; + } else { + keyIndex++; + } + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, objectStoreDataNameSort.length, "Saw all the expected keys"); + + ok(true, "Test group 29"); + + keyIndex = 0; + + request = objectStore.index("name").openCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataNameSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataNameSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataNameSort[keyIndex].value.weight, + "Correct weight" + ); + } + + let nextKey = !keyIndex ? "Flo" : undefined; + + cursor.continue(nextKey); + + is( + cursor.key, + objectStoreDataNameSort[keyIndex].value.name, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataNameSort[keyIndex].key, + "Correct primary key" + ); + is( + cursor.value.name, + objectStoreDataNameSort[keyIndex].value.name, + "Correct name" + ); + is( + cursor.value.height, + objectStoreDataNameSort[keyIndex].value.height, + "Correct height" + ); + if ("weight" in cursor.value) { + is( + cursor.value.weight, + objectStoreDataNameSort[keyIndex].value.weight, + "Correct weight" + ); + } + + keyIndex += keyIndex ? 1 : 2; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, objectStoreDataNameSort.length, "Saw all the expected keys"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_indexes_bad_values.js b/dom/indexedDB/test/unit/test_indexes_bad_values.js new file mode 100644 index 0000000000..c695490f74 --- /dev/null +++ b/dom/indexedDB/test/unit/test_indexes_bad_values.js @@ -0,0 +1,140 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + const objectStoreName = "People"; + + const objectStoreData = [ + { key: "237-23-7732", value: { name: "Bob", height: 60, weight: 120 } }, + { key: "237-23-7733", value: { name: "Ann", height: 52, weight: 110 } }, + { key: "237-23-7734", value: { name: "Ron", height: 73, weight: 180 } }, + { key: "237-23-7735", value: { name: "Sue", height: 58, weight: 130 } }, + { key: "237-23-7736", value: { name: "Joe", height: 65, weight: 150 } }, + { key: "237-23-7737", value: { name: "Pat", height: 65 } }, + { key: "237-23-7738", value: { name: "Mel", height: 66, weight: {} } }, + ]; + + const badObjectStoreData = [ + { key: "237-23-7739", value: { name: "Rob", height: 65 } }, + { key: "237-23-7740", value: { name: "Jen", height: 66, weight: {} } }, + ]; + + const indexData = [ + { name: "weight", keyPath: "weight", options: { unique: false } }, + ]; + + const objectStoreDataWeightSort = [ + { key: "237-23-7733", value: { name: "Ann", height: 52, weight: 110 } }, + { key: "237-23-7732", value: { name: "Bob", height: 60, weight: 120 } }, + { key: "237-23-7735", value: { name: "Sue", height: 58, weight: 130 } }, + { key: "237-23-7736", value: { name: "Joe", height: 65, weight: 150 } }, + { key: "237-23-7734", value: { name: "Ron", height: 73, weight: 180 } }, + ]; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + + let objectStore = db.createObjectStore(objectStoreName, {}); + + let addedData = 0; + for (let i in objectStoreData) { + request = objectStore.add(objectStoreData[i].value, objectStoreData[i].key); + request.onerror = errorHandler; + request.onsuccess = function (event) { + if (++addedData == objectStoreData.length) { + testGenerator.next(event); + } + }; + } + event = yield undefined; + + for (let i in indexData) { + objectStore.createIndex( + indexData[i].name, + indexData[i].keyPath, + indexData[i].options + ); + } + + addedData = 0; + for (let i in badObjectStoreData) { + request = objectStore.add( + badObjectStoreData[i].value, + badObjectStoreData[i].key + ); + request.onerror = errorHandler; + request.onsuccess = function (event) { + if (++addedData == badObjectStoreData.length) { + executeSoon(function () { + testGenerator.next(); + }); + } + }; + } + yield undefined; + yield undefined; + + objectStore = db.transaction(objectStoreName).objectStore(objectStoreName); + + let keyIndex = 0; + + request = objectStore.index("weight").openKeyCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataWeightSort[keyIndex].value.weight, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataWeightSort[keyIndex].key, + "Correct value" + ); + keyIndex++; + + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, objectStoreDataWeightSort.length, "Saw all weights"); + + keyIndex = 0; + + request = objectStore.openCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + keyIndex++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + keyIndex, + objectStoreData.length + badObjectStoreData.length, + "Saw all people" + ); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_indexes_funny_things.js b/dom/indexedDB/test/unit/test_indexes_funny_things.js new file mode 100644 index 0000000000..953920dfe0 --- /dev/null +++ b/dom/indexedDB/test/unit/test_indexes_funny_things.js @@ -0,0 +1,188 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +var testGenerator = testSteps(); + +function* testSteps() { + // Blob constructor is not implemented outside of windows yet (Bug 827723). + if (!this.window) { + finishTest(); + return; + } + + const name = this.window ? window.location.pathname : "Splendid Test"; + + const objectStoreName = "Things"; + + const blob1 = new Blob(["foo", "bar"], { type: "text/plain" }); + const blob2 = new Blob(["foobazybar"], { type: "text/plain" }); + const blob3 = new Blob(["2"], { type: "bogus/" }); + const str = "The Book of Mozilla"; + str.type = blob1; + const arr = [1, 2, 3, 4, 5]; + + const objectStoreData = [ + { key: "1", value: blob1 }, + { key: "2", value: blob2 }, + { key: "3", value: blob3 }, + { key: "4", value: str }, + { key: "5", value: arr }, + ]; + + const indexData = [ + { name: "type", keyPath: "type", options: {} }, + { name: "length", keyPath: "length", options: { unique: true } }, + ]; + + const objectStoreDataTypeSort = [ + { key: "3", value: blob3 }, + { key: "1", value: blob1 }, + { key: "2", value: blob2 }, + ]; + + const objectStoreDataLengthSort = [ + { key: "5", value: arr }, + { key: "4", value: str }, + ]; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + let db = event.target.result; + + let objectStore = db.createObjectStore(objectStoreName, { keyPath: null }); + + // First, add all our data to the object store. + let addedData = 0; + for (let i in objectStoreData) { + request = objectStore.add(objectStoreData[i].value, objectStoreData[i].key); + request.onerror = errorHandler; + request.onsuccess = function (event) { + if (++addedData == objectStoreData.length) { + testGenerator.next(event); + } + }; + } + event = yield undefined; + // Now create the indexes. + for (let i in indexData) { + objectStore.createIndex( + indexData[i].name, + indexData[i].keyPath, + indexData[i].options + ); + } + is(objectStore.indexNames.length, indexData.length, "Good index count"); + yield undefined; + objectStore = db.transaction(objectStoreName).objectStore(objectStoreName); + + // Check global properties to make sure they are correct. + is(objectStore.indexNames.length, indexData.length, "Good index count"); + for (let i in indexData) { + let found = false; + for (let j = 0; j < objectStore.indexNames.length; j++) { + if (objectStore.indexNames.item(j) == indexData[i].name) { + found = true; + break; + } + } + is(found, true, "objectStore has our index"); + let index = objectStore.index(indexData[i].name); + is(index.name, indexData[i].name, "Correct name"); + is(index.objectStore.name, objectStore.name, "Correct store name"); + is(index.keyPath, indexData[i].keyPath, "Correct keyPath"); + is(index.unique, !!indexData[i].options.unique, "Correct unique value"); + } + + ok(true, "Test group 1"); + + let keyIndex = 0; + + request = objectStore.index("type").openKeyCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataTypeSort[keyIndex].value.type, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataTypeSort[keyIndex].key, + "Correct primary key" + ); + ok(!("value" in cursor), "No value"); + + cursor.continue(); + + is( + cursor.key, + objectStoreDataTypeSort[keyIndex].value.type, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataTypeSort[keyIndex].key, + "Correct value" + ); + ok(!("value" in cursor), "No value"); + + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, objectStoreDataTypeSort.length, "Saw all the expected keys"); + + ok(true, "Test group 2"); + + keyIndex = 0; + + request = objectStore.index("length").openKeyCursor(null, "next"); + request.onerror = errorHandler; + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + is( + cursor.key, + objectStoreDataLengthSort[keyIndex].value.length, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataLengthSort[keyIndex].key, + "Correct value" + ); + + cursor.continue(); + + is( + cursor.key, + objectStoreDataLengthSort[keyIndex].value.length, + "Correct key" + ); + is( + cursor.primaryKey, + objectStoreDataLengthSort[keyIndex].key, + "Correct value" + ); + + keyIndex++; + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(keyIndex, objectStoreDataLengthSort.length, "Saw all the expected keys"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_invalid_cursor.js b/dom/indexedDB/test/unit/test_invalid_cursor.js new file mode 100644 index 0000000000..891a7b1446 --- /dev/null +++ b/dom/indexedDB/test/unit/test_invalid_cursor.js @@ -0,0 +1,64 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator, disableWorkerTest */ +var disableWorkerTest = "Need to implement a gc() function for worker tests"; + +var testGenerator = testSteps(); + +function* testSteps() { + const dbName = "window" in this ? window.location.pathname : "test"; + const dbVersion = 1; + const objectStoreName = "foo"; + const data = 0; + + let req = indexedDB.open(dbName, dbVersion); + req.onerror = errorHandler; + req.onupgradeneeded = grabEventAndContinueHandler; + req.onsuccess = grabEventAndContinueHandler; + + let event = yield undefined; + + is(event.type, "upgradeneeded", "Got upgradeneeded event"); + + let db = event.target.result; + + let objectStore = db.createObjectStore(objectStoreName, { + autoIncrement: true, + }); + objectStore.add(data); + + event = yield undefined; + + is(event.type, "success", "Got success event for open"); + + objectStore = db.transaction(objectStoreName).objectStore(objectStoreName); + + objectStore.openCursor().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.type, "success", "Got success event for openCursor"); + + let cursor = event.target.result; + is(cursor.value, data, "Got correct cursor value"); + + objectStore.get(cursor.key).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, data, "Got correct get value"); + + info("Collecting garbage"); + + gc(); + + info("Done collecting garbage"); + + cursor.continue(); + event = yield undefined; + + is(event.target.result, null, "No more entries"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_invalid_version.js b/dom/indexedDB/test/unit/test_invalid_version.js new file mode 100644 index 0000000000..79d74ab2cc --- /dev/null +++ b/dom/indexedDB/test/unit/test_invalid_version.js @@ -0,0 +1,45 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + try { + indexedDB.open(name, 0); + ok(false, "Should have thrown!"); + } catch (e) { + ok(e instanceof TypeError, "Got TypeError."); + is(e.name, "TypeError", "Good error name."); + } + + try { + indexedDB.open(name, -1); + ok(false, "Should have thrown!"); + } catch (e) { + ok(e instanceof TypeError, "Got TypeError."); + is(e.name, "TypeError", "Good error name."); + } + + try { + indexedDB.open(name, { version: 0 }); + ok(false, "Should have thrown!"); + } catch (e) { + ok(e instanceof TypeError, "Got TypeError."); + is(e.name, "TypeError", "Good error name."); + } + + try { + indexedDB.open(name, { version: -1 }); + ok(false, "Should have thrown!"); + } catch (e) { + ok(e instanceof TypeError, "Got TypeError."); + is(e.name, "TypeError", "Good error name."); + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_invalidate.js b/dom/indexedDB/test/unit/test_invalidate.js new file mode 100644 index 0000000000..5058756ff5 --- /dev/null +++ b/dom/indexedDB/test/unit/test_invalidate.js @@ -0,0 +1,85 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const databaseName = "window" in this ? window.location.pathname : "Test"; + + let dbCount = 0; + + // Test invalidating during a versionchange transaction. + info("Opening database " + ++dbCount); + + let request = indexedDB.open(databaseName, dbCount); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + let event = yield undefined; + + is(event.type, "upgradeneeded", "Upgrading database " + dbCount); + + request.onupgradeneeded = unexpectedSuccessHandler; + + let objStore = request.result.createObjectStore("foo", { + autoIncrement: true, + }); + objStore.createIndex("fooIndex", "fooIndex", { unique: true }); + objStore.put({ foo: 1 }); + objStore.get(1); + objStore.count(); + objStore.openCursor(); + objStore.delete(1); + + info("Invalidating database " + dbCount); + + clearAllDatabases(continueToNextStepSync); + + objStore = request.result.createObjectStore("bar"); + objStore.createIndex("barIndex", "barIndex", { multiEntry: true }); + objStore.put({ bar: 1, barIndex: [0, 1] }, 10); + objStore.get(10); + objStore.count(); + objStore.openCursor(); + objStore.delete(10); + + yield undefined; + + executeSoon(continueToNextStepSync); + yield undefined; + + // Test invalidating after the complete event of a versionchange transaction. + info("Opening database " + ++dbCount); + + request = indexedDB.open(databaseName, dbCount); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + event = yield undefined; + + is(event.type, "upgradeneeded", "Upgrading database " + dbCount); + + request.onupgradeneeded = unexpectedSuccessHandler; + + request.transaction.oncomplete = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.type, + "complete", + "Got complete event for versionchange transaction on database " + dbCount + ); + + info("Invalidating database " + dbCount); + + clearAllDatabases(continueToNextStepSync); + yield undefined; + + executeSoon(continueToNextStepSync); + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_key_requirements.js b/dom/indexedDB/test/unit/test_key_requirements.js new file mode 100644 index 0000000000..1e5b8f22c1 --- /dev/null +++ b/dom/indexedDB/test/unit/test_key_requirements.js @@ -0,0 +1,266 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + db.addEventListener("error", function (event) { + event.preventDefault(); + }); + + let objectStore = db.createObjectStore("foo", { autoIncrement: true }); + + request = objectStore.add({}); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + let key1 = event.target.result; + + request = objectStore.put({}, key1); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, key1, "put gave the same key back"); + + let key2 = 10; + + request = objectStore.put({}, key2); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, key2, "put gave the same key back"); + + key2 = 100; + + request = objectStore.add({}, key2); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, key2, "put gave the same key back"); + + try { + objectStore.put({}); + ok(true, "put with no key should not throw with autoIncrement!"); + } catch (e) { + ok(false, "put with no key threw with autoIncrement"); + } + + try { + objectStore.put({}); + ok(true, "put with no key should not throw with autoIncrement!"); + } catch (e) { + ok(false, "put with no key threw with autoIncrement"); + } + + try { + objectStore.delete(); + ok(false, "remove with no key should throw!"); + } catch (e) { + ok(true, "remove with no key threw"); + } + + objectStore = db.createObjectStore("bar"); + + try { + objectStore.add({}); + ok(false, "add with no key should throw!"); + } catch (e) { + ok(true, "add with no key threw"); + } + + try { + objectStore.put({}); + ok(false, "put with no key should throw!"); + } catch (e) { + ok(true, "put with no key threw"); + } + + try { + objectStore.put({}); + ok(false, "put with no key should throw!"); + } catch (e) { + ok(true, "put with no key threw"); + } + + try { + objectStore.delete(); + ok(false, "remove with no key should throw!"); + } catch (e) { + ok(true, "remove with no key threw"); + } + + objectStore = db.createObjectStore("baz", { keyPath: "id" }); + + try { + objectStore.add({}); + ok(false, "add with no key should throw!"); + } catch (e) { + ok(true, "add with no key threw"); + } + + try { + objectStore.add({ id: 5 }, 5); + ok(false, "add with inline key and passed key should throw!"); + } catch (e) { + ok(true, "add with inline key and passed key threw"); + } + + try { + objectStore.put({}); + ok(false, "put with no key should throw!"); + } catch (e) { + ok(true, "put with no key threw"); + } + + try { + objectStore.put({}); + ok(false, "put with no key should throw!"); + } catch (e) { + ok(true, "put with no key threw"); + } + + try { + objectStore.delete(); + ok(false, "remove with no key should throw!"); + } catch (e) { + ok(true, "remove with no key threw"); + } + + key1 = 10; + + request = objectStore.add({ id: key1 }); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, key1, "add gave back the same key"); + + request = objectStore.put({ id: 10 }); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, key1, "put gave back the same key"); + + request = objectStore.put({ id: 10 }); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, key1, "put gave back the same key"); + + request = objectStore.add({ id: 10 }); + request.addEventListener("error", new ExpectError("ConstraintError", true)); + request.onsuccess = unexpectedSuccessHandler; + event = yield undefined; + + try { + objectStore.add({}, null); + ok(false, "add with null key should throw!"); + } catch (e) { + ok(true, "add with null key threw"); + } + + try { + objectStore.put({}, null); + ok(false, "put with null key should throw!"); + } catch (e) { + ok(true, "put with null key threw"); + } + + try { + objectStore.put({}, null); + ok(false, "put with null key should throw!"); + } catch (e) { + ok(true, "put with null key threw"); + } + + try { + objectStore.delete({}, null); + ok(false, "remove with null key should throw!"); + } catch (e) { + ok(true, "remove with null key threw"); + } + + objectStore = db.createObjectStore("bazing", { + keyPath: "id", + autoIncrement: true, + }); + + request = objectStore.add({}); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + key1 = event.target.result; + + request = objectStore.put({ id: key1 }); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, key1, "put gave the same key back"); + + key2 = 10; + + request = objectStore.put({ id: key2 }); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, key2, "put gave the same key back"); + + try { + objectStore.put({}); + ok(true, "put with no key should not throw with autoIncrement!"); + } catch (e) { + ok(false, "put with no key threw with autoIncrement"); + } + + try { + objectStore.put({}); + ok(true, "put with no key should not throw with autoIncrement!"); + } catch (e) { + ok(false, "put with no key threw with autoIncrement"); + } + + try { + objectStore.delete(); + ok(false, "remove with no key should throw!"); + } catch (e) { + ok(true, "remove with no key threw"); + } + + try { + objectStore.add({ id: 5 }, 5); + ok(false, "add with inline key and passed key should throw!"); + } catch (e) { + ok(true, "add with inline key and passed key threw"); + } + + request = objectStore.delete(key2); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + // Wait for success + yield undefined; + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_keys.js b/dom/indexedDB/test/unit/test_keys.js new file mode 100644 index 0000000000..e3f8d6abba --- /dev/null +++ b/dom/indexedDB/test/unit/test_keys.js @@ -0,0 +1,350 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +// helper function that ensures that ArrayBuffer instances are meaningfully +// displayed (not just as 'object ArrayBuffer') +// TODO better move to helpers.js? +function showKey(key) { + if (key instanceof Array) { + return key.map(x => showKey(x)).toString(); + } + if (key instanceof ArrayBuffer) { + return "ArrayBuffer([" + new Uint8Array(key).toString() + "])"; + } + return key.toString(); +} + +function* testSteps() { + const dbname = this.window ? window.location.pathname : "Splendid Test"; + + let openRequest = indexedDB.open(dbname, 1); + openRequest.onerror = errorHandler; + openRequest.onupgradeneeded = grabEventAndContinueHandler; + openRequest.onsuccess = unexpectedSuccessHandler; + let event = yield undefined; + let db = event.target.result; + + // Create test stores + let store = db.createObjectStore("store"); + let enc = new TextEncoder(); + + // Test simple inserts + // Note: the keys must be in order + var keys = [ + -1 / 0, + -1.7e308, + -10000, + -2, + -1.5, + -1, + -1.00001e-200, + -1e-200, + 0, + 1e-200, + 1.00001e-200, + 1, + 2, + 10000, + 1.7e308, + 1 / 0, + new Date("1750-01-02"), + new Date("1800-12-31T12:34:56.001"), + new Date(-1000), + new Date(-10), + new Date(-1), + new Date(0), + new Date(1), + new Date(2), + new Date(1000), + new Date("1971-01-01"), + new Date("1971-01-01T01:01:01Z"), + new Date("1971-01-01T01:01:01.001Z"), + new Date("1971-01-01T01:01:01.01Z"), + new Date("1971-01-01T01:01:01.1Z"), + new Date("1980-02-02"), + new Date("3333-03-19T03:33:33.333"), + "", + "\x00", + "\x00\x00", + "\x00\x01", + "\x01", + "\x02", + "\x03", + "\x04", + "\x07", + "\x08", + "\x0F", + "\x10", + "\x1F", + "\x20", + "01234", + "\x3F", + "\x40", + "A", + "A\x00", + "A1", + "ZZZZ", + "a", + "a\x00", + "aa", + "azz", + "}", + "\x7E", + "\x7F", + "\x80", + "\xFF", + "\u0100", + "\u01FF", + "\u0200", + "\u03FF", + "\u0400", + "\u07FF", + "\u0800", + "\u0FFF", + "\u1000", + "\u1FFF", + "\u2000", + "\u3FFF", + "\u4000", + "\u7FFF", + "\u8000", + "\uD800", + "\uD800a", + "\uD800\uDC01", + "\uDBFF", + "\uDC00", + "\uDFFF\uD800", + "\uFFFE", + "\uFFFF", + "\uFFFF\x00", + "\uFFFFZZZ", + // Note: enc.encode returns an Uint8Array, which is a valid key, but when + // converting it back and forth, the result will be a plain ArrayBuffer, + // which is expected in comparisons below + // TODO is it ok that the information that the original key was an + // Uint8Array is lost? + new ArrayBuffer(0), + Uint8Array.from([0]).buffer, + Uint8Array.from([0, 0]).buffer, + Uint8Array.from([0, 1]).buffer, + Uint8Array.from([0, 1, 0]).buffer, + enc.encode("abc").buffer, + enc.encode("abcd").buffer, + enc.encode("xyz").buffer, + Uint8Array.from([0x80]).buffer, + [], + [-1 / 0], + [-1], + [0], + [1], + [1, "a"], + [1, []], + [1, [""]], + [2, 3], + [2, 3.0000000000001], + [12, [[]]], + [12, [[[]]]], + [12, [[[""]]]], + [12, [[["foo"]]]], + [12, [[[[[3]]]]]], + [12, [[[[[[3]]]]]]], + [new Date(-1)], + [new Date(1)], + [""], + ["", [[]]], + ["", [[[]]]], + ["abc"], + ["abc", "def"], + ["abc\x00"], + ["abc\x00", "\x00\x01"], + ["abc\x00", "\x00def"], + ["abc\x00\x00def"], + ["x", [[]]], + ["x", [[[]]]], + // see comment on scalar ArrayBuffers above + [new ArrayBuffer(0)], + [new ArrayBuffer(0), "abc"], + [new ArrayBuffer(0), new ArrayBuffer(0)], + [new ArrayBuffer(0), enc.encode("abc").buffer], + [enc.encode("abc").buffer], + [enc.encode("abc").buffer, new ArrayBuffer(0)], + [enc.encode("abc").buffer, enc.encode("xyz").buffer], + [enc.encode("xyz").buffer], + [[]], + [[], "foo"], + [[], []], + [[[]]], + [[[]], []], + [[[]], [[]]], + [[[]], [[1]]], + [[[]], [[[]]]], + [[[1]]], + [[[[]], []]], + ]; + + for (var i = 0; i < keys.length; ++i) { + let keyI = keys[i]; + is(indexedDB.cmp(keyI, keyI), 0, i + " compared to self"); + + function doCompare(keyI) { + for (var j = i - 1; j >= i - 10 && j >= 0; --j) { + is(indexedDB.cmp(keyI, keys[j]), 1, i + " compared to " + j); + is(indexedDB.cmp(keys[j], keyI), -1, j + " compared to " + i); + } + } + + doCompare(keyI); + store.add(i, keyI).onsuccess = function (e) { + is( + indexedDB.cmp(e.target.result, keyI), + 0, + "Returned key should cmp as equal; index = " + + i + + ", input = " + + showKey(keyI) + + ", returned = " + + showKey(e.target.result) + ); + ok( + compareKeys(e.target.result, keyI), + "Returned key should actually be equal; index = " + + i + + ", input = " + + showKey(keyI) + + ", returned = " + + showKey(e.target.result) + ); + }; + + // Test that -0 compares the same as 0 + if (keyI === 0) { + doCompare(-0); + let req = store.add(i, -0); + req.addEventListener("error", new ExpectError("ConstraintError", true)); + req.onsuccess = unexpectedSuccessHandler; + yield undefined; + } else if (Array.isArray(keyI) && keyI.length === 1 && keyI[0] === 0) { + doCompare([-0]); + let req = store.add(i, [-0]); + req.addEventListener("error", new ExpectError("ConstraintError", true)); + req.onsuccess = unexpectedSuccessHandler; + yield undefined; + } + } + + store.openCursor().onsuccess = grabEventAndContinueHandler; + for (i = 0; i < keys.length; ++i) { + event = yield undefined; + let cursor = event.target.result; + is( + indexedDB.cmp(cursor.key, keys[i]), + 0, + "Read back key should cmp as equal; index = " + + i + + ", input = " + + showKey(keys[i]) + + ", readBack = " + + showKey(cursor.key) + ); + ok( + compareKeys(cursor.key, keys[i]), + "Read back key should actually be equal; index = " + + i + + ", input = " + + showKey(keys[i]) + + ", readBack = " + + showKey(cursor.key) + ); + is(cursor.value, i, "Stored with right value"); + + cursor.continue(); + } + event = yield undefined; + is(event.target.result, null, "no more results expected"); + + // Note that nan is defined below as '0 / 0'. + var invalidKeys = [ + "nan", + "undefined", + "null", + "/x/", + "{}", + "new Date(NaN)", + 'new Date("foopy")', + "[nan]", + "[undefined]", + "[null]", + "[/x/]", + "[{}]", + "[new Date(NaN)]", + "[1, nan]", + "[1, undefined]", + "[1, null]", + "[1, /x/]", + "[1, {}]", + "[1, [nan]]", + "[1, [undefined]]", + "[1, [null]]", + "[1, [/x/]]", + "[1, [{}]]", + // ATTENTION, the following key allocates 2GB of memory and might cause + // subtle failures in some environments, see bug 1796753. We might + // want to have some common way between IndexeDB mochitests and + // xpcshell tests how to access AppConstants in order to dynamically + // exclude this key from some environments, rather than disabling the + // entire xpcshell variant of this test for ASAN/TSAN. + "new Uint8Array(2147483647)", + ]; + + function checkInvalidKeyException(ex, i, callText) { + let suffix = ` during ${callText} with invalid key ${i}: ${invalidKeys[i]}`; + // isInstance() is not available in mochitest, and we use this JS also as mochitest. + // eslint-disable-next-line mozilla/use-isInstance + ok(ex instanceof DOMException, "Threw DOMException" + suffix); + is(ex.name, "DataError", "Threw right DOMException" + suffix); + is(ex.code, 0, "Threw with right code" + suffix); + } + + for (i = 0; i < invalidKeys.length; ++i) { + let key_fn = Function( + `"use strict"; var nan = 0 / 0; let k = (${invalidKeys[i]}); return k;` + ); + let key; + try { + key = key_fn(); + } catch (e) { + // If we cannot instantiate the key, we are most likely on a 32 Bit + // platform with insufficient memory. Just skip it. + info("Key instantiation failed, skipping"); + continue; + } + try { + indexedDB.cmp(key, 1); + ok(false, "didn't throw"); + } catch (ex) { + checkInvalidKeyException(ex, i, "cmp(key, 1)"); + } + try { + indexedDB.cmp(1, key); + ok(false, "didn't throw2"); + } catch (ex) { + checkInvalidKeyException(ex, i, "cmp(1, key)"); + } + try { + store.put(1, key); + ok(false, "didn't throw3"); + } catch (ex) { + checkInvalidKeyException(ex, i, "store.put(1, key)"); + } + } + + openRequest.onsuccess = grabEventAndContinueHandler; + yield undefined; + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_locale_aware_index_getAll.js b/dom/indexedDB/test/unit/test_locale_aware_index_getAll.js new file mode 100644 index 0000000000..c73e9d77e6 --- /dev/null +++ b/dom/indexedDB/test/unit/test_locale_aware_index_getAll.js @@ -0,0 +1,212 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const objectStoreName = "People"; + + const objectStoreData = [ + { + key: "237-23-7732", + value: { name: "\u00E1na", height: 60, weight: 120 }, + }, + { key: "237-23-7733", value: { name: "ana", height: 52, weight: 110 } }, + { key: "237-23-7734", value: { name: "fabio", height: 73, weight: 180 } }, + { + key: "237-23-7735", + value: { name: "\u00F3scar", height: 58, weight: 130 }, + }, + { key: "237-23-7736", value: { name: "bob", height: 65, weight: 150 } }, + { key: "237-23-7737", value: { name: "\u00E9ason", height: 65 } }, + ]; + + const indexData = [ + { name: "name", keyPath: "name", options: { unique: true, locale: true } }, + { + name: "height", + keyPath: "height", + options: { unique: false, locale: true }, + }, + { + name: "weight", + keyPath: "weight", + options: { unique: false, locale: true }, + }, + ]; + + const objectStoreDataHeightSort = [ + { key: "237-23-7733", value: { name: "ana", height: 52, weight: 110 } }, + { + key: "237-23-7735", + value: { name: "\u00F3scar", height: 58, weight: 130 }, + }, + { + key: "237-23-7732", + value: { name: "\u00E1na", height: 60, weight: 120 }, + }, + { key: "237-23-7736", value: { name: "bob", height: 65, weight: 150 } }, + { key: "237-23-7737", value: { name: "\u00E9ason", height: 65 } }, + { key: "237-23-7734", value: { name: "fabio", height: 73, weight: 180 } }, + ]; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + + let objectStore = db.createObjectStore(objectStoreName); + + // First, add all our data to the object store. + let addedData = 0; + for (let i in objectStoreData) { + request = objectStore.add(objectStoreData[i].value, objectStoreData[i].key); + request.onerror = errorHandler; + request.onsuccess = function (event) { + if (++addedData == objectStoreData.length) { + testGenerator.next(event); + } + }; + } + yield undefined; + ok(true, "1"); + + // Now create the indexes. + for (let i in indexData) { + objectStore.createIndex( + indexData[i].name, + indexData[i].keyPath, + indexData[i].options + ); + } + + is(objectStore.indexNames.length, indexData.length, "Good index count"); + yield undefined; + + ok(true, "2"); + objectStore = db.transaction(objectStoreName).objectStore(objectStoreName); + + request = objectStore.index("height").mozGetAllKeys(65); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + ok(true, "3"); + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 2, "Correct length"); + + for (let i in event.target.result) { + is( + event.target.result[i], + objectStoreDataHeightSort[parseInt(i) + 3].key, + "Correct key" + ); + } + + request = objectStore.index("height").mozGetAllKeys(65, 0); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + ok(true, "3"); + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 2, "Correct length"); + + for (let i in event.target.result) { + is( + event.target.result[i], + objectStoreDataHeightSort[parseInt(i) + 3].key, + "Correct key" + ); + } + + request = objectStore.index("height").mozGetAllKeys(65, null); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + ok(true, "3"); + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 2, "Correct length"); + + for (let i in event.target.result) { + is( + event.target.result[i], + objectStoreDataHeightSort[parseInt(i) + 3].key, + "Correct key" + ); + } + + request = objectStore.index("height").mozGetAllKeys(65, undefined); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + ok(true, "3"); + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 2, "Correct length"); + + for (let i in event.target.result) { + is( + event.target.result[i], + objectStoreDataHeightSort[parseInt(i) + 3].key, + "Correct key" + ); + } + + request = objectStore.index("height").mozGetAllKeys(); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + ok(true, "4"); + + is(event.target.result instanceof Array, true, "Got an array object"); + is( + event.target.result.length, + objectStoreDataHeightSort.length, + "Correct length" + ); + + for (let i in event.target.result) { + is(event.target.result[i], objectStoreDataHeightSort[i].key, "Correct key"); + } + + request = objectStore.index("height").mozGetAllKeys(null, 4); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + ok(true, "5"); + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 4, "Correct length"); + + for (let i in event.target.result) { + is(event.target.result[i], objectStoreDataHeightSort[i].key, "Correct key"); + } + + request = objectStore.index("height").mozGetAllKeys(65, 1); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + ok(true, "6"); + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 1, "Correct length"); + + for (let i in event.target.result) { + is( + event.target.result[i], + objectStoreDataHeightSort[parseInt(i) + 3].key, + "Correct key" + ); + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_locale_aware_index_getAllObjects.js b/dom/indexedDB/test/unit/test_locale_aware_index_getAllObjects.js new file mode 100644 index 0000000000..be51d3bf2e --- /dev/null +++ b/dom/indexedDB/test/unit/test_locale_aware_index_getAllObjects.js @@ -0,0 +1,239 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const objectStoreName = "People"; + + const objectStoreData = [ + { + key: "237-23-7732", + value: { name: "\u00E1na", height: 60, weight: 120 }, + }, + { key: "237-23-7733", value: { name: "ana", height: 52, weight: 110 } }, + { key: "237-23-7734", value: { name: "fabio", height: 73, weight: 180 } }, + { + key: "237-23-7735", + value: { name: "\u00F3scar", height: 58, weight: 130 }, + }, + { key: "237-23-7736", value: { name: "bob", height: 65, weight: 150 } }, + { key: "237-23-7737", value: { name: "\u00E9ason", height: 65 } }, + ]; + + const indexData = [ + { name: "name", keyPath: "name", options: { unique: true, locale: true } }, + { + name: "height", + keyPath: "height", + options: { unique: false, locale: true }, + }, + { + name: "weight", + keyPath: "weight", + options: { unique: false, locale: true }, + }, + ]; + + const objectStoreDataHeightSort = [ + { key: "237-23-7733", value: { name: "ana", height: 52, weight: 110 } }, + { + key: "237-23-7735", + value: { name: "\u00F3scar", height: 58, weight: 130 }, + }, + { + key: "237-23-7732", + value: { name: "\u00E1na", height: 60, weight: 120 }, + }, + { key: "237-23-7736", value: { name: "bob", height: 65, weight: 150 } }, + { key: "237-23-7737", value: { name: "\u00E9ason", height: 65 } }, + { key: "237-23-7734", value: { name: "fabio", height: 73, weight: 180 } }, + ]; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + + let objectStore = db.createObjectStore(objectStoreName, {}); + + // First, add all our data to the object store. + let addedData = 0; + for (let i in objectStoreData) { + request = objectStore.add(objectStoreData[i].value, objectStoreData[i].key); + request.onerror = errorHandler; + request.onsuccess = function (event) { + if (++addedData == objectStoreData.length) { + testGenerator.next(event); + } + }; + } + event = yield undefined; + + // Now create the indexes. + for (let i in indexData) { + objectStore.createIndex( + indexData[i].name, + indexData[i].keyPath, + indexData[i].options + ); + } + + is(objectStore.indexNames.length, indexData.length, "Good index count"); + yield undefined; + + objectStore = db.transaction(objectStoreName).objectStore(objectStoreName); + + request = objectStore.index("height").mozGetAll(65); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 2, "Correct length"); + + for (let i in event.target.result) { + let result = event.target.result[i]; + let testObj = objectStoreDataHeightSort[parseInt(i) + 3].value; + + is(result.name, testObj.name, "Correct name"); + is(result.height, testObj.height, "Correct height"); + + if (testObj.hasOwnProperty("weight")) { + is(result.weight, testObj.weight, "Correct weight"); + } + } + + request = objectStore.index("height").mozGetAll(65, 0); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 2, "Correct length"); + + for (let i in event.target.result) { + let result = event.target.result[i]; + let testObj = objectStoreDataHeightSort[parseInt(i) + 3].value; + + is(result.name, testObj.name, "Correct name"); + is(result.height, testObj.height, "Correct height"); + + if (testObj.hasOwnProperty("weight")) { + is(result.weight, testObj.weight, "Correct weight"); + } + } + + request = objectStore.index("height").mozGetAll(65, null); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 2, "Correct length"); + + for (let i in event.target.result) { + let result = event.target.result[i]; + let testObj = objectStoreDataHeightSort[parseInt(i) + 3].value; + + is(result.name, testObj.name, "Correct name"); + is(result.height, testObj.height, "Correct height"); + + if (testObj.hasOwnProperty("weight")) { + is(result.weight, testObj.weight, "Correct weight"); + } + } + + request = objectStore.index("height").mozGetAll(65, undefined); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 2, "Correct length"); + + for (let i in event.target.result) { + let result = event.target.result[i]; + let testObj = objectStoreDataHeightSort[parseInt(i) + 3].value; + + is(result.name, testObj.name, "Correct name"); + is(result.height, testObj.height, "Correct height"); + + if (testObj.hasOwnProperty("weight")) { + is(result.weight, testObj.weight, "Correct weight"); + } + } + + request = objectStore.index("height").mozGetAll(); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is( + event.target.result.length, + objectStoreDataHeightSort.length, + "Correct length" + ); + + for (let i in event.target.result) { + let result = event.target.result[i]; + let testObj = objectStoreDataHeightSort[i].value; + + is(result.name, testObj.name, "Correct name"); + is(result.height, testObj.height, "Correct height"); + + if (testObj.hasOwnProperty("weight")) { + is(result.weight, testObj.weight, "Correct weight"); + } + } + + request = objectStore.index("height").mozGetAll(null, 4); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 4, "Correct length"); + + for (let i in event.target.result) { + let result = event.target.result[i]; + let testObj = objectStoreDataHeightSort[i].value; + + is(result.name, testObj.name, "Correct name"); + is(result.height, testObj.height, "Correct height"); + + if (testObj.hasOwnProperty("weight")) { + is(result.weight, testObj.weight, "Correct weight"); + } + } + + request = objectStore.index("height").mozGetAll(65, 1); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array object"); + is(event.target.result.length, 1, "Correct length"); + + for (let i in event.target.result) { + let result = event.target.result[i]; + let testObj = objectStoreDataHeightSort[parseInt(i) + 3].value; + + is(result.name, testObj.name, "Correct name"); + is(result.height, testObj.height, "Correct height"); + + if (testObj.hasOwnProperty("weight")) { + is(result.weight, testObj.weight, "Correct weight"); + } + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_marker_file.js b/dom/indexedDB/test/unit/test_marker_file.js new file mode 100644 index 0000000000..342f78f34d --- /dev/null +++ b/dom/indexedDB/test/unit/test_marker_file.js @@ -0,0 +1,91 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +function getTestingFiles() { + const filenameBase = "3128029391StpsleeTn+ddi"; + let baseDir = getRelativeFile("storage/permanent/chrome/idb"); + + let dbFile = baseDir.clone(); + dbFile.append(filenameBase + ".sqlite"); + + let dir = baseDir.clone(); + dir.append(filenameBase + ".files"); + + let markerFile = baseDir.clone(); + markerFile.append("idb-deleting-" + filenameBase); + + return { dbFile, dir, markerFile }; +} + +function createTestingEnvironment(markerFileOnly = false) { + let testingFiles = getTestingFiles(); + + if (!markerFileOnly) { + testingFiles.dbFile.create( + Ci.nsIFile.NORMAL_FILE_TYPE, + parseInt("0644", 8) + ); + + testingFiles.dir.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt("0755", 8)); + } + + testingFiles.markerFile.create( + Ci.nsIFile.NORMAL_FILE_TYPE, + parseInt("0644", 8) + ); +} + +/** + * This test verifies the initialization, indexedDB.open(), and + * indexedDB.deleteDatabase() aren't blocked when there are unexpected files + * which haven't been deleted due to some reasons. Normally, we expect every + * delete operation works fine. Hoever, it's reported that there is only a + * directory without a corresponding database. It's probably because the delete + * operation fails for some reasons. P1 introduces the mark-file to let the + * future operation understand whether there might be unexpected files in idb + * directory. And, this test verifies these three things work fine if a + * marker-file, a databse file, and a directory exist in current idb directory. + */ + +/* exported testSteps */ +async function testSteps() { + SpecialPowers.setBoolPref("dom.quotaManager.testing", true); + + const name = this.window ? window.location.pathname : "Splendid Test"; + + info("Verifying initialization"); + + let request = initStorage(); + await requestFinished(request); + + createTestingEnvironment(); + + request = initPersistentOrigin(getSystemPrincipal()); + await requestFinished(request); + + let testingFiles = getTestingFiles(); + ok(!testingFiles.dbFile.exists(), "The obsolete database file doesn't exist"); + ok(!testingFiles.dir.exists(), "The obsolete directory doesn't exist"); + ok(!testingFiles.markerFile.exists(), "The marker file doesn't exist"); + + info("Verifying open shouldn't be blocked by unexpected files"); + + createTestingEnvironment(); + + request = indexedDB.open(name); + await expectingUpgrade(request); + let event = await expectingSuccess(request); + ok(true, "The database was opened successfully"); + let db = event.target.result; + db.close(); + + info("Verifying deleteDatabase isn't blocked by unexpected files"); + + createTestingEnvironment(true); + + request = indexedDB.deleteDatabase(name); + await expectingSuccess(request); + ok(true, "The database was deleted successfully"); +} diff --git a/dom/indexedDB/test/unit/test_maximal_serialized_object_size.js b/dom/indexedDB/test/unit/test_maximal_serialized_object_size.js new file mode 100644 index 0000000000..64ee2a0b9a --- /dev/null +++ b/dom/indexedDB/test/unit/test_maximal_serialized_object_size.js @@ -0,0 +1,109 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator, disableWorkerTest */ +var disableWorkerTest = "Need a way to set temporary prefs from a worker"; + +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window + ? window.location.pathname + : "test_maximal_serialized_object_size.js"; + const megaBytes = 1024 * 1024; + const kMessageOverhead = 1; // in MB + const kMaxIpcMessageSize = 20; // in MB + const kMaxIdbMessageSize = kMaxIpcMessageSize - kMessageOverhead; + + let chunks = new Array(kMaxIdbMessageSize); + for (let i = 0; i < kMaxIdbMessageSize; i++) { + chunks[i] = new ArrayBuffer(1 * megaBytes); + } + + if (this.window) { + SpecialPowers.pushPrefEnv( + { + set: [ + [ + "dom.indexedDB.maxSerializedMsgSize", + kMaxIpcMessageSize * megaBytes, + ], + ], + }, + continueToNextStep + ); + yield undefined; + } else { + setMaxSerializedMsgSize(kMaxIpcMessageSize * megaBytes); + } + + let openRequest = indexedDB.open(name, 1); + openRequest.onerror = errorHandler; + openRequest.onupgradeneeded = grabEventAndContinueHandler; + openRequest.onsuccess = unexpectedSuccessHandler; + let event = yield undefined; + + let db = event.target.result; + + is(db.objectStoreNames.length, 0, "Correct objectStoreNames list"); + + let objectStore = db.createObjectStore("test store", { keyPath: "id" }); + is(db.objectStoreNames.length, 1, "Correct objectStoreNames list"); + is( + db.objectStoreNames.item(0), + objectStore.name, + "Correct object store name" + ); + + function testTooLargeError(aOperation, aObject) { + try { + objectStore[aOperation](aObject).onerror = errorHandler; + ok(false, "UnknownError is expected to be thrown!"); + } catch (e) { + ok(e instanceof DOMException, "got a DOM exception"); + is(e.name, "UnknownError", "correct error"); + ok(!!e.message, "Error message: " + e.message); + ok( + e.message.startsWith( + `IDBObjectStore.${aOperation}: The serialized value is too large` + ), + "Correct error message prefix." + ); + } + } + + info("Verify IDBObjectStore.add() - object is too large"); + testTooLargeError("add", { id: 1, data: chunks }); + + info( + "Verify IDBObjectStore.add() - object size is closed to the maximal size." + ); + chunks.length = chunks.length - 1; + let request = objectStore.add({ id: 1, data: chunks }); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + yield undefined; + + info("Verify IDBObjectStore.add() - object key is too large"); + chunks.length = 10; + testTooLargeError("add", { id: chunks }); + + objectStore.createIndex("index name", "index"); + ok(objectStore.index("index name"), "Index created."); + + info("Verify IDBObjectStore.add() - index key is too large"); + testTooLargeError("add", { id: 2, index: chunks }); + + info("Verify IDBObjectStore.add() - object key and index key are too large"); + let indexChunks = chunks.splice(0, 5); + testTooLargeError("add", { id: chunks, index: indexChunks }); + + openRequest.onsuccess = continueToNextStep; + yield undefined; + + db.close(); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_metadata2Restore.js b/dom/indexedDB/test/unit/test_metadata2Restore.js new file mode 100644 index 0000000000..da31eecc86 --- /dev/null +++ b/dom/indexedDB/test/unit/test_metadata2Restore.js @@ -0,0 +1,328 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const openParams = [ + // This one lives in storage/default/http+++localhost+81^userContextId=1 + // The .metadata-v2 file was intentionally removed for this origin directory + // to test restoring. + { + attrs: { userContextId: 1 }, + url: "http://localhost:81", + dbName: "dbC", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+82^userContextId=1 + // The .metadata-v2 file was intentionally truncated for this origin directory + // to test restoring. + { + attrs: { userContextId: 1 }, + url: "http://localhost:82", + dbName: "dbD", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+83^userContextId=1 + // The .metadata-v2 file was intentionally modified to contain only + // 4 bytes of the 64 bit timestamp + // for this origin directory to test restoring. + { + attrs: { userContextId: 1 }, + url: "http://localhost:83", + dbName: "dbE", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+84^userContextId=1 + // The .metadata-v2 file was intentionally modified to contain only + // the 64 bit timestamp + // for this origin directory to test restoring. + { + attrs: { userContextId: 1 }, + url: "http://localhost:84", + dbName: "dbF", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+85^userContextId=1 + // The .metadata-v2 file was intentionally modified to contain only + // the 64 bit timestamp and + // the 8 bit persisted flag + // for this origin directory to test restoring. + { + attrs: { userContextId: 1 }, + url: "http://localhost:85", + dbName: "dbG", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+86^userContextId=1 + // The .metadata-v2 file was intentionally modified to contain only + // the 64 bit timestamp, + // the 8 bit persisted flag and + // 2 bytes of the 32 bit reserved data 1 + // for this origin directory to test restoring. + { + attrs: { userContextId: 1 }, + url: "http://localhost:86", + dbName: "dbH", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+87^userContextId=1 + // The .metadata-v2 file was intentionally modified to contain only + // the 64 bit timestamp, + // the 8 bit persisted flag and + // the 32 bit reserved data 1 + // for this origin directory to test restoring. + { + attrs: { userContextId: 1 }, + url: "http://localhost:87", + dbName: "dbI", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+88^userContextId=1 + // The .metadata-v2 file was intentionally modified to contain only + // the 64 bit timestamp, + // the 8 bit persisted flag, + // the 32 bit reserved data 1 and + // 2 bytes of the 32 bit reserved data 2 + // for this origin directory to test restoring. + { + attrs: { userContextId: 1 }, + url: "http://localhost:88", + dbName: "dbJ", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+89^userContextId=1 + // The .metadata-v2 file was intentionally modified to contain only + // the 64 bit timestamp, + // the 8 bit persisted flag, + // the 32 bit reserved data 1 and + // the 32 bit reserved data 2 + // for this origin directory to test restoring. + { + attrs: { userContextId: 1 }, + url: "http://localhost:89", + dbName: "dbK", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+90^userContextId=1 + // The .metadata-v2 file was intentionally modified to contain only + // the 64 bit timestamp, + // the 8 bit persisted flag, + // the 32 bit reserved data 1, + // the 32 bit reserved data 2 and + // 2 bytes of the 32 bit suffix length + // for this origin directory to test restoring. + { + attrs: { userContextId: 1 }, + url: "http://localhost:90", + dbName: "dbL", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+91^userContextId=1 + // The .metadata-v2 file was intentionally modified to contain only + // the 64 bit timestamp, + // the 8 bit persisted flag, + // the 32 bit reserved data 1, + // the 32 bit reserved data 2, + // the 32 bit suffix length and + // first 5 chars of the suffix + // for this origin directory to test restoring. + { + attrs: { userContextId: 1 }, + url: "http://localhost:91", + dbName: "dbM", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+92^userContextId=1 + // The .metadata-v2 file was intentionally modified to contain only + // the 64 bit timestamp, + // the 8 bit persisted flag, + // the 32 bit reserved data 1, + // the 32 bit reserved data 2, + // the 32 bit suffix length and + // the suffix + // for this origin directory to test restoring. + { + attrs: { userContextId: 1 }, + url: "http://localhost:92", + dbName: "dbN", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+93^userContextId=1 + // The .metadata-v2 file was intentionally modified to contain only + // the 64 bit timestamp, + // the 8 bit persisted flag, + // the 32 bit reserved data 1, + // the 32 bit reserved data 2, + // the 32 bit suffix length, + // the suffix and + // 2 bytes of the 32 bit group length + // for this origin directory to test restoring. + { + attrs: { userContextId: 1 }, + url: "http://localhost:93", + dbName: "dbO", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+94^userContextId=1 + // The .metadata-v2 file was intentionally modified to contain only + // the 64 bit timestamp, + // the 8 bit persisted flag, + // the 32 bit reserved data 1, + // the 32 bit reserved data 2, + // the 32 bit suffix length, + // the suffix, + // the 32 bit group length and + // first 5 chars of the group + // for this origin directory to test restoring. + { + attrs: { userContextId: 1 }, + url: "http://localhost:94", + dbName: "dbP", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+95^userContextId=1 + // The .metadata-v2 file was intentionally modified to contain only + // the 64 bit timestamp, + // the 8 bit persisted flag, + // the 32 bit reserved data 1, + // the 32 bit reserved data 2, + // the 32 bit suffix length, + // the suffix, + // the 32 bit group length and + // the group + // for this origin directory to test restoring. + { + attrs: { userContextId: 1 }, + url: "http://localhost:95", + dbName: "dbQ", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+96^userContextId=1 + // The .metadata-v2 file was intentionally modified to contain only + // the 64 bit timestamp, + // the 8 bit persisted flag, + // the 32 bit reserved data 1, + // the 32 bit reserved data 2, + // the 32 bit suffix length, + // the suffix, + // the 32 bit group length, + // the group and + // 2 bytes of the 32 bit origin length + // for this origin directory to test restoring. + { + attrs: { userContextId: 1 }, + url: "http://localhost:96", + dbName: "dbR", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+97^userContextId=1 + // The .metadata-v2 file was intentionally modified to contain only + // the 64 bit timestamp, + // the 8 bit persisted flag, + // the 32 bit reserved data 1, + // the 32 bit reserved data 2, + // the 32 bit suffix length, + // the suffix, + // the 32 bit group length, + // the group, + // the 32 bit origin length and + // first 12 char of the origin + // for this origin directory to test restoring. + { + attrs: { userContextId: 1 }, + url: "http://localhost:97", + dbName: "dbS", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+98^userContextId=1 + // The .metadata-v2 file was intentionally modified to contain only + // the 64 bit timestamp, + // the 8 bit persisted flag, + // the 32 bit reserved data 1, + // the 32 bit reserved data 2, + // the 32 bit suffix length, + // the suffix, + // the 32 bit group length, + // the group, + // the 32 bit origin length and + // the origin + // for this origin directory to test restoring. + { + attrs: { userContextId: 1 }, + url: "http://localhost:98", + dbName: "dbT", + dbOptions: { version: 1, storage: "default" }, + }, + ]; + + function openDatabase(params) { + let request; + if ("url" in params) { + let uri = Services.io.newURI(params.url); + let principal = Services.scriptSecurityManager.createContentPrincipal( + uri, + params.attrs || {} + ); + request = indexedDB.openForPrincipal( + principal, + params.dbName, + params.dbOptions + ); + } else { + request = indexedDB.open(params.dbName, params.dbOptions); + } + return request; + } + + clearAllDatabases(continueToNextStepSync); + yield undefined; + + installPackagedProfile("metadata2Restore_profile"); + + for (let params of openParams) { + let request = openDatabase(params); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + is(event.type, "success", "Correct event type"); + } + + resetAllDatabases(continueToNextStepSync); + yield undefined; + + for (let params of openParams) { + let request = openDatabase(params); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + is(event.type, "success", "Correct event type"); + } + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_metadataRestore.js b/dom/indexedDB/test/unit/test_metadataRestore.js new file mode 100644 index 0000000000..001d4da65b --- /dev/null +++ b/dom/indexedDB/test/unit/test_metadataRestore.js @@ -0,0 +1,131 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const openParams = [ + // This one lives in storage/default/http+++localhost+81 + { + url: "http://localhost:81", + dbName: "dbC", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+82 + { + url: "http://localhost:82", + dbName: "dbD", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+83 + { + url: "http://localhost:83", + dbName: "dbE", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+84 + { + url: "http://localhost:84", + dbName: "dbF", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+85 + { + url: "http://localhost:85", + dbName: "dbG", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+86 + { + url: "http://localhost:86", + dbName: "dbH", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+87 + { + url: "http://localhost:87", + dbName: "dbI", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+88 + { + url: "http://localhost:88", + dbName: "dbJ", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+89 + { + url: "http://localhost:89", + dbName: "dbK", + dbOptions: { version: 1, storage: "default" }, + }, + + // This one lives in storage/default/http+++localhost+90 + { + url: "http://localhost:90", + dbName: "dbL", + dbOptions: { version: 1, storage: "default" }, + }, + ]; + + function openDatabase(params) { + let request; + if ("url" in params) { + let uri = Services.io.newURI(params.url); + let principal = Services.scriptSecurityManager.createContentPrincipal( + uri, + {} + ); + request = indexedDB.openForPrincipal( + principal, + params.dbName, + params.dbOptions + ); + } else { + request = indexedDB.open(params.dbName, params.dbOptions); + } + return request; + } + + clearAllDatabases(continueToNextStepSync); + yield undefined; + + installPackagedProfile("metadataRestore_profile"); + + for (let params of openParams) { + let request = openDatabase(params); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + is(event.type, "success", "Correct event type"); + } + + resetAllDatabases(continueToNextStepSync); + yield undefined; + + for (let params of openParams) { + let request = openDatabase(params); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + is(event.type, "success", "Correct event type"); + } + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_multientry.js b/dom/indexedDB/test/unit/test_multientry.js new file mode 100644 index 0000000000..7641da7712 --- /dev/null +++ b/dom/indexedDB/test/unit/test_multientry.js @@ -0,0 +1,271 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + // Test object stores + + let name = this.window ? window.location.pathname : "Splendid Test"; + let openRequest = indexedDB.open(name, 1); + openRequest.onerror = errorHandler; + openRequest.onupgradeneeded = grabEventAndContinueHandler; + openRequest.onsuccess = unexpectedSuccessHandler; + let event = yield undefined; + let db = event.target.result; + db.onerror = errorHandler; + let tests = [ + { add: { x: 1, id: 1 }, indexes: [{ v: 1, k: 1 }] }, + { + add: { x: [2, 3], id: 2 }, + indexes: [ + { v: 1, k: 1 }, + { v: 2, k: 2 }, + { v: 3, k: 2 }, + ], + }, + { + put: { x: [2, 4], id: 1 }, + indexes: [ + { v: 2, k: 1 }, + { v: 2, k: 2 }, + { v: 3, k: 2 }, + { v: 4, k: 1 }, + ], + }, + { + add: { x: [5, 6, 5, -2, 3], id: 3 }, + indexes: [ + { v: -2, k: 3 }, + { v: 2, k: 1 }, + { v: 2, k: 2 }, + { v: 3, k: 2 }, + { v: 3, k: 3 }, + { v: 4, k: 1 }, + { v: 5, k: 3 }, + { v: 6, k: 3 }, + ], + }, + { delete: IDBKeyRange.bound(1, 3), indexes: [] }, + { + put: { x: ["food", {}, false, undefined, /x/, [73, false]], id: 2 }, + indexes: [{ v: "food", k: 2 }], + }, + { + add: { x: [{}, /x/, -12, "food", null, [false], undefined], id: 3 }, + indexes: [ + { v: -12, k: 3 }, + { v: "food", k: 2 }, + { v: "food", k: 3 }, + ], + }, + { + put: { x: [], id: 2 }, + indexes: [ + { v: -12, k: 3 }, + { v: "food", k: 3 }, + ], + }, + { put: { x: { y: 3 }, id: 3 }, indexes: [] }, + { add: { x: false, id: 7 }, indexes: [] }, + { delete: IDBKeyRange.lowerBound(0), indexes: [] }, + ]; + + let store = db.createObjectStore("mystore", { keyPath: "id" }); + let index = store.createIndex("myindex", "x", { multiEntry: true }); + is(index.multiEntry, true, "index created with multiEntry"); + + let i; + for (i = 0; i < tests.length; ++i) { + let test = tests[i]; + let testName = " for " + JSON.stringify(test); + let req; + if (test.add) { + req = store.add(test.add); + } else if (test.put) { + req = store.put(test.put); + } else if (test.delete) { + req = store.delete(test.delete); + } else { + ok(false, "borked test"); + } + req.onsuccess = grabEventAndContinueHandler; + yield undefined; + + req = index.openKeyCursor(); + req.onsuccess = grabEventAndContinueHandler; + for (let j = 0; j < test.indexes.length; ++j) { + yield undefined; + is( + req.result.key, + test.indexes[j].v, + "found expected index key at index " + j + testName + ); + is( + req.result.primaryKey, + test.indexes[j].k, + "found expected index primary key at index " + j + testName + ); + req.result.continue(); + } + yield undefined; + ok(req.result == null, "exhausted indexes"); + + let tempIndex = store.createIndex("temp index", "x", { multiEntry: true }); + req = tempIndex.openKeyCursor(); + req.onsuccess = grabEventAndContinueHandler; + for (let j = 0; j < test.indexes.length; ++j) { + yield undefined; + is( + req.result.key, + test.indexes[j].v, + "found expected temp index key at index " + j + testName + ); + is( + req.result.primaryKey, + test.indexes[j].k, + "found expected temp index primary key at index " + j + testName + ); + req.result.continue(); + } + yield undefined; + ok(req.result == null, "exhausted temp index"); + store.deleteIndex("temp index"); + } + + // Unique indexes + tests = [ + { add: { x: 1, id: 1 }, indexes: [{ v: 1, k: 1 }] }, + { + add: { x: [2, 3], id: 2 }, + indexes: [ + { v: 1, k: 1 }, + { v: 2, k: 2 }, + { v: 3, k: 2 }, + ], + }, + { put: { x: [2, 4], id: 3 }, fail: true }, + { + put: { x: [1, 4], id: 1 }, + indexes: [ + { v: 1, k: 1 }, + { v: 2, k: 2 }, + { v: 3, k: 2 }, + { v: 4, k: 1 }, + ], + }, + { + add: { x: [5, 0, 5, 5, 5], id: 3 }, + indexes: [ + { v: 0, k: 3 }, + { v: 1, k: 1 }, + { v: 2, k: 2 }, + { v: 3, k: 2 }, + { v: 4, k: 1 }, + { v: 5, k: 3 }, + ], + }, + { + delete: IDBKeyRange.bound(1, 2), + indexes: [ + { v: 0, k: 3 }, + { v: 5, k: 3 }, + ], + }, + { add: { x: [0, 6], id: 8 }, fail: true }, + { add: { x: 5, id: 8 }, fail: true }, + { put: { x: 0, id: 8 }, fail: true }, + ]; + + store.deleteIndex("myindex"); + index = store.createIndex("myindex", "x", { multiEntry: true, unique: true }); + is(index.multiEntry, true, "index created with multiEntry"); + + let indexes; + for (i = 0; i < tests.length; ++i) { + let test = tests[i]; + let testName = " for " + JSON.stringify(test); + let req; + if (test.add) { + req = store.add(test.add); + } else if (test.put) { + req = store.put(test.put); + } else if (test.delete) { + req = store.delete(test.delete); + } else { + ok(false, "borked test"); + } + + if (!test.fail) { + req.onsuccess = grabEventAndContinueHandler; + yield undefined; + indexes = test.indexes; + } else { + req.onsuccess = unexpectedSuccessHandler; + req.onerror = grabEventAndContinueHandler; + ok(true, "waiting for error"); + let e = yield undefined; + ok(true, "got error: " + e.type); + e.preventDefault(); + e.stopPropagation(); + } + + req = index.openKeyCursor(); + req.onsuccess = grabEventAndContinueHandler; + for (let j = 0; j < indexes.length; ++j) { + yield undefined; + is( + req.result.key, + indexes[j].v, + "found expected index key at index " + j + testName + ); + is( + req.result.primaryKey, + indexes[j].k, + "found expected index primary key at index " + j + testName + ); + req.result.continue(); + } + yield undefined; + ok(req.result == null, "exhausted indexes"); + + let tempIndex = store.createIndex("temp index", "x", { + multiEntry: true, + unique: true, + }); + req = tempIndex.openKeyCursor(); + req.onsuccess = grabEventAndContinueHandler; + for (let j = 0; j < indexes.length; ++j) { + yield undefined; + is( + req.result.key, + indexes[j].v, + "found expected temp index key at index " + j + testName + ); + is( + req.result.primaryKey, + indexes[j].k, + "found expected temp index primary key at index " + j + testName + ); + req.result.continue(); + } + yield undefined; + ok(req.result == null, "exhausted temp index"); + store.deleteIndex("temp index"); + } + + openRequest.onsuccess = grabEventAndContinueHandler; + yield undefined; + + let trans = db.transaction(["mystore"], "readwrite"); + store = trans.objectStore("mystore"); + index = store.index("myindex"); + is(index.multiEntry, true, "index still is multiEntry"); + trans.oncomplete = grabEventAndContinueHandler; + yield undefined; + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_mutableFileUpgrade.js b/dom/indexedDB/test/unit/test_mutableFileUpgrade.js new file mode 100644 index 0000000000..1875b29924 --- /dev/null +++ b/dom/indexedDB/test/unit/test_mutableFileUpgrade.js @@ -0,0 +1,128 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const dbNames = ["No files", "Blobs and mutable files"]; + const version = 1; + const objectStoreName = "test"; + + clearAllDatabases(continueToNextStepSync); + yield undefined; + + installPackagedProfile("mutableFileUpgrade_profile"); + + let request = indexedDB.open(dbNames[0], version); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + is(event.type, "success", "Correct event type"); + + let db = event.target.result; + db.onerror = errorHandler; + + request = db + .transaction([objectStoreName]) + .objectStore(objectStoreName) + .get(1); + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, "text", "Correct result"); + + request = indexedDB.open(dbNames[1], version); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.type, "success", "Correct event type"); + + db = event.target.result; + db.onerror = errorHandler; + + request = db + .transaction([objectStoreName]) + .objectStore(objectStoreName) + .get(1); + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, "text", "Correct result"); + + request = db + .transaction([objectStoreName]) + .objectStore(objectStoreName) + .get(2); + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + verifyBlob(event.target.result, getBlob("blob0")); + yield undefined; + + request = db + .transaction([objectStoreName]) + .objectStore(objectStoreName) + .get(3); + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + let result = event.target.result; + + verifyBlob(result[0], getBlob("blob1")); + yield undefined; + + verifyBlob(result[1], getBlob("blob2")); + yield undefined; + + request = db + .transaction([objectStoreName]) + .objectStore(objectStoreName) + .get(4); + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + try { + event.target.result; + ok(false, "IDBMutableFile must not be read"); + } catch (err) { + is(err.name, "InvalidStateError", "Wrong error type"); + } + + request = db + .transaction([objectStoreName]) + .objectStore(objectStoreName) + .get(5); + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + try { + event.target.result; + ok(false, "IDBMutableFile must not be read"); + } catch (err) { + is(err.name, "InvalidStateError", "Wrong error type"); + } + + request = db + .transaction([objectStoreName]) + .objectStore(objectStoreName) + .get(6); + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + try { + event.target.result; + ok(false, "IDBMutableFile must not be read"); + } catch (err) { + is(err.name, "InvalidStateError", "Wrong error type"); + } + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_names_sorted.js b/dom/indexedDB/test/unit/test_names_sorted.js new file mode 100644 index 0000000000..d89fcd7f3a --- /dev/null +++ b/dom/indexedDB/test/unit/test_names_sorted.js @@ -0,0 +1,128 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const objectStoreInfo = [ + { name: "foo", options: { keyPath: "id" }, location: 1 }, + { name: "bar", options: { keyPath: "id" }, location: 0 }, + ]; + const indexInfo = [ + { name: "foo", keyPath: "value", location: 1 }, + { name: "bar", keyPath: "value", location: 0 }, + ]; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + let event = yield undefined; + let db = event.target.result; + + for (let i = 0; i < objectStoreInfo.length; i++) { + let info = objectStoreInfo[i]; + let objectStore = info.hasOwnProperty("options") + ? db.createObjectStore(info.name, info.options) + : db.createObjectStore(info.name); + + // Test index creation, and that it ends up in indexNames. + for (let j = 0; j < indexInfo.length; j++) { + let info = indexInfo[j]; + info.hasOwnProperty("options") + ? objectStore.createIndex(info.name, info.keyPath, info.options) + : objectStore.createIndex(info.name, info.keyPath); + } + } + + request.onsuccess = grabEventAndContinueHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + + event = yield undefined; + + let objectStoreNames = []; + for (let i = 0; i < objectStoreInfo.length; i++) { + let info = objectStoreInfo[i]; + objectStoreNames.push(info.name); + + is( + db.objectStoreNames[info.location], + info.name, + "Got objectStore name in the right location" + ); + + let trans = db.transaction(info.name); + let objectStore = trans.objectStore(info.name); + for (let j = 0; j < indexInfo.length; j++) { + let info = indexInfo[j]; + is( + objectStore.indexNames[info.location], + info.name, + "Got index name in the right location" + ); + } + } + + let trans = db.transaction(objectStoreNames); + for (let i = 0; i < objectStoreInfo.length; i++) { + let info = objectStoreInfo[i]; + + is( + trans.objectStoreNames[info.location], + info.name, + "Got objectStore name in the right location" + ); + } + + db.close(); + + request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + event = yield undefined; + + db = event.target.result; + + objectStoreNames = []; + for (let i = 0; i < objectStoreInfo.length; i++) { + let info = objectStoreInfo[i]; + objectStoreNames.push(info.name); + + is( + db.objectStoreNames[info.location], + info.name, + "Got objectStore name in the right location" + ); + + let trans = db.transaction(info.name); + let objectStore = trans.objectStore(info.name); + for (let j = 0; j < indexInfo.length; j++) { + let info = indexInfo[j]; + is( + objectStore.indexNames[info.location], + info.name, + "Got index name in the right location" + ); + } + } + + trans = db.transaction(objectStoreNames); + for (let i = 0; i < objectStoreInfo.length; i++) { + let info = objectStoreInfo[i]; + + is( + trans.objectStoreNames[info.location], + info.name, + "Got objectStore name in the right location" + ); + } + + db.close(); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_objectCursors.js b/dom/indexedDB/test/unit/test_objectCursors.js new file mode 100644 index 0000000000..10d8c83c6e --- /dev/null +++ b/dom/indexedDB/test/unit/test_objectCursors.js @@ -0,0 +1,87 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + const objectStores = [ + { name: "a", autoIncrement: false }, + { name: "b", autoIncrement: true }, + ]; + + const indexes = [ + { name: "a", options: {} }, + { name: "b", options: { unique: true } }, + ]; + + var j = 0; + for (let i in objectStores) { + let request = indexedDB.open(name, ++j); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + db.onversionchange = function (event) { + event.target.close(); + }; + + let objectStore = db.createObjectStore(objectStores[i].name, { + keyPath: "id", + autoIncrement: objectStores[i].autoIncrement, + }); + + for (let j in indexes) { + objectStore.createIndex(indexes[j].name, "name", indexes[j].options); + } + + let data = { name: "Ben" }; + if (!objectStores[i].autoIncrement) { + data.id = 1; + } + + request = objectStore.add(data); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + ok(event.target.result == 1 || event.target.result == 2, "Good id"); + } + + executeSoon(function () { + testGenerator.next(); + }); + yield undefined; + + let request = indexedDB.open(name, j); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + + for (let i in objectStores) { + for (let j in indexes) { + let objectStore = db + .transaction(objectStores[i].name) + .objectStore(objectStores[i].name); + let index = objectStore.index(indexes[j].name); + + request = index.openCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(event.target.result.value.name, "Ben", "Good object"); + executeSoon(function () { + testGenerator.next(); + }); + }; + yield undefined; + } + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_objectStore_getAllKeys.js b/dom/indexedDB/test/unit/test_objectStore_getAllKeys.js new file mode 100644 index 0000000000..15d69e7b93 --- /dev/null +++ b/dom/indexedDB/test/unit/test_objectStore_getAllKeys.js @@ -0,0 +1,123 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const dbName = this.window + ? window.location.pathname + : "test_objectStore_getAllKeys"; + const dbVersion = 1; + const objectStoreName = "foo"; + const keyCount = 200; + + let request = indexedDB.open(dbName, dbVersion); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + + let event = yield undefined; + + info("Creating database"); + + let db = event.target.result; + let objectStore = db.createObjectStore(objectStoreName); + for (let i = 0; i < keyCount; i++) { + objectStore.add(true, i); + } + + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + db = event.target.result; + objectStore = db.transaction(objectStoreName).objectStore(objectStoreName); + + info("Getting all keys"); + objectStore.getAllKeys().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + ok(Array.isArray(event.target.result), "Got an array result"); + is(event.target.result.length, keyCount, "Got correct array length"); + + let match = true; + for (let i = 0; i < keyCount; i++) { + if (event.target.result[i] != i) { + match = false; + break; + } + } + ok(match, "Got correct keys"); + + info("Getting all keys with key range"); + let keyRange = IDBKeyRange.bound(10, 20, false, true); + objectStore.getAllKeys(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + ok(Array.isArray(event.target.result), "Got an array result"); + is(event.target.result.length, 10, "Got correct array length"); + + match = true; + for (let i = 10; i < 20; i++) { + if (event.target.result[i - 10] != i) { + match = false; + break; + } + } + ok(match, "Got correct keys"); + + info("Getting all keys with unmatched key range"); + keyRange = IDBKeyRange.bound(10000, 200000); + objectStore.getAllKeys(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + ok(Array.isArray(event.target.result), "Got an array result"); + is(event.target.result.length, 0, "Got correct array length"); + + info("Getting all keys with limit"); + objectStore.getAllKeys(null, 5).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + ok(Array.isArray(event.target.result), "Got an array result"); + is(event.target.result.length, 5, "Got correct array length"); + + match = true; + for (let i = 0; i < 5; i++) { + if (event.target.result[i] != i) { + match = false; + break; + } + } + ok(match, "Got correct keys"); + + info("Getting all keys with key range and limit"); + keyRange = IDBKeyRange.bound(10, 20, false, true); + objectStore.getAllKeys(keyRange, 5).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + ok(Array.isArray(event.target.result), "Got an array result"); + is(event.target.result.length, 5, "Got correct array length"); + + match = true; + for (let i = 10; i < 15; i++) { + if (event.target.result[i - 10] != i) { + match = false; + break; + } + } + ok(match, "Got correct keys"); + + info("Getting all keys with unmatched key range and limit"); + keyRange = IDBKeyRange.bound(10000, 200000); + objectStore.getAllKeys(keyRange, 5).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + ok(Array.isArray(event.target.result), "Got an array result"); + is(event.target.result.length, 0, "Got correct array length"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_objectStore_inline_autoincrement_key_added_on_put.js b/dom/indexedDB/test/unit/test_objectStore_inline_autoincrement_key_added_on_put.js new file mode 100644 index 0000000000..8446fcd5d0 --- /dev/null +++ b/dom/indexedDB/test/unit/test_objectStore_inline_autoincrement_key_added_on_put.js @@ -0,0 +1,57 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + var request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + var event = yield undefined; + + var db = event.target.result; + + var test = { + name: "inline key; key generator", + autoIncrement: true, + storedObject: { name: "Lincoln" }, + keyName: "id", + }; + + let objectStore = db.createObjectStore(test.name, { + keyPath: test.keyName, + autoIncrement: test.autoIncrement, + }); + + request = objectStore.add(test.storedObject); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + let id = event.target.result; + request = objectStore.get(id); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + // Sanity check! + is( + event.target.result.name, + test.storedObject.name, + "The correct object was stored." + ); + + // Ensure that the id was also stored on the object. + is(event.target.result.id, id, "The object had the id stored on it."); + + // Wait for success + yield undefined; + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_objectStore_openKeyCursor.js b/dom/indexedDB/test/unit/test_objectStore_openKeyCursor.js new file mode 100644 index 0000000000..3794bb7cca --- /dev/null +++ b/dom/indexedDB/test/unit/test_objectStore_openKeyCursor.js @@ -0,0 +1,401 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const dbName = this.window + ? window.location.pathname + : "test_objectStore_openKeyCursor"; + const dbVersion = 1; + const objectStoreName = "foo"; + const keyCount = 100; + + let request = indexedDB.open(dbName, dbVersion); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + + let event = yield undefined; + + info("Creating database"); + + let db = event.target.result; + let objectStore = db.createObjectStore(objectStoreName); + for (let i = 0; i < keyCount; i++) { + objectStore.add(true, i); + } + + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + db = event.target.result; + objectStore = db + .transaction(objectStoreName, "readwrite") + .objectStore(objectStoreName); + + info("Getting all keys"); + objectStore.getAllKeys().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + const allKeys = event.target.result; + + ok(Array.isArray(allKeys), "Got an array result"); + is(allKeys.length, keyCount, "Got correct array length"); + + info("Opening normal key cursor"); + + let seenKeys = []; + objectStore.openKeyCursor().onsuccess = event => { + let cursor = event.target.result; + if (!cursor) { + continueToNextStepSync(); + return; + } + + is(cursor.source, objectStore, "Correct source"); + is(cursor.direction, "next", "Correct direction"); + + let exception = null; + try { + cursor.update(10); + } catch (e) { + exception = e; + } + ok(!!exception, "update() throws for key cursor"); + + exception = null; + try { + cursor.delete(); + } catch (e) { + exception = e; + } + ok(!!exception, "delete() throws for key cursor"); + + is(cursor.key, cursor.primaryKey, "key and primaryKey match"); + ok(!("value" in cursor), "No 'value' property on key cursor"); + + seenKeys.push(cursor.key); + cursor.continue(); + }; + yield undefined; + + is(seenKeys.length, allKeys.length, "Saw the right number of keys"); + + let match = true; + for (let i = 0; i < seenKeys.length; i++) { + if (seenKeys[i] !== allKeys[i]) { + match = false; + break; + } + } + ok(match, "All keys matched"); + + info("Opening key cursor with keyRange"); + + let keyRange = IDBKeyRange.bound(10, 20, false, true); + + seenKeys = []; + objectStore.openKeyCursor(keyRange).onsuccess = event => { + let cursor = event.target.result; + if (!cursor) { + continueToNextStepSync(); + return; + } + + is(cursor.source, objectStore, "Correct source"); + is(cursor.direction, "next", "Correct direction"); + + let exception = null; + try { + cursor.update(10); + } catch (e) { + exception = e; + } + ok(!!exception, "update() throws for key cursor"); + + exception = null; + try { + cursor.delete(); + } catch (e) { + exception = e; + } + ok(!!exception, "delete() throws for key cursor"); + + is(cursor.key, cursor.primaryKey, "key and primaryKey match"); + ok(!("value" in cursor), "No 'value' property on key cursor"); + + seenKeys.push(cursor.key); + cursor.continue(); + }; + yield undefined; + + is(seenKeys.length, 10, "Saw the right number of keys"); + + match = true; + for (let i = 0; i < seenKeys.length; i++) { + if (seenKeys[i] !== allKeys[i + 10]) { + match = false; + break; + } + } + ok(match, "All keys matched"); + + info("Opening key cursor with unmatched keyRange"); + + keyRange = IDBKeyRange.bound(10000, 200000); + + seenKeys = []; + objectStore.openKeyCursor(keyRange).onsuccess = event => { + let cursor = event.target.result; + if (!cursor) { + continueToNextStepSync(); + return; + } + + ok(false, "Shouldn't have any keys here"); + cursor.continue(); + }; + yield undefined; + + is(seenKeys.length, 0, "Saw the right number of keys"); + + info("Opening reverse key cursor"); + + seenKeys = []; + objectStore.openKeyCursor(null, "prev").onsuccess = event => { + let cursor = event.target.result; + if (!cursor) { + continueToNextStepSync(); + return; + } + + is(cursor.source, objectStore, "Correct source"); + is(cursor.direction, "prev", "Correct direction"); + + let exception = null; + try { + cursor.update(10); + } catch (e) { + exception = e; + } + ok(!!exception, "update() throws for key cursor"); + + exception = null; + try { + cursor.delete(); + } catch (e) { + exception = e; + } + ok(!!exception, "delete() throws for key cursor"); + + is(cursor.key, cursor.primaryKey, "key and primaryKey match"); + ok(!("value" in cursor), "No 'value' property on key cursor"); + + seenKeys.push(cursor.key); + cursor.continue(); + }; + yield undefined; + + is(seenKeys.length, allKeys.length, "Saw the right number of keys"); + + seenKeys.reverse(); + + match = true; + for (let i = 0; i < seenKeys.length; i++) { + if (seenKeys[i] !== allKeys[i]) { + match = false; + break; + } + } + ok(match, "All keys matched"); + + info("Opening reverse key cursor with key range"); + + keyRange = IDBKeyRange.bound(10, 20, false, true); + + seenKeys = []; + objectStore.openKeyCursor(keyRange, "prev").onsuccess = event => { + let cursor = event.target.result; + if (!cursor) { + continueToNextStepSync(); + return; + } + + is(cursor.source, objectStore, "Correct source"); + is(cursor.direction, "prev", "Correct direction"); + + let exception = null; + try { + cursor.update(10); + } catch (e) { + exception = e; + } + ok(!!exception, "update() throws for key cursor"); + + exception = null; + try { + cursor.delete(); + } catch (e) { + exception = e; + } + ok(!!exception, "delete() throws for key cursor"); + + is(cursor.key, cursor.primaryKey, "key and primaryKey match"); + ok(!("value" in cursor), "No 'value' property on key cursor"); + + seenKeys.push(cursor.key); + cursor.continue(); + }; + yield undefined; + + is(seenKeys.length, 10, "Saw the right number of keys"); + + seenKeys.reverse(); + + match = true; + for (let i = 0; i < 10; i++) { + if (seenKeys[i] !== allKeys[i + 10]) { + match = false; + break; + } + } + ok(match, "All keys matched"); + + info("Opening reverse key cursor with unmatched key range"); + + keyRange = IDBKeyRange.bound(10000, 200000); + + seenKeys = []; + objectStore.openKeyCursor(keyRange, "prev").onsuccess = event => { + let cursor = event.target.result; + if (!cursor) { + continueToNextStepSync(); + return; + } + + ok(false, "Shouldn't have any keys here"); + cursor.continue(); + }; + yield undefined; + + is(seenKeys.length, 0, "Saw the right number of keys"); + + info("Opening key cursor with advance"); + + seenKeys = []; + objectStore.openKeyCursor().onsuccess = event => { + let cursor = event.target.result; + if (!cursor) { + continueToNextStepSync(); + return; + } + + is(cursor.source, objectStore, "Correct source"); + is(cursor.direction, "next", "Correct direction"); + + let exception = null; + try { + cursor.update(10); + } catch (e) { + exception = e; + } + ok(!!exception, "update() throws for key cursor"); + + exception = null; + try { + cursor.delete(); + } catch (e) { + exception = e; + } + ok(!!exception, "delete() throws for key cursor"); + + is(cursor.key, cursor.primaryKey, "key and primaryKey match"); + ok(!("value" in cursor), "No 'value' property on key cursor"); + + seenKeys.push(cursor.key); + if (seenKeys.length == 1) { + cursor.advance(10); + } else { + cursor.continue(); + } + }; + yield undefined; + + is(seenKeys.length, allKeys.length - 9, "Saw the right number of keys"); + + match = true; + for (let i = 0, j = 0; i < seenKeys.length; i++) { + if (seenKeys[i] !== allKeys[i + j]) { + match = false; + break; + } + if (i == 0) { + j = 9; + } + } + ok(match, "All keys matched"); + + info("Opening key cursor with continue-to-key"); + + seenKeys = []; + objectStore.openKeyCursor().onsuccess = event => { + let cursor = event.target.result; + if (!cursor) { + continueToNextStepSync(); + return; + } + + is(cursor.source, objectStore, "Correct source"); + is(cursor.direction, "next", "Correct direction"); + + let exception = null; + try { + cursor.update(10); + } catch (e) { + exception = e; + } + ok(!!exception, "update() throws for key cursor"); + + exception = null; + try { + cursor.delete(); + } catch (e) { + exception = e; + } + ok(!!exception, "delete() throws for key cursor"); + + is(cursor.key, cursor.primaryKey, "key and primaryKey match"); + ok(!("value" in cursor), "No 'value' property on key cursor"); + + seenKeys.push(cursor.key); + + if (seenKeys.length == 1) { + cursor.continue(10); + } else { + cursor.continue(); + } + }; + yield undefined; + + is(seenKeys.length, allKeys.length - 9, "Saw the right number of keys"); + + match = true; + for (let i = 0, j = 0; i < seenKeys.length; i++) { + if (seenKeys[i] !== allKeys[i + j]) { + match = false; + break; + } + if (i == 0) { + j = 9; + } + } + ok(match, "All keys matched"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_objectStore_remove_values.js b/dom/indexedDB/test/unit/test_objectStore_remove_values.js new file mode 100644 index 0000000000..7bf5c21b33 --- /dev/null +++ b/dom/indexedDB/test/unit/test_objectStore_remove_values.js @@ -0,0 +1,98 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + var data = [ + { + name: "inline key; key generator", + autoIncrement: true, + storedObject: { name: "Lincoln" }, + keyName: "id", + keyValue: undefined, + }, + { + name: "inline key; no key generator", + autoIncrement: false, + storedObject: { id: 1, name: "Lincoln" }, + keyName: "id", + keyValue: undefined, + }, + { + name: "out of line key; key generator", + autoIncrement: true, + storedObject: { name: "Lincoln" }, + keyName: undefined, + keyValue: undefined, + }, + { + name: "out of line key; no key generator", + autoIncrement: false, + storedObject: { name: "Lincoln" }, + keyName: null, + keyValue: 1, + }, + ]; + + for (let i = 0; i < data.length; i++) { + let test = data[i]; + + let request = indexedDB.open(name, i + 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + db.onversionchange = function (event) { + event.target.close(); + }; + + let objectStore = db.createObjectStore(test.name, { + keyPath: test.keyName, + autoIncrement: test.autoIncrement, + }); + + request = objectStore.add(test.storedObject, test.keyValue); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + let id = event.target.result; + request = objectStore.get(id); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + // Sanity check! + is( + test.storedObject.name, + event.target.result.name, + "The correct object was stored." + ); + + request = objectStore.delete(id); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + // Make sure it was removed. + request = objectStore.get(id); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + ok(event.target.result === undefined, "Object was deleted"); + + // Wait for success + yield undefined; + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_object_identity.js b/dom/indexedDB/test/unit/test_object_identity.js new file mode 100644 index 0000000000..6b23fa5243 --- /dev/null +++ b/dom/indexedDB/test/unit/test_object_identity.js @@ -0,0 +1,49 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + let request = indexedDB.open( + this.window ? window.location.pathname : "Splendid Test", + 1 + ); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + let transaction = event.target.transaction; + + let objectStore1 = db.createObjectStore("foo"); + let objectStore2 = transaction.objectStore("foo"); + ok(objectStore1 === objectStore2, "Got same objectStores"); + + let index1 = objectStore1.createIndex("bar", "key"); + let index2 = objectStore2.index("bar"); + ok(index1 === index2, "Got same indexes"); + + request.onsuccess = continueToNextStep; + yield undefined; + + transaction = db.transaction(db.objectStoreNames); + + let objectStore3 = transaction.objectStore("foo"); + let objectStore4 = transaction.objectStore("foo"); + ok(objectStore3 === objectStore4, "Got same objectStores"); + + ok(objectStore3 !== objectStore1, "Different objectStores"); + ok(objectStore4 !== objectStore2, "Different objectStores"); + + let index3 = objectStore3.index("bar"); + let index4 = objectStore4.index("bar"); + ok(index3 === index4, "Got same indexes"); + + ok(index3 !== index1, "Different indexes"); + ok(index4 !== index2, "Different indexes"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_obsoleteOriginAttributesUpgrade.js b/dom/indexedDB/test/unit/test_obsoleteOriginAttributesUpgrade.js new file mode 100644 index 0000000000..893dfb08a5 --- /dev/null +++ b/dom/indexedDB/test/unit/test_obsoleteOriginAttributesUpgrade.js @@ -0,0 +1,45 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const url = "moz-extension://8ea6d31b-917c-431f-a204-15b95e904d4f"; + const dbName = "Hello."; + const dbVersion = 1; + + clearAllDatabases(continueToNextStepSync); + yield; + + // The origin directory contained in the package is: + // "moz-extension+++8ea6d31b-917c-431f-a204-15b95e904d4f^addonId=indexedDB-test%40kmaglione.mozilla.com" + installPackagedProfile("obsoleteOriginAttributes_profile"); + + let request = indexedDB.openForPrincipal( + getPrincipal(url), + dbName, + dbVersion + ); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield; + + is(event.type, "success", "Correct event type"); + + resetAllDatabases(continueToNextStepSync); + yield; + + request = indexedDB.openForPrincipal(getPrincipal(url), dbName, dbVersion); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield; + + is(event.type, "success", "Correct event type"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_odd_result_order.js b/dom/indexedDB/test/unit/test_odd_result_order.js new file mode 100644 index 0000000000..e7462a87fd --- /dev/null +++ b/dom/indexedDB/test/unit/test_odd_result_order.js @@ -0,0 +1,78 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const data = { key: 5, index: 10 }; + + let request = indexedDB.open( + this.window ? window.location.pathname : "Splendid Test", + 1 + ); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + + ok(db instanceof IDBDatabase, "Got a real database"); + + db.onerror = errorHandler; + + let objectStore = db.createObjectStore("foo", { + keyPath: "key", + autoIncrement: true, + }); + objectStore.createIndex("foo", "index"); + + event.target.onsuccess = continueToNextStep; + yield undefined; + + objectStore = db.transaction("foo", "readwrite").objectStore("foo"); + request = objectStore.add(data); + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + let key; + executeSoon(function () { + key = request.result; + continueToNextStep(); + }); + yield undefined; + + is(key, data.key, "Got the right key"); + + objectStore = db.transaction("foo").objectStore("foo"); + objectStore.get(data.key).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + let obj; + executeSoon(function () { + obj = event.target.result; + continueToNextStep(); + }); + yield undefined; + + is(obj.key, data.key, "Got the right key"); + is(obj.index, data.index, "Got the right property value"); + + objectStore = db.transaction("foo", "readwrite").objectStore("foo"); + request = objectStore.delete(data.key); + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + key = undefined; + executeSoon(function () { + key = request.result; + continueToNextStep(); + }, 0); + yield undefined; + + ok(key === undefined, "Got the right value"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_oldDirectories.js b/dom/indexedDB/test/unit/test_oldDirectories.js new file mode 100644 index 0000000000..1649bd63a5 --- /dev/null +++ b/dom/indexedDB/test/unit/test_oldDirectories.js @@ -0,0 +1,66 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + // This lives in storage/default/http+++www.mozilla.org + const url = "http://www.mozilla.org"; + const dbName = "dbC"; + const dbVersion = 1; + + function openDatabase() { + let uri = Services.io.newURI(url); + let principal = Services.scriptSecurityManager.createContentPrincipal( + uri, + {} + ); + let request = indexedDB.openForPrincipal(principal, dbName, dbVersion); + return request; + } + + clearAllDatabases(continueToNextStepSync); + yield undefined; + + installPackagedProfile("oldDirectories_profile"); + + let request = openDatabase(); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + is(event.type, "success", "Correct event type"); + + resetAllDatabases(continueToNextStepSync); + yield undefined; + + request = openDatabase(); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.type, "success", "Correct event type"); + + let profileDir = Services.dirsvc.get("ProfD", Ci.nsIFile); + + let dir = profileDir.clone(); + dir.append("indexedDB"); + + let exists = dir.exists(); + ok(!exists, "indexedDB doesn't exist"); + + dir = profileDir.clone(); + dir.append("storage"); + dir.append("persistent"); + + exists = dir.exists(); + ok(!exists, "storage/persistent doesn't exist"); + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_open_empty_db.js b/dom/indexedDB/test/unit/test_open_empty_db.js new file mode 100644 index 0000000000..e7bc09a991 --- /dev/null +++ b/dom/indexedDB/test/unit/test_open_empty_db.js @@ -0,0 +1,46 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const names = [ + // "", + null, + undefined, + this.window ? window.location.pathname : "Splendid Test", + ]; + + const version = 1; + + for (let name of names) { + let request = indexedDB.open(name, version); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + if (name === null) { + name = "null"; + } else if (name === undefined) { + name = "undefined"; + } + + let db = event.target.result; + is(db.name, name, "Bad name"); + is(db.version, version, "Bad version"); + is(db.objectStoreNames.length, 0, "Bad objectStores list"); + + is(db.name, request.result.name, "Bad name"); + is(db.version, request.result.version, "Bad version"); + is( + db.objectStoreNames.length, + request.result.objectStoreNames.length, + "Bad objectStores list" + ); + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_open_for_principal.js b/dom/indexedDB/test/unit/test_open_for_principal.js new file mode 100644 index 0000000000..657045364e --- /dev/null +++ b/dom/indexedDB/test/unit/test_open_for_principal.js @@ -0,0 +1,89 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + const objectStoreName = "Foo"; + + const data = { key: 1, value: "bar" }; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + is(event.type, "upgradeneeded", "Got correct event type"); + + let db = event.target.result; + db.onerror = errorHandler; + + let objectStore = db.createObjectStore(objectStoreName, {}); + + event = yield undefined; + + is(event.type, "success", "Got correct event type"); + + objectStore = db + .transaction([objectStoreName], "readwrite") + .objectStore(objectStoreName); + + request = objectStore.get(data.key); + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, null, "Got no data"); + + request = objectStore.add(data.value, data.key); + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, data.key, "Got correct key"); + + let uri = Services.io.newURI("http://appdata.example.com"); + let principal = Services.scriptSecurityManager.createContentPrincipal( + uri, + {} + ); + + request = indexedDB.openForPrincipal(principal, name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.type, "upgradeneeded", "Got correct event type"); + + db = event.target.result; + db.onerror = errorHandler; + + objectStore = db.createObjectStore(objectStoreName, {}); + + event = yield undefined; + + is(event.type, "success", "Got correct event type"); + + objectStore = db.transaction([objectStoreName]).objectStore(objectStoreName); + + request = objectStore.get(data.key); + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, null, "Got no data"); + + db.close(); + + request = indexedDB.deleteForPrincipal(principal, name); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_open_objectStore.js b/dom/indexedDB/test/unit/test_open_objectStore.js new file mode 100644 index 0000000000..1908edc469 --- /dev/null +++ b/dom/indexedDB/test/unit/test_open_objectStore.js @@ -0,0 +1,36 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const objectStoreName = "Objects"; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + is(db.objectStoreNames.length, 0, "Bad objectStores list"); + + let objectStore = db.createObjectStore(objectStoreName, { keyPath: "foo" }); + + is(db.objectStoreNames.length, 1, "Bad objectStores list"); + is(db.objectStoreNames.item(0), objectStoreName, "Bad name"); + + yield undefined; + + objectStore = db.transaction(objectStoreName).objectStore(objectStoreName); + + is(objectStore.name, objectStoreName, "Bad name"); + is(objectStore.keyPath, "foo", "Bad keyPath"); + is(objectStore.indexNames.length, 0, "Bad indexNames"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_optionalArguments.js b/dom/indexedDB/test/unit/test_optionalArguments.js new file mode 100644 index 0000000000..1f15335b18 --- /dev/null +++ b/dom/indexedDB/test/unit/test_optionalArguments.js @@ -0,0 +1,1796 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +var testGenerator = testSteps(); + +function* testSteps() { + const osName = "people"; + const indexName = "weight"; + + const data = [ + { ssn: "237-23-7732", name: "Bob", height: 60, weight: 120 }, + { ssn: "237-23-7733", name: "Ann", height: 52, weight: 110 }, + { ssn: "237-23-7734", name: "Ron", height: 73, weight: 180 }, + { ssn: "237-23-7735", name: "Sue", height: 58, weight: 130 }, + { ssn: "237-23-7736", name: "Joe", height: 65, weight: 150 }, + { ssn: "237-23-7737", name: "Pat", height: 65 }, + { ssn: "237-23-7738", name: "Mel", height: 66, weight: {} }, + { ssn: "237-23-7739", name: "Tom", height: 62, weight: 130 }, + ]; + + const weightSort = [1, 0, 3, 7, 4, 2]; + + let request = indexedDB.open( + this.window ? window.location.pathname : "Splendid Test", + 1 + ); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + is(event.type, "upgradeneeded", "Got upgradeneeded event"); + + let db = event.target.result; + db.onerror = errorHandler; + + let objectStore = db.createObjectStore(osName, { keyPath: "ssn" }); + objectStore.createIndex(indexName, "weight", { unique: false }); + + for (let i of data) { + objectStore.add(i); + } + + event = yield undefined; + + is(event.type, "success", "Got success event"); + + try { + IDBKeyRange.bound(1, -1); + ok(false, "Bound keyRange with backwards args should throw!"); + } catch (e) { + is(e.name, "DataError", "Threw correct exception"); + is(e.code, 0, "Threw with correct code"); + } + + try { + IDBKeyRange.bound(1, 1); + ok(true, "Bound keyRange with same arg should be ok"); + } catch (e) { + ok(false, "Bound keyRange with same arg should have been ok"); + } + + try { + IDBKeyRange.bound(1, 1, true); + ok(false, "Bound keyRange with same arg and open should throw!"); + } catch (e) { + is(e.name, "DataError", "Threw correct exception"); + is(e.code, 0, "Threw with correct code"); + } + + try { + IDBKeyRange.bound(1, 1, true, true); + ok(false, "Bound keyRange with same arg and open should throw!"); + } catch (e) { + is(e.name, "DataError", "Threw correct exception"); + is(e.code, 0, "Threw with correct code"); + } + + objectStore = db.transaction(osName).objectStore(osName); + + try { + objectStore.get(); + ok(false, "Get with unspecified arg should have thrown"); + } catch (e) { + ok(true, "Get with unspecified arg should have thrown"); + } + + try { + objectStore.get(undefined); + ok(false, "Get with undefined should have thrown"); + } catch (e) { + ok(true, "Get with undefined arg should have thrown"); + } + + try { + objectStore.get(null); + ok(false, "Get with null should have thrown"); + } catch (e) { + is(e instanceof DOMException, true, "Got right kind of exception"); + is(e.name, "DataError", "Correct error."); + is(e.code, 0, "Correct code."); + } + + objectStore.get(data[2].ssn).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result.name, data[2].name, "Correct data"); + + let keyRange = IDBKeyRange.only(data[2].ssn); + + objectStore.get(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result.name, data[2].name, "Correct data"); + + keyRange = IDBKeyRange.lowerBound(data[2].ssn); + + objectStore.get(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result.name, data[2].name, "Correct data"); + + keyRange = IDBKeyRange.lowerBound(data[2].ssn, true); + + objectStore.get(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result.name, data[3].name, "Correct data"); + + keyRange = IDBKeyRange.upperBound(data[2].ssn); + + objectStore.get(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result.name, data[0].name, "Correct data"); + + keyRange = IDBKeyRange.bound(data[2].ssn, data[4].ssn); + + objectStore.get(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result.name, data[2].name, "Correct data"); + + keyRange = IDBKeyRange.bound(data[2].ssn, data[4].ssn, true); + + objectStore.get(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result.name, data[3].name, "Correct data"); + + objectStore = db.transaction(osName, "readwrite").objectStore(osName); + + try { + objectStore.delete(); + ok(false, "Delete with unspecified arg should have thrown"); + } catch (e) { + ok(true, "Delete with unspecified arg should have thrown"); + } + + try { + objectStore.delete(undefined); + ok(false, "Delete with undefined should have thrown"); + } catch (e) { + ok(true, "Delete with undefined arg should have thrown"); + } + + try { + objectStore.delete(null); + ok(false, "Delete with null should have thrown"); + } catch (e) { + is(e instanceof DOMException, true, "Got right kind of exception"); + is(e.name, "DataError", "Correct error."); + is(e.code, 0, "Correct code."); + } + + objectStore.count().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, data.length, "Correct count"); + + objectStore.delete(data[2].ssn).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + ok(event.target.result === undefined, "Correct result"); + + objectStore.count().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, data.length - 1, "Correct count"); + + keyRange = IDBKeyRange.bound(data[3].ssn, data[5].ssn); + + objectStore.delete(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + ok(event.target.result === undefined, "Correct result"); + + objectStore.count().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, data.length - 4, "Correct count"); + + keyRange = IDBKeyRange.lowerBound(10); + + objectStore.delete(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + ok(event.target.result === undefined, "Correct result"); + + objectStore.count().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, 0, "Correct count"); + + event.target.transaction.oncomplete = grabEventAndContinueHandler; + + for (let i of data) { + objectStore.add(i); + } + + yield undefined; + + objectStore = db.transaction(osName).objectStore(osName); + + objectStore.count().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, data.length, "Correct count"); + + let count = 0; + + objectStore.openCursor().onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, data.length, "Correct count for no arg to openCursor"); + + count = 0; + + objectStore.openCursor(null).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, data.length, "Correct count for null arg to openCursor"); + + count = 0; + + objectStore.openCursor(undefined).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, data.length, "Correct count for undefined arg to openCursor"); + + count = 0; + + objectStore.openCursor(data[2].ssn).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 1, "Correct count for single key arg to openCursor"); + + count = 0; + + objectStore.openCursor("foo").onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 0, "Correct count for non-existent single key arg to openCursor"); + + count = 0; + keyRange = IDBKeyRange.only(data[2].ssn); + + objectStore.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 1, "Correct count for only keyRange arg to openCursor"); + + count = 0; + keyRange = IDBKeyRange.lowerBound(data[2].ssn); + + objectStore.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, data.length - 2, "Correct count for lowerBound arg to openCursor"); + + count = 0; + keyRange = IDBKeyRange.lowerBound(data[2].ssn, true); + + objectStore.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, data.length - 3, "Correct count for lowerBound arg to openCursor"); + + count = 0; + keyRange = IDBKeyRange.lowerBound("foo"); + + objectStore.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 0, "Correct count for non-existent lowerBound arg to openCursor"); + + count = 0; + keyRange = IDBKeyRange.bound(data[2].ssn, data[3].ssn); + + objectStore.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 2, "Correct count for bound arg to openCursor"); + + count = 0; + keyRange = IDBKeyRange.bound(data[2].ssn, data[3].ssn, true); + + objectStore.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 1, "Correct count for bound arg to openCursor"); + + count = 0; + keyRange = IDBKeyRange.bound(data[2].ssn, data[3].ssn, true, true); + + objectStore.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 0, "Correct count for bound arg to openCursor"); + + let index = objectStore.index(indexName); + + count = 0; + + index.openKeyCursor().onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length, + "Correct count for unspecified arg to index.openKeyCursor" + ); + + count = 0; + + index.openKeyCursor(null).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length, + "Correct count for null arg to index.openKeyCursor" + ); + + count = 0; + + index.openKeyCursor(undefined).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length, + "Correct count for undefined arg to index.openKeyCursor" + ); + + count = 0; + + index.openKeyCursor(data[0].weight).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 1, "Correct count for single key arg to index.openKeyCursor"); + + count = 0; + + index.openKeyCursor("foo").onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 0, "Correct count for non-existent key arg to index.openKeyCursor"); + + count = 0; + keyRange = IDBKeyRange.only("foo"); + + index.openKeyCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + 0, + "Correct count for non-existent keyRange arg to index.openKeyCursor" + ); + + count = 0; + keyRange = IDBKeyRange.only(data[0].weight); + + index.openKeyCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 1, "Correct count for only keyRange arg to index.openKeyCursor"); + + count = 0; + keyRange = IDBKeyRange.lowerBound(data[weightSort[0]].weight); + + index.openKeyCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length, + "Correct count for lowerBound keyRange arg to index.openKeyCursor" + ); + + count = 0; + keyRange = IDBKeyRange.lowerBound(data[weightSort[0]].weight, true); + + index.openKeyCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length - 1, + "Correct count for lowerBound keyRange arg to index.openKeyCursor" + ); + + count = 0; + keyRange = IDBKeyRange.lowerBound("foo"); + + index.openKeyCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + 0, + "Correct count for lowerBound keyRange arg to index.openKeyCursor" + ); + + count = 0; + keyRange = IDBKeyRange.upperBound(data[weightSort[0]].weight); + + index.openKeyCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + 1, + "Correct count for upperBound keyRange arg to index.openKeyCursor" + ); + + count = 0; + keyRange = IDBKeyRange.upperBound(data[weightSort[0]].weight, true); + + index.openKeyCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + 0, + "Correct count for upperBound keyRange arg to index.openKeyCursor" + ); + + count = 0; + keyRange = IDBKeyRange.upperBound( + data[weightSort[weightSort.length - 1]].weight + ); + + index.openKeyCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length, + "Correct count for upperBound keyRange arg to index.openKeyCursor" + ); + + count = 0; + keyRange = IDBKeyRange.upperBound( + data[weightSort[weightSort.length - 1]].weight, + true + ); + + index.openKeyCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length - 1, + "Correct count for upperBound keyRange arg to index.openKeyCursor" + ); + + count = 0; + keyRange = IDBKeyRange.upperBound("foo"); + + index.openKeyCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length, + "Correct count for upperBound keyRange arg to index.openKeyCursor" + ); + + count = 0; + keyRange = IDBKeyRange.upperBound(0); + + index.openKeyCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + 0, + "Correct count for upperBound keyRange arg to index.openKeyCursor" + ); + + count = 0; + keyRange = IDBKeyRange.bound( + data[weightSort[0]].weight, + data[weightSort[weightSort.length - 1]].weight + ); + + index.openKeyCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length, + "Correct count for bound keyRange arg to index.openKeyCursor" + ); + + count = 0; + keyRange = IDBKeyRange.bound( + data[weightSort[0]].weight, + data[weightSort[weightSort.length - 1]].weight, + true + ); + + index.openKeyCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length - 1, + "Correct count for bound keyRange arg to index.openKeyCursor" + ); + + count = 0; + keyRange = IDBKeyRange.bound( + data[weightSort[0]].weight, + data[weightSort[weightSort.length - 1]].weight, + true, + true + ); + + index.openKeyCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length - 2, + "Correct count for bound keyRange arg to index.openKeyCursor" + ); + + count = 0; + keyRange = IDBKeyRange.bound( + data[weightSort[0]].weight - 1, + data[weightSort[weightSort.length - 1]].weight + 1 + ); + + index.openKeyCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length, + "Correct count for bound keyRange arg to index.openKeyCursor" + ); + + count = 0; + keyRange = IDBKeyRange.bound( + data[weightSort[0]].weight - 2, + data[weightSort[0]].weight - 1 + ); + + index.openKeyCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 0, "Correct count for bound keyRange arg to index.openKeyCursor"); + + count = 0; + keyRange = IDBKeyRange.bound( + data[weightSort[1]].weight, + data[weightSort[2]].weight + ); + + index.openKeyCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 3, "Correct count for bound keyRange arg to index.openKeyCursor"); + + count = 0; + + index.openCursor().onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length, + "Correct count for unspecified arg to index.openCursor" + ); + + count = 0; + + index.openCursor(null).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length, + "Correct count for null arg to index.openCursor" + ); + + count = 0; + + index.openCursor(undefined).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length, + "Correct count for undefined arg to index.openCursor" + ); + + count = 0; + + index.openCursor(data[0].weight).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 1, "Correct count for single key arg to index.openCursor"); + + count = 0; + + index.openCursor("foo").onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 0, "Correct count for non-existent key arg to index.openCursor"); + + count = 0; + keyRange = IDBKeyRange.only("foo"); + + index.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + 0, + "Correct count for non-existent keyRange arg to index.openCursor" + ); + + count = 0; + keyRange = IDBKeyRange.only(data[0].weight); + + index.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 1, "Correct count for only keyRange arg to index.openCursor"); + + count = 0; + keyRange = IDBKeyRange.lowerBound(data[weightSort[0]].weight); + + index.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length, + "Correct count for lowerBound keyRange arg to index.openCursor" + ); + + count = 0; + keyRange = IDBKeyRange.lowerBound(data[weightSort[0]].weight, true); + + index.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length - 1, + "Correct count for lowerBound keyRange arg to index.openCursor" + ); + + count = 0; + keyRange = IDBKeyRange.lowerBound("foo"); + + index.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 0, "Correct count for lowerBound keyRange arg to index.openCursor"); + + count = 0; + keyRange = IDBKeyRange.upperBound(data[weightSort[0]].weight); + + index.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 1, "Correct count for upperBound keyRange arg to index.openCursor"); + + count = 0; + keyRange = IDBKeyRange.upperBound(data[weightSort[0]].weight, true); + + index.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 0, "Correct count for upperBound keyRange arg to index.openCursor"); + + count = 0; + keyRange = IDBKeyRange.upperBound( + data[weightSort[weightSort.length - 1]].weight + ); + + index.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length, + "Correct count for upperBound keyRange arg to index.openCursor" + ); + + count = 0; + keyRange = IDBKeyRange.upperBound( + data[weightSort[weightSort.length - 1]].weight, + true + ); + + index.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length - 1, + "Correct count for upperBound keyRange arg to index.openCursor" + ); + + count = 0; + keyRange = IDBKeyRange.upperBound("foo"); + + index.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length, + "Correct count for upperBound keyRange arg to index.openCursor" + ); + + count = 0; + keyRange = IDBKeyRange.upperBound(0); + + index.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 0, "Correct count for upperBound keyRange arg to index.openCursor"); + + count = 0; + keyRange = IDBKeyRange.bound( + data[weightSort[0]].weight, + data[weightSort[weightSort.length - 1]].weight + ); + + index.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length, + "Correct count for bound keyRange arg to index.openCursor" + ); + + count = 0; + keyRange = IDBKeyRange.bound( + data[weightSort[0]].weight, + data[weightSort[weightSort.length - 1]].weight, + true + ); + + index.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length - 1, + "Correct count for bound keyRange arg to index.openCursor" + ); + + count = 0; + keyRange = IDBKeyRange.bound( + data[weightSort[0]].weight, + data[weightSort[weightSort.length - 1]].weight, + true, + true + ); + + index.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length - 2, + "Correct count for bound keyRange arg to index.openCursor" + ); + + count = 0; + keyRange = IDBKeyRange.bound( + data[weightSort[0]].weight - 1, + data[weightSort[weightSort.length - 1]].weight + 1 + ); + + index.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length, + "Correct count for bound keyRange arg to index.openCursor" + ); + + count = 0; + keyRange = IDBKeyRange.bound( + data[weightSort[0]].weight - 2, + data[weightSort[0]].weight - 1 + ); + + index.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 0, "Correct count for bound keyRange arg to index.openCursor"); + + count = 0; + keyRange = IDBKeyRange.bound( + data[weightSort[1]].weight, + data[weightSort[2]].weight + ); + + index.openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 3, "Correct count for bound keyRange arg to index.openCursor"); + + try { + index.get(); + ok(false, "Get with unspecified arg should have thrown"); + } catch (e) { + ok(true, "Get with unspecified arg should have thrown"); + } + + try { + index.get(undefined); + ok(false, "Get with undefined should have thrown"); + } catch (e) { + ok(true, "Get with undefined arg should have thrown"); + } + + try { + index.get(null); + ok(false, "Get with null should have thrown"); + } catch (e) { + is(e instanceof DOMException, true, "Got right kind of exception"); + is(e.name, "DataError", "Correct error."); + is(e.code, 0, "Correct code."); + } + + index.get(data[0].weight).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result.weight, data[0].weight, "Got correct result"); + + keyRange = IDBKeyRange.only(data[0].weight); + + index.get(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result.weight, data[0].weight, "Got correct result"); + + keyRange = IDBKeyRange.lowerBound(data[weightSort[0]].weight); + + index.get(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result.weight, + data[weightSort[0]].weight, + "Got correct result" + ); + + keyRange = IDBKeyRange.lowerBound(data[weightSort[0]].weight - 1); + + index.get(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result.weight, + data[weightSort[0]].weight, + "Got correct result" + ); + + keyRange = IDBKeyRange.lowerBound(data[weightSort[0]].weight + 1); + + index.get(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result.weight, + data[weightSort[1]].weight, + "Got correct result" + ); + + keyRange = IDBKeyRange.lowerBound(data[weightSort[0]].weight, true); + + index.get(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result.weight, + data[weightSort[1]].weight, + "Got correct result" + ); + + keyRange = IDBKeyRange.bound( + data[weightSort[0]].weight, + data[weightSort[1]].weight + ); + + index.get(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result.weight, + data[weightSort[0]].weight, + "Got correct result" + ); + + keyRange = IDBKeyRange.bound( + data[weightSort[0]].weight, + data[weightSort[1]].weight, + true + ); + + index.get(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result.weight, + data[weightSort[1]].weight, + "Got correct result" + ); + + keyRange = IDBKeyRange.bound( + data[weightSort[0]].weight, + data[weightSort[1]].weight, + true, + true + ); + + index.get(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, undefined, "Got correct result"); + + keyRange = IDBKeyRange.upperBound(data[weightSort[5]].weight); + + index.get(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is( + event.target.result.weight, + data[weightSort[0]].weight, + "Got correct result" + ); + + keyRange = IDBKeyRange.upperBound(data[weightSort[0]].weight, true); + + index.get(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, undefined, "Got correct result"); + + try { + index.getKey(); + ok(false, "Get with unspecified arg should have thrown"); + } catch (e) { + ok(true, "Get with unspecified arg should have thrown"); + } + + try { + index.getKey(undefined); + ok(false, "Get with undefined should have thrown"); + } catch (e) { + ok(true, "Get with undefined arg should have thrown"); + } + + try { + index.getKey(null); + ok(false, "Get with null should have thrown"); + } catch (e) { + is(e instanceof DOMException, true, "Got right kind of exception"); + is(e.name, "DataError", "Correct error."); + is(e.code, 0, "Correct code."); + } + + index.getKey(data[0].weight).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, data[0].ssn, "Got correct result"); + + keyRange = IDBKeyRange.only(data[0].weight); + + index.getKey(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, data[0].ssn, "Got correct result"); + + keyRange = IDBKeyRange.lowerBound(data[weightSort[0]].weight); + + index.getKey(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, data[weightSort[0]].ssn, "Got correct result"); + + keyRange = IDBKeyRange.lowerBound(data[weightSort[0]].weight - 1); + + index.getKey(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, data[weightSort[0]].ssn, "Got correct result"); + + keyRange = IDBKeyRange.lowerBound(data[weightSort[0]].weight + 1); + + index.getKey(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, data[weightSort[1]].ssn, "Got correct result"); + + keyRange = IDBKeyRange.lowerBound(data[weightSort[0]].weight, true); + + index.getKey(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, data[weightSort[1]].ssn, "Got correct result"); + + keyRange = IDBKeyRange.bound( + data[weightSort[0]].weight, + data[weightSort[1]].weight + ); + + index.getKey(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, data[weightSort[0]].ssn, "Got correct result"); + + keyRange = IDBKeyRange.bound( + data[weightSort[0]].weight, + data[weightSort[1]].weight, + true + ); + + index.getKey(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, data[weightSort[1]].ssn, "Got correct result"); + + keyRange = IDBKeyRange.bound( + data[weightSort[0]].weight, + data[weightSort[1]].weight, + true, + true + ); + + index.getKey(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, undefined, "Got correct result"); + + keyRange = IDBKeyRange.upperBound(data[weightSort[5]].weight); + + index.getKey(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, data[weightSort[0]].ssn, "Got correct result"); + + keyRange = IDBKeyRange.upperBound(data[weightSort[0]].weight, true); + + index.getKey(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, undefined, "Got correct result"); + + count = 0; + + index.openKeyCursor().onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length, + "Correct count for no arg to index.openKeyCursor" + ); + + count = 0; + + index.openKeyCursor(null).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length, + "Correct count for null arg to index.openKeyCursor" + ); + + count = 0; + + index.openKeyCursor(undefined).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + weightSort.length, + "Correct count for undefined arg to index.openKeyCursor" + ); + + count = 0; + + index.openKeyCursor(data[weightSort[0]].weight).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 1, "Correct count for single key arg to index.openKeyCursor"); + + count = 0; + + index.openKeyCursor("foo").onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is( + count, + 0, + "Correct count for non-existent single key arg to index.openKeyCursor" + ); + + count = 0; + keyRange = IDBKeyRange.only(data[weightSort[0]].weight); + + index.openKeyCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + count++; + cursor.continue(); + } else { + testGenerator.next(); + } + }; + yield undefined; + + is(count, 1, "Correct count for only keyRange arg to index.openKeyCursor"); + + objectStore.mozGetAll(data[1].ssn).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array"); + is(event.target.result.length, 1, "Got correct length"); + is(event.target.result[0].ssn, data[1].ssn, "Got correct result"); + + objectStore.mozGetAll(null).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array"); + is(event.target.result.length, data.length, "Got correct length"); + for (let i in event.target.result) { + is(event.target.result[i].ssn, data[i].ssn, "Got correct value"); + } + + objectStore.mozGetAll(undefined).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array"); + is(event.target.result.length, data.length, "Got correct length"); + for (let i in event.target.result) { + is(event.target.result[i].ssn, data[i].ssn, "Got correct value"); + } + + objectStore.mozGetAll().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array"); + is(event.target.result.length, data.length, "Got correct length"); + for (let i in event.target.result) { + is(event.target.result[i].ssn, data[i].ssn, "Got correct value"); + } + + keyRange = IDBKeyRange.lowerBound(0); + + objectStore.mozGetAll(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array"); + is(event.target.result.length, data.length, "Got correct length"); + for (let i in event.target.result) { + is(event.target.result[i].ssn, data[i].ssn, "Got correct value"); + } + + index.mozGetAll().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array"); + is(event.target.result.length, weightSort.length, "Got correct length"); + for (let i in event.target.result) { + is( + event.target.result[i].ssn, + data[weightSort[i]].ssn, + "Got correct value" + ); + } + + index.mozGetAll(undefined).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array"); + is(event.target.result.length, weightSort.length, "Got correct length"); + for (let i in event.target.result) { + is( + event.target.result[i].ssn, + data[weightSort[i]].ssn, + "Got correct value" + ); + } + + index.mozGetAll(null).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array"); + is(event.target.result.length, weightSort.length, "Got correct length"); + for (let i in event.target.result) { + is( + event.target.result[i].ssn, + data[weightSort[i]].ssn, + "Got correct value" + ); + } + + index.mozGetAll(data[weightSort[0]].weight).onsuccess = + grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array"); + is(event.target.result.length, 1, "Got correct length"); + is(event.target.result[0].ssn, data[weightSort[0]].ssn, "Got correct result"); + + keyRange = IDBKeyRange.lowerBound(0); + + index.mozGetAll(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array"); + is(event.target.result.length, weightSort.length, "Got correct length"); + for (let i in event.target.result) { + is( + event.target.result[i].ssn, + data[weightSort[i]].ssn, + "Got correct value" + ); + } + + index.mozGetAllKeys().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array"); + is(event.target.result.length, weightSort.length, "Got correct length"); + for (let i in event.target.result) { + is(event.target.result[i], data[weightSort[i]].ssn, "Got correct value"); + } + + index.mozGetAllKeys(undefined).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array"); + is(event.target.result.length, weightSort.length, "Got correct length"); + for (let i in event.target.result) { + is(event.target.result[i], data[weightSort[i]].ssn, "Got correct value"); + } + + index.mozGetAllKeys(null).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array"); + is(event.target.result.length, weightSort.length, "Got correct length"); + for (let i in event.target.result) { + is(event.target.result[i], data[weightSort[i]].ssn, "Got correct value"); + } + + index.mozGetAllKeys(data[weightSort[0]].weight).onsuccess = + grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array"); + is(event.target.result.length, 1, "Got correct length"); + is(event.target.result[0], data[weightSort[0]].ssn, "Got correct result"); + + keyRange = IDBKeyRange.lowerBound(0); + + index.mozGetAllKeys(keyRange).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result instanceof Array, true, "Got an array"); + is(event.target.result.length, weightSort.length, "Got correct length"); + for (let i in event.target.result) { + is(event.target.result[i], data[weightSort[i]].ssn, "Got correct value"); + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_orphaned_files.js b/dom/indexedDB/test/unit/test_orphaned_files.js new file mode 100644 index 0000000000..fc4592c356 --- /dev/null +++ b/dom/indexedDB/test/unit/test_orphaned_files.js @@ -0,0 +1,59 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/** + * The goal of this test is to prove that orphaned files are cleaned up during + * origin initialization. A file is orphaned when there's a file with zero size + * in the $dbName.files/journals directory and the file table in the database + * contains no records for given id. A file can become orphaned when we didn't + * have a chance to remove the file from disk during shutdown or the app just + * crashed. + */ + +/* exported testSteps */ +async function testSteps() { + const name = "test_orphaned_files.js"; + + const objectStoreName = "Blobs"; + + const blobData = { key: 1 }; + + info("Installing profile"); + + let request = clearAllDatabases(); + await requestFinished(request); + + // The profile contains one initialized origin directory (with an IndexedDB + // database and an orphaned file), a script for origin initialization and the + // storage database: + // - storage/permanent/chrome + // - create_db.js + // - storage.sqlite + // The file create_db.js in the package was run locally, specifically it was + // temporarily added to xpcshell.ini and then executed: + // mach xpcshell-test --interactive dom/indexedDB/test/unit/create_db.js + // Note: to make it become the profile in the test, additional manual steps + // are needed. + // 1. Remove the file "storage/ls-archive.sqlite". + + installPackagedProfile("orphaned_files_profile"); + + info("Opening database"); + + request = indexedDB.open(name); + await expectingSuccess(request); + + info("Getting data"); + + request = request.result + .transaction([objectStoreName]) + .objectStore(objectStoreName) + .get(blobData.key); + await requestSucceeded(request); + + info("Verifying data"); + + ok(request.result === undefined, "Correct result"); +} diff --git a/dom/indexedDB/test/unit/test_overlapping_transactions.js b/dom/indexedDB/test/unit/test_overlapping_transactions.js new file mode 100644 index 0000000000..0fe6b734c1 --- /dev/null +++ b/dom/indexedDB/test/unit/test_overlapping_transactions.js @@ -0,0 +1,93 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const objectStores = ["foo", "bar"]; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + is(db.objectStoreNames.length, 0, "Correct objectStoreNames list"); + + event.target.onsuccess = grabEventAndContinueHandler; + for (let i in objectStores) { + db.createObjectStore(objectStores[i], { autoIncrement: true }); + } + event = yield undefined; + + is( + db.objectStoreNames.length, + objectStores.length, + "Correct objectStoreNames list" + ); + + for (let i = 0; i < 50; i++) { + let stepNumber = 0; + + request = db.transaction(["foo"], "readwrite").objectStore("foo").add({}); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(stepNumber, 1, "This callback came first"); + stepNumber++; + event.target.transaction.oncomplete = grabEventAndContinueHandler; + }; + + request = db.transaction(["foo"], "readwrite").objectStore("foo").add({}); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(stepNumber, 2, "This callback came second"); + stepNumber++; + event.target.transaction.oncomplete = grabEventAndContinueHandler; + }; + + request = db + .transaction(["foo", "bar"], "readwrite") + .objectStore("bar") + .add({}); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(stepNumber, 3, "This callback came third"); + stepNumber++; + event.target.transaction.oncomplete = grabEventAndContinueHandler; + }; + + request = db + .transaction(["foo", "bar"], "readwrite") + .objectStore("bar") + .add({}); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(stepNumber, 4, "This callback came fourth"); + stepNumber++; + event.target.transaction.oncomplete = grabEventAndContinueHandler; + }; + + request = db.transaction(["bar"], "readwrite").objectStore("bar").add({}); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(stepNumber, 5, "This callback came fifth"); + stepNumber++; + event.target.transaction.oncomplete = grabEventAndContinueHandler; + }; + + stepNumber++; + yield undefined; + yield undefined; + yield undefined; + yield undefined; + yield undefined; + + is(stepNumber, 6, "All callbacks received"); + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_put_get_values.js b/dom/indexedDB/test/unit/test_put_get_values.js new file mode 100644 index 0000000000..364a3c12e5 --- /dev/null +++ b/dom/indexedDB/test/unit/test_put_get_values.js @@ -0,0 +1,52 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const objectStoreName = "Objects"; + + let testString = { key: 0, value: "testString" }; + let testInt = { key: 1, value: 1002 }; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + + let objectStore = db.createObjectStore(objectStoreName, { autoIncrement: 0 }); + + request = objectStore.add(testString.value, testString.key); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(event.target.result, testString.key, "Got the right key"); + request = objectStore.get(testString.key); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(event.target.result, testString.value, "Got the right value"); + }; + }; + + request = objectStore.add(testInt.value, testInt.key); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(event.target.result, testInt.key, "Got the right key"); + request = objectStore.get(testInt.key); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(event.target.result, testInt.value, "Got the right value"); + }; + }; + + // Wait for success + yield undefined; + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_put_get_values_autoIncrement.js b/dom/indexedDB/test/unit/test_put_get_values_autoIncrement.js new file mode 100644 index 0000000000..fe91bf5582 --- /dev/null +++ b/dom/indexedDB/test/unit/test_put_get_values_autoIncrement.js @@ -0,0 +1,52 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const objectStoreName = "Objects"; + + let testString = { value: "testString" }; + let testInt = { value: 1002 }; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + + let objectStore = db.createObjectStore(objectStoreName, { autoIncrement: 1 }); + + request = objectStore.put(testString.value); + request.onerror = errorHandler; + request.onsuccess = function (event) { + testString.key = event.target.result; + request = objectStore.get(testString.key); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(event.target.result, testString.value, "Got the right value"); + }; + }; + + request = objectStore.put(testInt.value); + request.onerror = errorHandler; + request.onsuccess = function (event) { + testInt.key = event.target.result; + request = objectStore.get(testInt.key); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(event.target.result, testInt.value, "Got the right value"); + }; + }; + + // Wait for success + yield undefined; + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_quotaExceeded_recovery.js b/dom/indexedDB/test/unit/test_quotaExceeded_recovery.js new file mode 100644 index 0000000000..20366be417 --- /dev/null +++ b/dom/indexedDB/test/unit/test_quotaExceeded_recovery.js @@ -0,0 +1,141 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator, disableWorkerTest */ +var disableWorkerTest = "Need a way to set temporary prefs from a worker"; + +var testGenerator = testSteps(); + +function* testSteps() { + const spec = "http://foo.com"; + const name = this.window + ? window.location.pathname + : "test_quotaExceeded_recovery"; + const objectStoreName = "foo"; + + const android = mozinfo.os == "android"; + + // We want 512 KB database on Android and 4 MB database on other platforms. + const groupLimitKB = android ? 512 : 4096; + + // The group limit is calculated as 20% of the global temporary storage limit. + const tempStorageLimitKB = groupLimitKB * 5; + + // We want 64 KB chunks on Android and 512 KB chunks on other platforms. + const dataSizeKB = android ? 64 : 512; + const dataSize = dataSizeKB * 1024; + + const maxIter = 5; + + for (let blobs of [false, true]) { + setTemporaryStorageLimit(tempStorageLimitKB); + + clearAllDatabases(continueToNextStepSync); + yield undefined; + + info("Opening database"); + + let request = indexedDB.openForPrincipal(getPrincipal(spec), name); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + + yield undefined; + + // upgradeneeded + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + + info("Creating objectStore"); + + request.result.createObjectStore(objectStoreName, { autoIncrement: true }); + + yield undefined; + + // success + let db = request.result; + db.onerror = errorHandler; + + ok(true, "Filling database"); + + let obj = { + name: "foo", + }; + + if (!blobs) { + obj.data = getRandomView(dataSize); + } + + let iter = 1; + let i = 1; + let j = 1; + while (true) { + if (blobs) { + obj.data = getBlob(getView(dataSize)); + } + + let trans = db.transaction(objectStoreName, "readwrite"); + request = trans.objectStore(objectStoreName).add(obj); + request.onerror = function (event) { + event.stopPropagation(); + }; + + trans.oncomplete = function (event) { + if (iter == 1) { + i++; + } + j++; + testGenerator.next(true); + }; + trans.onabort = function (event) { + is(trans.error.name, "QuotaExceededError", "Reached quota limit"); + testGenerator.next(false); + }; + + let completeFired = yield undefined; + if (completeFired) { + ok(true, "Got complete event"); + continue; + } + + ok(true, "Got abort event"); + + if (iter++ == maxIter) { + break; + } + + if (iter > 1) { + ok(i == j, "Recycled entire database"); + j = 1; + } + + trans = db.transaction(objectStoreName, "readwrite"); + + // Don't use a cursor for deleting stored blobs (Cursors prolong live + // of stored files since each record must be fetched from the database + // first which creates a memory reference to the stored blob.) + if (blobs) { + request = trans.objectStore(objectStoreName).clear(); + } else { + request = trans.objectStore(objectStoreName).openCursor(); + request.onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + cursor.delete(); + cursor.continue(); + } + }; + } + + trans.onabort = unexpectedSuccessHandler; + trans.oncomplete = grabEventAndContinueHandler; + + yield undefined; + } + } + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_readonly_transactions.js b/dom/indexedDB/test/unit/test_readonly_transactions.js new file mode 100644 index 0000000000..8252ae028f --- /dev/null +++ b/dom/indexedDB/test/unit/test_readonly_transactions.js @@ -0,0 +1,168 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const osName = "foo"; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + is(db.objectStoreNames.length, 0, "Correct objectStoreNames list"); + + db.createObjectStore(osName, { autoIncrement: "true" }); + + yield undefined; + + let key1, key2; + + request = db.transaction([osName], "readwrite").objectStore(osName).add({}); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(event.target.transaction.mode, "readwrite", "Correct mode"); + key1 = event.target.result; + testGenerator.next(); + }; + yield undefined; + + request = db.transaction(osName, "readwrite").objectStore(osName).add({}); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(event.target.transaction.mode, "readwrite", "Correct mode"); + key2 = event.target.result; + testGenerator.next(); + }; + yield undefined; + + request = db + .transaction([osName], "readwrite") + .objectStore(osName) + .put({}, key1); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(event.target.transaction.mode, "readwrite", "Correct mode"); + testGenerator.next(); + }; + yield undefined; + + request = db + .transaction(osName, "readwrite") + .objectStore(osName) + .put({}, key2); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(event.target.transaction.mode, "readwrite", "Correct mode"); + testGenerator.next(); + }; + yield undefined; + + request = db + .transaction([osName], "readwrite") + .objectStore(osName) + .put({}, key1); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(event.target.transaction.mode, "readwrite", "Correct mode"); + testGenerator.next(); + }; + yield undefined; + + request = db + .transaction(osName, "readwrite") + .objectStore(osName) + .put({}, key1); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(event.target.transaction.mode, "readwrite", "Correct mode"); + testGenerator.next(); + }; + yield undefined; + + request = db + .transaction([osName], "readwrite") + .objectStore(osName) + .delete(key1); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(event.target.transaction.mode, "readwrite", "Correct mode"); + testGenerator.next(); + }; + yield undefined; + + request = db + .transaction(osName, "readwrite") + .objectStore(osName) + .delete(key2); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(event.target.transaction.mode, "readwrite", "Correct mode"); + testGenerator.next(); + }; + yield undefined; + + try { + request = db.transaction([osName]).objectStore(osName).add({}); + ok(false, "Adding to a readonly transaction should fail!"); + } catch (e) { + ok(true, "Adding to a readonly transaction failed"); + } + + try { + request = db.transaction(osName).objectStore(osName).add({}); + ok(false, "Adding to a readonly transaction should fail!"); + } catch (e) { + ok(true, "Adding to a readonly transaction failed"); + } + + try { + request = db.transaction([osName]).objectStore(osName).put({}); + ok(false, "Adding or modifying a readonly transaction should fail!"); + } catch (e) { + ok(true, "Adding or modifying a readonly transaction failed"); + } + + try { + request = db.transaction(osName).objectStore(osName).put({}); + ok(false, "Adding or modifying a readonly transaction should fail!"); + } catch (e) { + ok(true, "Adding or modifying a readonly transaction failed"); + } + + try { + request = db.transaction([osName]).objectStore(osName).put({}, key1); + ok(false, "Modifying a readonly transaction should fail!"); + } catch (e) { + ok(true, "Modifying a readonly transaction failed"); + } + + try { + request = db.transaction(osName).objectStore(osName).put({}, key1); + ok(false, "Modifying a readonly transaction should fail!"); + } catch (e) { + ok(true, "Modifying a readonly transaction failed"); + } + + try { + request = db.transaction([osName]).objectStore(osName).delete(key1); + ok(false, "Removing from a readonly transaction should fail!"); + } catch (e) { + ok(true, "Removing from a readonly transaction failed"); + } + + try { + request = db.transaction(osName).objectStore(osName).delete(key2); + ok(false, "Removing from a readonly transaction should fail!"); + } catch (e) { + ok(true, "Removing from a readonly transaction failed"); + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_readwriteflush_disabled.js b/dom/indexedDB/test/unit/test_readwriteflush_disabled.js new file mode 100644 index 0000000000..6271959346 --- /dev/null +++ b/dom/indexedDB/test/unit/test_readwriteflush_disabled.js @@ -0,0 +1,72 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator, disableWorkerTest */ +var disableWorkerTest = "Need a way to set temporary prefs from a worker"; + +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window + ? window.location.pathname + : "test_readwriteflush_disabled.js"; + + info("Resetting experimental pref"); + + if (this.window) { + SpecialPowers.pushPrefEnv( + { + set: [["dom.indexedDB.experimental", false]], + }, + continueToNextStep + ); + yield undefined; + } else { + resetExperimental(); + } + + info("Opening database"); + + let request = indexedDB.open(name); + request.onerror = errorHandler; + request.onupgradeneeded = continueToNextStepSync; + request.onsuccess = unexpectedSuccessHandler; + + yield undefined; + + // upgradeneeded + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = continueToNextStepSync; + + info("Creating objectStore"); + + request.result.createObjectStore(name); + + yield undefined; + + // success + let db = request.result; + + info("Attempting to create a 'readwriteflush' transaction"); + + let exception; + + try { + db.transaction(name, "readwriteflush"); + } catch (e) { + exception = e; + } + + ok(exception, "'readwriteflush' transaction threw"); + ok(exception instanceof Error, "exception is an Error object"); + is( + exception.message, + "IDBDatabase.transaction: 'readwriteflush' (value of argument 2) is not " + + "a valid value for enumeration IDBTransactionMode.", + "exception has the correct message" + ); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_remove_index.js b/dom/indexedDB/test/unit/test_remove_index.js new file mode 100644 index 0000000000..5cdd096bab --- /dev/null +++ b/dom/indexedDB/test/unit/test_remove_index.js @@ -0,0 +1,56 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const indexName = "My Test Index"; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + is(db.objectStoreNames.length, 0, "Correct objectStoreNames list"); + + let objectStore = db.createObjectStore("test store", { keyPath: "foo" }); + is(db.objectStoreNames.length, 1, "Correct objectStoreNames list"); + is(db.objectStoreNames.item(0), objectStore.name, "Correct name"); + + is(objectStore.indexNames.length, 0, "Correct indexNames list"); + + let index = objectStore.createIndex(indexName, "foo"); + + is(objectStore.indexNames.length, 1, "Correct indexNames list"); + is(objectStore.indexNames.item(0), indexName, "Correct name"); + is(objectStore.index(indexName), index, "Correct instance"); + + objectStore.deleteIndex(indexName); + + is(objectStore.indexNames.length, 0, "Correct indexNames list"); + try { + objectStore.index(indexName); + ok(false, "should have thrown"); + } catch (ex) { + ok(ex instanceof DOMException, "Got a DOMException"); + is(ex.name, "NotFoundError", "expect a NotFoundError"); + is(ex.code, DOMException.NOT_FOUND_ERR, "expect a NOT_FOUND_ERR"); + } + + let index2 = objectStore.createIndex(indexName, "foo"); + isnot(index, index2, "New instance should be created"); + + is(objectStore.indexNames.length, 1, "Correct recreacted indexNames list"); + is(objectStore.indexNames.item(0), indexName, "Correct recreacted name"); + is(objectStore.index(indexName), index2, "Correct instance"); + + event.target.transaction.oncomplete = grabEventAndContinueHandler; + event = yield undefined; + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_remove_objectStore.js b/dom/indexedDB/test/unit/test_remove_objectStore.js new file mode 100644 index 0000000000..bdc16d9a6a --- /dev/null +++ b/dom/indexedDB/test/unit/test_remove_objectStore.js @@ -0,0 +1,131 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const objectStoreName = "Objects"; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + let event = yield undefined; + + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + + let db = event.target.result; + is(db.objectStoreNames.length, 0, "Correct objectStoreNames list"); + + let objectStore = db.createObjectStore(objectStoreName, { keyPath: "foo" }); + + let addedCount = 0; + + for (let i = 0; i < 100; i++) { + request = objectStore.add({ foo: i }); + request.onerror = errorHandler; + request.onsuccess = function (event) { + if (++addedCount == 100) { + executeSoon(function () { + testGenerator.next(); + }); + } + }; + } + yield undefined; + + is(db.objectStoreNames.length, 1, "Correct objectStoreNames list"); + is(db.objectStoreNames.item(0), objectStoreName, "Correct name"); + + event.target.transaction.oncomplete = grabEventAndContinueHandler; + event = yield undefined; + + // Wait for success. + event = yield undefined; + + db.close(); + + request = indexedDB.open(name, 2); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + event = yield undefined; + + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + + db = event.target.result; + let trans = event.target.transaction; + + let oldObjectStore = trans.objectStore(objectStoreName); + isnot(oldObjectStore, null, "Correct object store prior to deleting"); + db.deleteObjectStore(objectStoreName); + is(db.objectStoreNames.length, 0, "Correct objectStores list"); + try { + trans.objectStore(objectStoreName); + ok(false, "should have thrown"); + } catch (ex) { + ok(ex instanceof DOMException, "Got a DOMException"); + is(ex.name, "NotFoundError", "expect a NotFoundError"); + is(ex.code, DOMException.NOT_FOUND_ERR, "expect a NOT_FOUND_ERR"); + } + + objectStore = db.createObjectStore(objectStoreName, { keyPath: "foo" }); + is(db.objectStoreNames.length, 1, "Correct objectStoreNames list"); + is(db.objectStoreNames.item(0), objectStoreName, "Correct name"); + is( + trans.objectStore(objectStoreName), + objectStore, + "Correct new objectStore" + ); + isnot(oldObjectStore, objectStore, "Old objectStore is not new objectStore"); + + request = objectStore.openCursor(); + request.onerror = errorHandler; + request.onsuccess = function (event) { + is(event.target.result, null, "ObjectStore shouldn't have any items"); + testGenerator.next(event); + }; + event = yield undefined; + + db.deleteObjectStore(objectStore.name); + is(db.objectStoreNames.length, 0, "Correct objectStores list"); + + continueToNextStep(); + yield undefined; + + trans.oncomplete = grabEventAndContinueHandler; + event = yield undefined; + + // Wait for success. + event = yield undefined; + + db.close(); + + request = indexedDB.open(name, 3); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + event = yield undefined; + + db = event.target.result; + trans = event.target.transaction; + + objectStore = db.createObjectStore(objectStoreName, { keyPath: "foo" }); + + request = objectStore.add({ foo: "bar" }); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + db.deleteObjectStore(objectStoreName); + + event = yield undefined; + + trans.oncomplete = grabEventAndContinueHandler; + event = yield undefined; + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_rename_index.js b/dom/indexedDB/test/unit/test_rename_index.js new file mode 100644 index 0000000000..fb4af954b3 --- /dev/null +++ b/dom/indexedDB/test/unit/test_rename_index.js @@ -0,0 +1,196 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const storeName = "test store"; + const indexName_ToBeDeleted = "test index to be deleted"; + const indexName_v0 = "test index v0"; + const indexName_v1 = "test index v1"; + const indexName_v2 = "test index v2"; + const indexName_v3 = indexName_ToBeDeleted; + const indexName_v4 = "test index v4"; + + info("Rename in v1."); + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + let event = yield undefined; + + let db = event.target.result; + let txn = event.target.transaction; + + is(db.objectStoreNames.length, 0, "Correct objectStoreNames list"); + + let objectStore = db.createObjectStore(storeName, { keyPath: "foo" }); + is(db.objectStoreNames.length, 1, "Correct objectStoreNames list"); + is( + db.objectStoreNames.item(0), + objectStore.name, + "Correct object store name" + ); + + // create index to be deleted later in v3. + objectStore.createIndex(indexName_ToBeDeleted, "foo"); + ok(objectStore.index(indexName_ToBeDeleted), "Index created."); + + // create target index to be renamed. + let index = objectStore.createIndex(indexName_v0, "bar"); + ok(objectStore.index(indexName_v0), "Index created."); + is(index.name, indexName_v0, "Correct index name"); + index.name = indexName_v1; + is(index.name, indexName_v1, "Renamed index successfully"); + + txn.oncomplete = continueToNextStepSync; + yield undefined; + request.onsuccess = continueToNextStep; + yield undefined; + db.close(); + + info("Verify renaming done in v1 and run renaming in v2."); + request = indexedDB.open(name, 2); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + event = yield undefined; + + db = event.target.result; + txn = event.target.transaction; + + objectStore = txn.objectStore(storeName); + + // indexName_v0 created in v1 shall not be available. + try { + index = objectStore.index(indexName_v0); + ok(false, "NotFoundError shall be thrown."); + } catch (e) { + ok(e instanceof DOMException, "got a database exception"); + is(e.name, "NotFoundError", "correct error"); + } + + // rename to "v2". + index = objectStore.index(indexName_v1); + is(index.name, indexName_v1, "Correct index name"); + index.name = indexName_v2; + is(index.name, indexName_v2, "Renamed index successfully"); + + txn.oncomplete = continueToNextStepSync; + yield undefined; + request.onsuccess = continueToNextStep; + yield undefined; + db.close(); + + info("Verify renaming done in v2."); + request = indexedDB.open(name, 2); + request.onerror = errorHandler; + request.onupgradeneeded = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + db = event.target.result; + txn = db.transaction(storeName); + + objectStore = txn.objectStore(storeName); + index = objectStore.index(indexName_v2); + is(index.name, indexName_v2, "Correct index name"); + + db.close(); + + info("Rename in v3."); + request = indexedDB.open(name, 3); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + event = yield undefined; + + db = event.target.result; + txn = event.target.transaction; + + objectStore = txn.objectStore(storeName); + ok(objectStore.index(indexName_ToBeDeleted), "index is valid."); + objectStore.deleteIndex(indexName_ToBeDeleted); + try { + objectStore.index(indexName_ToBeDeleted); + ok(false, "NotFoundError shall be thrown if the index name is deleted."); + } catch (e) { + ok(e instanceof DOMException, "got a database exception"); + is(e.name, "NotFoundError", "correct error"); + } + + info("Rename with the name of the deleted index."); + index = objectStore.index(indexName_v2); + index.name = indexName_v3; + is(index.name, indexName_v3, "Renamed index successfully"); + + txn.oncomplete = continueToNextStepSync; + yield undefined; + request.onsuccess = continueToNextStep; + yield undefined; + db.close(); + + info("Verify renaming done in v3."); + request = indexedDB.open(name, 3); + request.onerror = errorHandler; + request.onupgradeneeded = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + db = event.target.result; + txn = db.transaction(storeName); + + objectStore = txn.objectStore(storeName); + index = objectStore.index(indexName_v3); + is(index.name, indexName_v3, "Correct index name"); + + db.close(); + + info("Abort the version change transaction while renaming index."); + request = indexedDB.open(name, 4); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + event = yield undefined; + + db = event.target.result; + txn = event.target.transaction; + + objectStore = txn.objectStore(storeName); + index = objectStore.index(indexName_v3); + index.name = indexName_v4; + is(index.name, indexName_v4, "Renamed successfully"); + let putRequest = objectStore.put({ foo: "fooValue", bar: "barValue" }); + putRequest.onsuccess = continueToNextStepSync; + yield undefined; + + // Aborting the transaction. + request.onerror = expectedErrorHandler("AbortError"); + txn.abort(); + yield undefined; + + // Verify if the name of the index handle is reverted. + is(index.name, indexName_v3, "The name is reverted after aborted."); + + info("Verify if the objectstore name is unchanged."); + request = indexedDB.open(name, 3); + request.onerror = errorHandler; + request.onupgradeneeded = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + db = event.target.result; + txn = db.transaction(storeName); + + objectStore = txn.objectStore(storeName); + index = objectStore.index(indexName_v3); + is(index.name, indexName_v3, "Correct index name"); + + db.close(); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_rename_index_errors.js b/dom/indexedDB/test/unit/test_rename_index_errors.js new file mode 100644 index 0000000000..34a83fe22d --- /dev/null +++ b/dom/indexedDB/test/unit/test_rename_index_errors.js @@ -0,0 +1,137 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const storeName = "test store"; + const indexName1 = "test index 1"; + const indexName2 = "test index 2"; + + info("Setup test indexes."); + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + let event = yield undefined; + + let db = event.target.result; + let txn = event.target.transaction; + + is(db.objectStoreNames.length, 0, "Correct objectStoreNames list"); + + let objectStore = db.createObjectStore(storeName, { keyPath: "foo" }); + is(db.objectStoreNames.length, 1, "Correct objectStoreNames list"); + is(db.objectStoreNames.item(0), objectStore.name, "Correct name"); + + let index1 = objectStore.createIndex(indexName1, "bar"); + is(objectStore.index(indexName1).name, index1.name, "Correct index name"); + is(index1.name, indexName1, "Correct index name"); + let index2 = objectStore.createIndex(indexName2, "baz"); + is(objectStore.index(indexName2).name, index2.name, "Correct index name"); + is(index2.name, indexName2, "Correct index name"); + + txn.oncomplete = continueToNextStepSync; + yield undefined; + request.onsuccess = continueToNextStep; + yield undefined; + db.close(); + + info("Verify IDB Errors in version 2."); + request = indexedDB.open(name, 2); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + event = yield undefined; + + db = event.target.result; + txn = event.target.transaction; + + objectStore = txn.objectStore(storeName); + index1 = objectStore.index(indexName1); + index2 = objectStore.index(indexName2); + is(index1.name, indexName1, "Correct index name"); + is(index2.name, indexName2, "Correct index name"); + + // Rename with the name already adopted by the other index. + try { + index1.name = indexName2; + ok( + false, + "ConstraintError shall be thrown if the index name already exists." + ); + } catch (e) { + ok(e instanceof DOMException, "got a database exception"); + is(e.name, "ConstraintError", "correct error"); + } + + // Rename with identical name. + try { + index1.name = indexName1; + ok(true, "It shall be fine to set the same name."); + } catch (e) { + ok(false, "Got a database exception: " + e.name); + } + + objectStore.deleteIndex(indexName2); + + // Rename after deleted. + try { + index2.name = indexName2; + ok(false, "InvalidStateError shall be thrown if deleted."); + } catch (e) { + ok(e instanceof DOMException, "got a database exception"); + is(e.name, "InvalidStateError", "correct error"); + } + + txn.oncomplete = continueToNextStepSync; + yield undefined; + request.onsuccess = continueToNextStep; + yield undefined; + db.close(); + + // Rename when the transaction is inactive. + try { + index1.name = indexName1; + ok( + false, + "TransactionInactiveError shall be thrown if the transaction is inactive." + ); + } catch (e) { + ok(e instanceof DOMException, "got a database exception"); + is(e.name, "TransactionInactiveError", "correct error"); + } + + info("Rename when the transaction is not an upgrade one."); + request = indexedDB.open(name, 2); + request.onerror = errorHandler; + request.onupgradeneeded = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + db = event.target.result; + txn = db.transaction(storeName); + objectStore = txn.objectStore(storeName); + index1 = objectStore.index(indexName1); + + try { + index1.name = indexName1; + ok( + false, + "InvalidStateError shall be thrown if it's not an upgrade transaction." + ); + } catch (e) { + ok(e instanceof DOMException, "got a database exception"); + is(e.name, "InvalidStateError", "correct error"); + } + + txn.oncomplete = continueToNextStepSync; + yield undefined; + db.close(); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_rename_objectStore.js b/dom/indexedDB/test/unit/test_rename_objectStore.js new file mode 100644 index 0000000000..6d3524b8ff --- /dev/null +++ b/dom/indexedDB/test/unit/test_rename_objectStore.js @@ -0,0 +1,173 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const storeName_ToBeDeleted = "test store to be deleted"; + const storeName_v0 = "test store v0"; + const storeName_v1 = "test store v1"; + const storeName_v2 = "test store v2"; + const storeName_v3 = storeName_ToBeDeleted; + const storeName_v4 = "test store v4"; + + info("Rename in v1."); + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + let event = yield undefined; + + let db = event.target.result; + let txn = event.target.transaction; + + is(db.objectStoreNames.length, 0, "Correct objectStoreNames list"); + + // create objectstore to be deleted later in v3. + db.createObjectStore(storeName_ToBeDeleted, { keyPath: "foo" }); + is(db.objectStoreNames.length, 1, "Correct objectStoreNames list"); + ok(db.objectStoreNames.contains(storeName_ToBeDeleted), "Correct name"); + + // create target objectstore to be renamed. + let objectStore = db.createObjectStore(storeName_v0, { keyPath: "bar" }); + is(db.objectStoreNames.length, 2, "Correct objectStoreNames list"); + ok(db.objectStoreNames.contains(objectStore.name), "Correct name"); + + objectStore.name = storeName_v1; + is(objectStore.name, storeName_v1, "Renamed successfully"); + + txn.oncomplete = continueToNextStepSync; + yield undefined; + request.onsuccess = continueToNextStep; + yield undefined; + db.close(); + + info("Verify renaming done in v1 and run renaming in v2."); + request = indexedDB.open(name, 2); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + event = yield undefined; + + db = event.target.result; + txn = event.target.transaction; + + is(db.objectStoreNames.length, 2, "Correct objectStoreNames list"); + ok(db.objectStoreNames.contains(storeName_v1), "Correct name"); + ok(db.objectStoreNames.contains(storeName_ToBeDeleted), "Correct name"); + + objectStore = txn.objectStore(storeName_v1); + objectStore.name = storeName_v2; + is(objectStore.name, storeName_v2, "Renamed successfully"); + + txn.oncomplete = continueToNextStepSync; + yield undefined; + request.onsuccess = continueToNextStep; + yield undefined; + db.close(); + + info("Verify renaming done in v2."); + request = indexedDB.open(name, 2); + request.onerror = errorHandler; + request.onupgradeneeded = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + db = event.target.result; + + is(db.objectStoreNames.length, 2, "Correct objectStoreNames list"); + ok(db.objectStoreNames.contains(storeName_v2), "Correct name"); + ok(db.objectStoreNames.contains(storeName_ToBeDeleted), "Correct name"); + + db.close(); + + info("Rename in v3."); + request = indexedDB.open(name, 3); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + event = yield undefined; + + db = event.target.result; + txn = event.target.transaction; + + is(db.objectStoreNames.length, 2, "Correct objectStoreNames list"); + ok(db.objectStoreNames.contains(storeName_v2), "Correct name"); + ok(db.objectStoreNames.contains(storeName_ToBeDeleted), "Correct name"); + db.deleteObjectStore(storeName_ToBeDeleted); + is(db.objectStoreNames.length, 1, "Correct objectStoreNames list"); + ok( + db.objectStoreNames.contains(storeName_v2) && + !db.objectStoreNames.contains(storeName_ToBeDeleted), + "Deleted correctly" + ); + + objectStore = txn.objectStore(storeName_v2); + objectStore.name = storeName_v3; + is(objectStore.name, storeName_v3, "Renamed successfully"); + + txn.oncomplete = continueToNextStepSync; + yield undefined; + request.onsuccess = continueToNextStep; + yield undefined; + db.close(); + + info("Verify renaming done in v3."); + request = indexedDB.open(name, 3); + request.onerror = errorHandler; + request.onupgradeneeded = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + db = event.target.result; + + is(db.objectStoreNames.length, 1, "Correct objectStoreNames list"); + ok(db.objectStoreNames.contains(storeName_v3), "Correct name"); + + db.close(); + + info("Abort the version change transaction while renaming objectstore."); + request = indexedDB.open(name, 4); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + event = yield undefined; + + db = event.target.result; + txn = event.target.transaction; + + objectStore = txn.objectStore(storeName_v3); + objectStore.name = storeName_v4; + is(objectStore.name, storeName_v4, "Renamed successfully"); + let putRequest = objectStore.put({ bar: "barValue" }); + putRequest.onsuccess = continueToNextStepSync; + yield undefined; + + // Aborting the transaction. + request.onerror = expectedErrorHandler("AbortError"); + txn.abort(); + yield undefined; + + // Verify if the name of the objectStore handle is reverted. + is(objectStore.name, storeName_v3, "The name is reverted after aborted."); + + info("Verify if the objectstore name is unchanged."); + request = indexedDB.open(name, 3); + request.onerror = errorHandler; + request.onupgradeneeded = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + db = event.target.result; + + is(db.objectStoreNames.length, 1, "Correct objectStoreNames list"); + ok(db.objectStoreNames.contains(storeName_v3), "Correct name"); + + db.close(); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_rename_objectStore_errors.js b/dom/indexedDB/test/unit/test_rename_objectStore_errors.js new file mode 100644 index 0000000000..d7b56053e7 --- /dev/null +++ b/dom/indexedDB/test/unit/test_rename_objectStore_errors.js @@ -0,0 +1,135 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + const storeName1 = "test store 1"; + const storeName2 = "test store 2"; + + info("Setup test object stores."); + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + let event = yield undefined; + + let db = event.target.result; + let txn = event.target.transaction; + + is(db.objectStoreNames.length, 0, "Correct objectStoreNames list"); + + let objectStore1 = db.createObjectStore(storeName1, { keyPath: "foo" }); + is(db.objectStoreNames.length, 1, "Correct objectStoreNames list"); + is(db.objectStoreNames.item(0), objectStore1.name, "Correct name"); + is(objectStore1.name, storeName1, "Correct name"); + + let objectStore2 = db.createObjectStore(storeName2, { keyPath: "bar" }); + is(db.objectStoreNames.length, 2, "Correct objectStoreNames list"); + is(db.objectStoreNames.item(1), objectStore2.name, "Correct name"); + is(objectStore2.name, storeName2, "Correct name"); + + txn.oncomplete = continueToNextStepSync; + yield undefined; + request.onsuccess = continueToNextStep; + yield undefined; + db.close(); + + info("Verify IDB Errors in version 2."); + request = indexedDB.open(name, 2); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = continueToNextStep; + event = yield undefined; + + db = event.target.result; + txn = event.target.transaction; + + is(db.objectStoreNames.length, 2, "Correct objectStoreNames list"); + + objectStore1 = txn.objectStore(storeName1); + objectStore2 = txn.objectStore(storeName2); + is(objectStore1.name, storeName1, "Correct name"); + is(objectStore2.name, storeName2, "Correct name"); + + // Rename with the name already adopted by the other object store. + try { + objectStore1.name = storeName2; + ok( + false, + "ConstraintError shall be thrown if the store name already exists." + ); + } catch (e) { + ok(e instanceof DOMException, "got a database exception"); + is(e.name, "ConstraintError", "correct error"); + } + + // Rename with the identical name. + try { + objectStore1.name = storeName1; + ok(true, "It shall be fine to set the same name."); + } catch (e) { + ok(false, "Got a database exception: " + e.name); + } + + db.deleteObjectStore(storeName2); + + // Rename after deleted. + try { + objectStore2.name = storeName2; + ok(false, "InvalidStateError shall be thrown if deleted."); + } catch (e) { + ok(e instanceof DOMException, "got a database exception"); + is(e.name, "InvalidStateError", "correct error"); + } + + txn.oncomplete = continueToNextStepSync; + yield undefined; + request.onsuccess = continueToNextStep; + yield undefined; + db.close(); + + info("Rename when the transaction is inactive."); + try { + objectStore1.name = storeName1; + ok( + false, + "TransactionInactiveError shall be thrown if the transaction is inactive." + ); + } catch (e) { + ok(e instanceof DOMException, "got a database exception"); + is(e.name, "TransactionInactiveError", "correct error"); + } + + info("Rename when the transaction is not an upgrade one."); + request = indexedDB.open(name, 2); + request.onerror = errorHandler; + request.onupgradeneeded = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + db = event.target.result; + txn = db.transaction(storeName1); + objectStore1 = txn.objectStore(storeName1); + + try { + objectStore1.name = storeName1; + ok( + false, + "InvalidStateError shall be thrown if it's not an upgrade transaction." + ); + } catch (e) { + ok(e instanceof DOMException, "got a database exception"); + is(e.name, "InvalidStateError", "correct error"); + } + + txn.oncomplete = continueToNextStepSync; + yield undefined; + db.close(); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_request_readyState.js b/dom/indexedDB/test/unit/test_request_readyState.js new file mode 100644 index 0000000000..db42c4e349 --- /dev/null +++ b/dom/indexedDB/test/unit/test_request_readyState.js @@ -0,0 +1,50 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + let request = indexedDB.open(name, 1); + is(request.readyState, "pending", "Correct readyState"); + + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + is(request.readyState, "done", "Correct readyState"); + + let db = event.target.result; + + let objectStore = db.createObjectStore("foo"); + let key = 10; + + request = objectStore.add({}, key); + is(request.readyState, "pending", "Correct readyState"); + + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(request.readyState, "done", "Correct readyState"); + is(event.target.result, key, "Correct key"); + + request = objectStore.get(key); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + is(request.readyState, "pending", "Correct readyState"); + event = yield undefined; + + ok(event.target.result, "Got something"); + is(request.readyState, "done", "Correct readyState"); + + // Wait for success + yield undefined; + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_sandbox.js b/dom/indexedDB/test/unit/test_sandbox.js new file mode 100644 index 0000000000..be9d2eb79b --- /dev/null +++ b/dom/indexedDB/test/unit/test_sandbox.js @@ -0,0 +1,82 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +function exerciseInterface() { + function DB(name, store) { + this.name = name; + this.store = store; + this._db = this._create(); + } + + DB.prototype = { + _create() { + var op = indexedDB.open(this.name); + op.onupgradeneeded = e => { + var db = e.target.result; + db.createObjectStore(this.store); + }; + return new Promise(resolve => { + op.onsuccess = e => resolve(e.target.result); + }); + }, + + _result(tx, op) { + return new Promise((resolve, reject) => { + op.onsuccess = e => resolve(e.target.result); + op.onerror = () => reject(op.error); + tx.onabort = () => reject(tx.error); + }); + }, + + get(k) { + return this._db.then(db => { + var tx = db.transaction(this.store, "readonly"); + var store = tx.objectStore(this.store); + return this._result(tx, store.get(k)); + }); + }, + + add(k, v) { + return this._db.then(db => { + var tx = db.transaction(this.store, "readwrite"); + var store = tx.objectStore(this.store); + return this._result(tx, store.add(v, k)); + }); + }, + }; + + var db = new DB("data", "base"); + return db + .add("x", [10, {}]) + .then(_ => db.get("x")) + .then(x => { + equal(x.length, 2); + equal(x[0], 10); + equal(typeof x[1], "object"); + equal(Object.keys(x[1]).length, 0); + }); +} + +function run_test() { + do_get_profile(); + + let sb = new Cu.Sandbox("https://www.example.com", { + wantGlobalProperties: ["indexedDB"], + }); + + sb.equal = equal; + var innerPromise = new Promise((resolve, reject) => { + sb.test_done = resolve; + sb.test_error = reject; + }); + Cu.evalInSandbox( + "(" + + exerciseInterface.toSource() + + ")()" + + ".then(test_done, test_error);", + sb + ); + + do_test_pending(); + Promise.all([innerPromise, exerciseInterface()]).then(do_test_finished); +} diff --git a/dom/indexedDB/test/unit/test_schema18upgrade.js b/dom/indexedDB/test/unit/test_schema18upgrade.js new file mode 100644 index 0000000000..af44a42b81 --- /dev/null +++ b/dom/indexedDB/test/unit/test_schema18upgrade.js @@ -0,0 +1,370 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const testName = "schema18upgrade"; + const testKeys = [ + -1 / 0, + -1.7e308, + -10000, + -2, + -1.5, + -1, + -1.00001e-200, + -1e-200, + 0, + 1e-200, + 1.00001e-200, + 1, + 2, + 10000, + 1.7e308, + 1 / 0, + new Date("1750-01-02"), + new Date("1800-12-31T12:34:56.001Z"), + new Date(-1000), + new Date(-10), + new Date(-1), + new Date(0), + new Date(1), + new Date(2), + new Date(1000), + new Date("1971-01-01"), + new Date("1971-01-01T01:01:01Z"), + new Date("1971-01-01T01:01:01.001Z"), + new Date("1971-01-01T01:01:01.01Z"), + new Date("1971-01-01T01:01:01.1Z"), + new Date("1980-02-02"), + new Date("3333-03-19T03:33:33.333Z"), + "", + "\x00", + "\x00\x00", + "\x00\x01", + "\x01", + "\x02", + "\x03", + "\x04", + "\x07", + "\x08", + "\x0F", + "\x10", + "\x1F", + "\x20", + "01234", + "\x3F", + "\x40", + "A", + "A\x00", + "A1", + "ZZZZ", + "a", + "a\x00", + "aa", + "azz", + "}", + "\x7E", + "\x7F", + "\x80", + "\xFF", + "\u0100", + "\u01FF", + "\u0200", + "\u03FF", + "\u0400", + "\u07FF", + "\u0800", + "\u0FFF", + "\u1000", + "\u1FFF", + "\u2000", + "\u3FFF", + "\u4000", + "\u7FFF", + "\u8000", + "\uD800", + "\uD800a", + "\uD800\uDC01", + "\uDBFF", + "\uDC00", + "\uDFFF\uD800", + "\uFFFE", + "\uFFFF", + "\uFFFF\x00", + "\uFFFFZZZ", + [], + [-1 / 0], + [-1], + [0], + [1], + [1, "a"], + [1, []], + [1, [""]], + [2, 3], + [2, 3.0000000000001], + [12, [[]]], + [12, [[[]]]], + [12, [[[""]]]], + [12, [[["foo"]]]], + [12, [[[[[3]]]]]], + [12, [[[[[[3]]]]]]], + [12, [[[[[[3], [[[[[4.2]]]]]]]]]]], + [new Date(-1)], + [new Date(1)], + [""], + ["", [[]]], + ["", [[[]]]], + ["abc"], + ["abc", "def"], + ["abc\x00"], + ["abc\x00", "\x00\x01"], + ["abc\x00", "\x00def"], + ["abc\x00\x00def"], + ["x", [[]]], + ["x", [[[]]]], + [[]], + [[], "foo"], + [[], []], + [[[]]], + [[[]], []], + [[[]], [[]]], + [[[]], [[1]]], + [[[]], [[[]]]], + [[[1]]], + [[[[]], []]], + ]; + const testString = + "abcdefghijklmnopqrstuvwxyz0123456789`~!@#$%^&*()-_+=,<.>/?\\|"; + + clearAllDatabases(continueToNextStepSync); + yield undefined; + + info("Installing profile"); + + installPackagedProfile(testName + "_profile"); + + info("Opening database with no version"); + + let request = indexedDB.open(testName); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + + is(db.version, 1, "Correct db version"); + + let transaction = db.transaction(testName); + transaction.oncomplete = grabEventAndContinueHandler; + + let objectStore = transaction.objectStore(testName); + let index = objectStore.index("uniqueIndex"); + + info("Starting 'uniqueIndex' cursor"); + + let keyIndex = 0; + index.openCursor().onsuccess = event => { + let cursor = event.target.result; + if (cursor) { + info( + "Comparing " + + JSON.stringify(cursor.primaryKey) + + " to " + + JSON.stringify(testKeys[cursor.key]) + + " [" + + cursor.key + + "]" + ); + is( + indexedDB.cmp(cursor.primaryKey, testKeys[cursor.key]), + 0, + "Keys compare equally via 'indexedDB.cmp'" + ); + is( + compareKeys(cursor.primaryKey, testKeys[cursor.key]), + true, + "Keys compare equally via 'compareKeys'" + ); + + let indexProperty = cursor.value.index; + is(Array.isArray(indexProperty), true, "index property is Array"); + is(indexProperty[0], cursor.key, "index property first item correct"); + is( + indexProperty[1], + cursor.key + 1, + "index property second item correct" + ); + + is(cursor.key, keyIndex, "Cursor key property is correct"); + + is(cursor.value.testString, testString, "Test string compared equally"); + + keyIndex++; + cursor.continue(); + } + }; + yield undefined; + + is(keyIndex, testKeys.length, "Saw all keys"); + + transaction = db.transaction(testName, "readwrite"); + transaction.oncomplete = grabEventAndContinueHandler; + + objectStore = transaction.objectStore(testName); + index = objectStore.index("index"); + + info("Getting all 'index' keys"); + + index.getAllKeys().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result.length, testKeys.length * 2, "Got all keys"); + + info("Starting objectStore cursor"); + + objectStore.openCursor().onsuccess = event => { + let cursor = event.target.result; + if (cursor) { + let value = cursor.value; + is(value.testString, testString, "Test string compared equally"); + + delete value.index; + cursor.update(value); + + cursor.continue(); + } else { + continueToNextStepSync(); + } + }; + yield undefined; + + info("Getting all 'index' keys"); + + index.getAllKeys().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result.length, 0, "Removed all keys"); + yield undefined; + + db.close(); + + info("Opening database with new version"); + + request = indexedDB.open(testName, 2); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + info("Deleting indexes"); + + objectStore = event.target.transaction.objectStore(testName); + objectStore.deleteIndex("index"); + objectStore.deleteIndex("uniqueIndex"); + + event = yield undefined; + + db = event.target.result; + + transaction = db.transaction(testName, "readwrite"); + transaction.oncomplete = grabEventAndContinueHandler; + + info("Starting objectStore cursor"); + + objectStore = transaction.objectStore(testName); + objectStore.openCursor().onsuccess = event => { + let cursor = event.target.result; + if (cursor) { + let value = cursor.value; + is(value.testString, testString, "Test string compared equally"); + + value.index = value.keyPath; + cursor.update(value); + + cursor.continue(); + } + }; + event = yield undefined; + + db.close(); + + info("Opening database with new version"); + + request = indexedDB.open(testName, 3); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + info("Creating indexes"); + + objectStore = event.target.transaction.objectStore(testName); + objectStore.createIndex("index", "index"); + + event = yield undefined; + + db = event.target.result; + + transaction = db.transaction(testName); + transaction.oncomplete = grabEventAndContinueHandler; + + objectStore = transaction.objectStore(testName); + index = objectStore.index("index"); + + info("Starting 'index' cursor"); + + keyIndex = 0; + index.openCursor().onsuccess = event => { + let cursor = event.target.result; + if (cursor) { + is( + indexedDB.cmp(cursor.primaryKey, testKeys[keyIndex]), + 0, + "Keys compare equally via 'indexedDB.cmp'" + ); + is( + compareKeys(cursor.primaryKey, testKeys[keyIndex]), + true, + "Keys compare equally via 'compareKeys'" + ); + is( + indexedDB.cmp(cursor.key, testKeys[keyIndex]), + 0, + "Keys compare equally via 'indexedDB.cmp'" + ); + is( + compareKeys(cursor.key, testKeys[keyIndex]), + true, + "Keys compare equally via 'compareKeys'" + ); + + let indexProperty = cursor.value.index; + is( + indexedDB.cmp(indexProperty, testKeys[keyIndex]), + 0, + "Keys compare equally via 'indexedDB.cmp'" + ); + is( + compareKeys(indexProperty, testKeys[keyIndex]), + true, + "Keys compare equally via 'compareKeys'" + ); + + is(cursor.value.testString, testString, "Test string compared equally"); + + keyIndex++; + cursor.continue(); + } + }; + yield undefined; + + is(keyIndex, testKeys.length, "Added all keys again"); + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_schema21upgrade.js b/dom/indexedDB/test/unit/test_schema21upgrade.js new file mode 100644 index 0000000000..c38e2fb08f --- /dev/null +++ b/dom/indexedDB/test/unit/test_schema21upgrade.js @@ -0,0 +1,370 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const testName = "schema21upgrade"; + const testKeys = [ + -1 / 0, + -1.7e308, + -10000, + -2, + -1.5, + -1, + -1.00001e-200, + -1e-200, + 0, + 1e-200, + 1.00001e-200, + 1, + 2, + 10000, + 1.7e308, + 1 / 0, + new Date("1750-01-02"), + new Date("1800-12-31T12:34:56.001Z"), + new Date(-1000), + new Date(-10), + new Date(-1), + new Date(0), + new Date(1), + new Date(2), + new Date(1000), + new Date("1971-01-01"), + new Date("1971-01-01T01:01:01Z"), + new Date("1971-01-01T01:01:01.001Z"), + new Date("1971-01-01T01:01:01.01Z"), + new Date("1971-01-01T01:01:01.1Z"), + new Date("1980-02-02"), + new Date("3333-03-19T03:33:33.333Z"), + "", + "\x00", + "\x00\x00", + "\x00\x01", + "\x01", + "\x02", + "\x03", + "\x04", + "\x07", + "\x08", + "\x0F", + "\x10", + "\x1F", + "\x20", + "01234", + "\x3F", + "\x40", + "A", + "A\x00", + "A1", + "ZZZZ", + "a", + "a\x00", + "aa", + "azz", + "}", + "\x7E", + "\x7F", + "\x80", + "\xFF", + "\u0100", + "\u01FF", + "\u0200", + "\u03FF", + "\u0400", + "\u07FF", + "\u0800", + "\u0FFF", + "\u1000", + "\u1FFF", + "\u2000", + "\u3FFF", + "\u4000", + "\u7FFF", + "\u8000", + "\uD800", + "\uD800a", + "\uD800\uDC01", + "\uDBFF", + "\uDC00", + "\uDFFF\uD800", + "\uFFFE", + "\uFFFF", + "\uFFFF\x00", + "\uFFFFZZZ", + [], + [-1 / 0], + [-1], + [0], + [1], + [1, "a"], + [1, []], + [1, [""]], + [2, 3], + [2, 3.0000000000001], + [12, [[]]], + [12, [[[]]]], + [12, [[[""]]]], + [12, [[["foo"]]]], + [12, [[[[[3]]]]]], + [12, [[[[[[3]]]]]]], + [12, [[[[[[3], [[[[[4.2]]]]]]]]]]], + [new Date(-1)], + [new Date(1)], + [""], + ["", [[]]], + ["", [[[]]]], + ["abc"], + ["abc", "def"], + ["abc\x00"], + ["abc\x00", "\x00\x01"], + ["abc\x00", "\x00def"], + ["abc\x00\x00def"], + ["x", [[]]], + ["x", [[[]]]], + [[]], + [[], "foo"], + [[], []], + [[[]]], + [[[]], []], + [[[]], [[]]], + [[[]], [[1]]], + [[[]], [[[]]]], + [[[1]]], + [[[[]], []]], + ]; + const testString = + "abcdefghijklmnopqrstuvwxyz0123456789`~!@#$%^&*()-_+=,<.>/?\\|"; + + clearAllDatabases(continueToNextStepSync); + yield undefined; + + info("Installing profile"); + + installPackagedProfile(testName + "_profile"); + + info("Opening database with no version"); + + let request = indexedDB.open(testName); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + + is(db.version, 1, "Correct db version"); + + let transaction = db.transaction(testName); + transaction.oncomplete = grabEventAndContinueHandler; + + let objectStore = transaction.objectStore(testName); + let index = objectStore.index("uniqueIndex"); + + info("Starting 'uniqueIndex' cursor"); + + let keyIndex = 0; + index.openCursor().onsuccess = event => { + let cursor = event.target.result; + if (cursor) { + info( + "Comparing " + + JSON.stringify(cursor.primaryKey) + + " to " + + JSON.stringify(testKeys[cursor.key]) + + " [" + + cursor.key + + "]" + ); + is( + indexedDB.cmp(cursor.primaryKey, testKeys[cursor.key]), + 0, + "Keys compare equally via 'indexedDB.cmp'" + ); + is( + compareKeys(cursor.primaryKey, testKeys[cursor.key]), + true, + "Keys compare equally via 'compareKeys'" + ); + + let indexProperty = cursor.value.index; + is(Array.isArray(indexProperty), true, "index property is Array"); + is(indexProperty[0], cursor.key, "index property first item correct"); + is( + indexProperty[1], + cursor.key + 1, + "index property second item correct" + ); + + is(cursor.key, keyIndex, "Cursor key property is correct"); + + is(cursor.value.testString, testString, "Test string compared equally"); + + keyIndex++; + cursor.continue(); + } + }; + yield undefined; + + is(keyIndex, testKeys.length, "Saw all keys"); + + transaction = db.transaction(testName, "readwrite"); + transaction.oncomplete = grabEventAndContinueHandler; + + objectStore = transaction.objectStore(testName); + index = objectStore.index("index"); + + info("Getting all 'index' keys"); + + index.getAllKeys().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result.length, testKeys.length * 2, "Got all keys"); + + info("Starting objectStore cursor"); + + objectStore.openCursor().onsuccess = event => { + let cursor = event.target.result; + if (cursor) { + let value = cursor.value; + is(value.testString, testString, "Test string compared equally"); + + delete value.index; + cursor.update(value); + + cursor.continue(); + } else { + continueToNextStepSync(); + } + }; + yield undefined; + + info("Getting all 'index' keys"); + + index.getAllKeys().onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result.length, 0, "Removed all keys"); + yield undefined; + + db.close(); + + info("Opening database with new version"); + + request = indexedDB.open(testName, 2); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + info("Deleting indexes"); + + objectStore = event.target.transaction.objectStore(testName); + objectStore.deleteIndex("index"); + objectStore.deleteIndex("uniqueIndex"); + + event = yield undefined; + + db = event.target.result; + + transaction = db.transaction(testName, "readwrite"); + transaction.oncomplete = grabEventAndContinueHandler; + + info("Starting objectStore cursor"); + + objectStore = transaction.objectStore(testName); + objectStore.openCursor().onsuccess = event => { + let cursor = event.target.result; + if (cursor) { + let value = cursor.value; + is(value.testString, testString, "Test string compared equally"); + + value.index = value.keyPath; + cursor.update(value); + + cursor.continue(); + } + }; + event = yield undefined; + + db.close(); + + info("Opening database with new version"); + + request = indexedDB.open(testName, 3); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + info("Creating indexes"); + + objectStore = event.target.transaction.objectStore(testName); + objectStore.createIndex("index", "index"); + + event = yield undefined; + + db = event.target.result; + + transaction = db.transaction(testName); + transaction.oncomplete = grabEventAndContinueHandler; + + objectStore = transaction.objectStore(testName); + index = objectStore.index("index"); + + info("Starting 'index' cursor"); + + keyIndex = 0; + index.openCursor().onsuccess = event => { + let cursor = event.target.result; + if (cursor) { + is( + indexedDB.cmp(cursor.primaryKey, testKeys[keyIndex]), + 0, + "Keys compare equally via 'indexedDB.cmp'" + ); + is( + compareKeys(cursor.primaryKey, testKeys[keyIndex]), + true, + "Keys compare equally via 'compareKeys'" + ); + is( + indexedDB.cmp(cursor.key, testKeys[keyIndex]), + 0, + "Keys compare equally via 'indexedDB.cmp'" + ); + is( + compareKeys(cursor.key, testKeys[keyIndex]), + true, + "Keys compare equally via 'compareKeys'" + ); + + let indexProperty = cursor.value.index; + is( + indexedDB.cmp(indexProperty, testKeys[keyIndex]), + 0, + "Keys compare equally via 'indexedDB.cmp'" + ); + is( + compareKeys(indexProperty, testKeys[keyIndex]), + true, + "Keys compare equally via 'compareKeys'" + ); + + is(cursor.value.testString, testString, "Test string compared equally"); + + keyIndex++; + cursor.continue(); + } + }; + yield undefined; + + is(keyIndex, testKeys.length, "Added all keys again"); + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_schema23upgrade.js b/dom/indexedDB/test/unit/test_schema23upgrade.js new file mode 100644 index 0000000000..fdd1c4c51b --- /dev/null +++ b/dom/indexedDB/test/unit/test_schema23upgrade.js @@ -0,0 +1,53 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const openParams = [ + // This one lives in storage/default/http+++www.mozilla.org + { url: "http://www.mozilla.org", dbName: "dbB", dbVersion: 1 }, + ]; + + clearAllDatabases(continueToNextStepSync); + yield undefined; + + installPackagedProfile("schema23upgrade_profile"); + + for (let params of openParams) { + let request = indexedDB.openForPrincipal( + getPrincipal(params.url), + params.dbName, + params.dbVersion + ); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + is(event.type, "success", "Correct event type"); + } + + resetAllDatabases(continueToNextStepSync); + yield undefined; + + for (let params of openParams) { + let request = indexedDB.openForPrincipal( + getPrincipal(params.url), + params.dbName, + params.dbVersion + ); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + is(event.type, "success", "Correct event type"); + } + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_setVersion.js b/dom/indexedDB/test/unit/test_setVersion.js new file mode 100644 index 0000000000..f1b50e7bb1 --- /dev/null +++ b/dom/indexedDB/test/unit/test_setVersion.js @@ -0,0 +1,46 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + db.close(); + + // Check default state. + is(db.version, 1, "Correct default version for a new database."); + + const versions = [7, 42]; + + for (let i = 0; i < versions.length; i++) { + let version = versions[i]; + + let request = indexedDB.open(name, version); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + + is(db.version, version, "Database version number updated correctly"); + is(event.target.transaction.mode, "versionchange", "Correct mode"); + + // Wait for success + yield undefined; + + db.close(); + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_setVersion_abort.js b/dom/indexedDB/test/unit/test_setVersion_abort.js new file mode 100644 index 0000000000..fe5d63fea2 --- /dev/null +++ b/dom/indexedDB/test/unit/test_setVersion_abort.js @@ -0,0 +1,96 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onsuccess = unexpectedSuccessHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + + let objectStore = db.createObjectStore("foo"); + objectStore.createIndex("bar", "baz"); + + is(db.version, 1, "Correct version"); + is(db.objectStoreNames.length, 1, "Correct objectStoreNames length"); + is(objectStore.indexNames.length, 1, "Correct indexNames length"); + + let transaction = event.target.transaction; + is(transaction.mode, "versionchange", "Correct transaction mode"); + transaction.oncomplete = unexpectedSuccessHandler; + transaction.onabort = grabEventAndContinueHandler; + transaction.abort(); + + is(db.version, 0, "Correct version"); + is(db.objectStoreNames.length, 0, "Correct objectStoreNames length"); + is(objectStore.indexNames.length, 0, "Correct indexNames length"); + + // Test that the db is actually closed. + try { + db.transaction(""); + ok(false, "Expect an exception"); + } catch (e) { + ok(true, "Expect an exception"); + is(e.name, "InvalidStateError", "Expect an InvalidStateError"); + } + + event = yield undefined; + is(event.type, "abort", "Got transaction abort event"); + is(event.target, transaction, "Right target"); + + is(db.version, 0, "Correct version"); + is(db.objectStoreNames.length, 0, "Correct objectStoreNames length"); + is(objectStore.indexNames.length, 0, "Correct indexNames length"); + + request.onerror = grabEventAndContinueHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + + event = yield undefined; + + is(event.type, "error", "Got request error event"); + is(event.target, request, "Right target"); + is(event.target.transaction, null, "No transaction"); + + event.preventDefault(); + + request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onsuccess = unexpectedSuccessHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + event = yield undefined; + + is(event.type, "upgradeneeded", "Got upgradeneeded event"); + + let db2 = event.target.result; + + isnot(db, db2, "Should give a different db instance"); + is(db2.version, 1, "Correct version"); + is(db2.objectStoreNames.length, 0, "Correct objectStoreNames length"); + + let objectStore2 = db2.createObjectStore("foo"); + objectStore2.createIndex("bar", "baz"); + + request.onsuccess = grabEventAndContinueHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + event = yield undefined; + + is(event.target.result, db2, "Correct target"); + is(event.type, "success", "Got success event"); + is(db2.version, 1, "Correct version"); + is(db2.objectStoreNames.length, 1, "Correct objectStoreNames length"); + is(objectStore2.indexNames.length, 1, "Correct indexNames length"); + is(db.version, 0, "Correct version still"); + is(db.objectStoreNames.length, 0, "Correct objectStoreNames length still"); + is(objectStore.indexNames.length, 0, "Correct indexNames length still"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_setVersion_events.js b/dom/indexedDB/test/unit/test_setVersion_events.js new file mode 100644 index 0000000000..d80edcca31 --- /dev/null +++ b/dom/indexedDB/test/unit/test_setVersion_events.js @@ -0,0 +1,171 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + // Open a datbase for the first time. + let request = indexedDB.open(name, 1); + + // Sanity checks + ok(request instanceof IDBRequest, "Request should be an IDBRequest"); + ok( + request instanceof IDBOpenDBRequest, + "Request should be an IDBOpenDBRequest" + ); + ok(request instanceof EventTarget, "Request should be an EventTarget"); + is(request.source, null, "Request should have no source"); + try { + request.result; + ok(false, "Getter should have thrown!"); + } catch (e) { + if (e.result == 0x8053000b /* NS_ERROR_DOM_INVALID_STATE_ERR */) { + ok(true, "Getter threw the right exception"); + } else { + throw e; + } + } + + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let versionChangeEventCount = 0; + let db1, db2, db3; + + db1 = event.target.result; + db1.addEventListener("versionchange", function (event) { + ok(true, "Got version change event"); + ok(event instanceof IDBVersionChangeEvent, "Event is of the right type"); + is("source" in event.target, false, "Correct source"); + is(event.target, db1, "Correct target"); + is(event.target.version, 1, "Correct db version"); + is(event.oldVersion, 1, "Correct event oldVersion"); + is(event.newVersion, 2, "Correct event newVersion"); + is(versionChangeEventCount++, 0, "Correct count"); + db1.close(); + }); + + // Open the database again and trigger an upgrade that should succeed + request = indexedDB.open(name, 2); + request.onerror = errorHandler; + request.onsuccess = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onblocked = errorHandler; + + event = yield undefined; + + // Test the upgradeneeded event. + ok(event instanceof IDBVersionChangeEvent, "Event is of the right type"); + ok(event.target.result instanceof IDBDatabase, "Good result"); + db2 = event.target.result; + is(event.target.transaction.mode, "versionchange", "Correct mode"); + is(db2.version, 2, "Correct db version"); + is(event.oldVersion, 1, "Correct event oldVersion"); + is(event.newVersion, 2, "Correct event newVersion"); + + request.onupgradeneeded = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + db2.addEventListener("versionchange", function (event) { + ok(true, "Got version change event"); + ok(event instanceof IDBVersionChangeEvent, "Event is of the right type"); + is("source" in event.target, false, "Correct source"); + is(event.target, db2, "Correct target"); + is(event.target.version, 2, "Correct db version"); + is(event.oldVersion, 2, "Correct event oldVersion"); + is(event.newVersion, 3, "Correct event newVersion"); + is(versionChangeEventCount++, 1, "Correct count"); + }); + + // Test opening the existing version again + request = indexedDB.open(name, 2); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + request.onblocked = errorHandler; + + event = yield undefined; + + db3 = event.target.result; + + // Test an upgrade that should fail + request = indexedDB.open(name, 3); + request.onerror = errorHandler; + request.onsuccess = errorHandler; + request.onupgradeneeded = errorHandler; + request.onblocked = grabEventAndContinueHandler; + + event = yield undefined; + ok(true, "Got version change blocked event"); + ok(event instanceof IDBVersionChangeEvent, "Event is of the right type"); + is(event.target.source, null, "Correct source"); + is(event.target.transaction, null, "Correct transaction"); + is(event.target, request, "Correct target"); + is(db3.version, 2, "Correct db version"); + is(event.oldVersion, 2, "Correct event oldVersion"); + is(event.newVersion, 3, "Correct event newVersion"); + versionChangeEventCount++; + db2.close(); + db3.close(); + + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + event = yield undefined; + + db3 = event.target.result; + db3.close(); + + // Test another upgrade that should succeed. + request = indexedDB.open(name, 4); + request.onerror = errorHandler; + request.onsuccess = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onblocked = errorHandler; + + event = yield undefined; + + ok(event instanceof IDBVersionChangeEvent, "Event is of the right type"); + ok(event.target.result instanceof IDBDatabase, "Good result"); + is(event.target.transaction.mode, "versionchange", "Correct mode"); + is(event.oldVersion, 3, "Correct event oldVersion"); + is(event.newVersion, 4, "Correct event newVersion"); + + request.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + ok(event.target.result instanceof IDBDatabase, "Expect a database here"); + is(event.target.result.version, 4, "Right version"); + is(db3.version, 3, "After closing the version should not change!"); + is(db2.version, 2, "After closing the version should not change!"); + is(db1.version, 1, "After closing the version should not change!"); + + is(versionChangeEventCount, 3, "Saw all expected events"); + + event = new IDBVersionChangeEvent("versionchange"); + ok(event, "Should be able to create an event with just passing in the type"); + event = new IDBVersionChangeEvent("versionchange", { oldVersion: 1 }); + ok(event, "Should be able to create an event with just the old version"); + is(event.oldVersion, 1, "Correct old version"); + is(event.newVersion, null, "Correct new version"); + event = new IDBVersionChangeEvent("versionchange", { newVersion: 1 }); + ok(event, "Should be able to create an event with just the new version"); + is(event.oldVersion, 0, "Correct old version"); + is(event.newVersion, 1, "Correct new version"); + event = new IDBVersionChangeEvent("versionchange", { + oldVersion: 1, + newVersion: 2, + }); + ok(event, "Should be able to create an event with both versions"); + is(event.oldVersion, 1, "Correct old version"); + is(event.newVersion, 2, "Correct new version"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_setVersion_exclusion.js b/dom/indexedDB/test/unit/test_setVersion_exclusion.js new file mode 100644 index 0000000000..a084375fa0 --- /dev/null +++ b/dom/indexedDB/test/unit/test_setVersion_exclusion.js @@ -0,0 +1,97 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + + let request2 = indexedDB.open(name, 2); + request2.onerror = errorHandler; + request2.onupgradeneeded = unexpectedSuccessHandler; + request2.onsuccess = unexpectedSuccessHandler; + + let event = yield undefined; + is(event.type, "upgradeneeded", "Expect an upgradeneeded event"); + is(event.target, request, "Event should be fired on the request"); + ok(event.target.result instanceof IDBDatabase, "Expect a database here"); + + let db = event.target.result; + is(db.version, 1, "Database has correct version"); + + db.onupgradeneeded = function () { + ok( + false, + "our ongoing VERSION_CHANGE transaction should exclude any others!" + ); + }; + + db.createObjectStore("foo"); + + try { + db.transaction("foo"); + ok(false, "Transactions should be disallowed now!"); + } catch (e) { + ok(e instanceof DOMException, "Expect a DOMException"); + is(e.name, "InvalidStateError", "Expect an InvalidStateError"); + is(e.code, DOMException.INVALID_STATE_ERR, "Expect an INVALID_STATE_ERR"); + } + + request.onupgradeneeded = unexpectedSuccessHandler; + request.transaction.oncomplete = grabEventAndContinueHandler; + + event = yield undefined; + is(event.type, "complete", "Got complete event"); + + try { + db.transaction("foo"); + ok(true, "Transactions should be allowed now!"); + } catch (e) { + ok(false, "Transactions should be allowed now!"); + } + + request.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + is(event.type, "success", "Expect a success event"); + is(event.target.result, db, "Same database"); + + db.onversionchange = function () { + ok(true, "next setVersion was unblocked appropriately"); + db.close(); + }; + + try { + db.transaction("foo"); + ok(true, "Transactions should be allowed now!"); + } catch (e) { + ok(false, "Transactions should be allowed now!"); + } + + request.onsuccess = unexpectedSuccessHandler; + request2.onupgradeneeded = grabEventAndContinueHandler; + + event = yield undefined; + is(event.type, "upgradeneeded", "Expect an upgradeneeded event"); + + db = event.target.result; + is(db.version, 2, "Database has correct version"); + + request2.onupgradeneeded = unexpectedSuccessHandler; + request2.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + is(event.type, "success", "Expect a success event"); + is(event.target.result, db, "Same database"); + is(db.version, 2, "Database has correct version"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_setVersion_throw.js b/dom/indexedDB/test/unit/test_setVersion_throw.js new file mode 100644 index 0000000000..2706c2c2a4 --- /dev/null +++ b/dom/indexedDB/test/unit/test_setVersion_throw.js @@ -0,0 +1,54 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "test_setVersion_throw"; + + // This test requires two databases. The first needs to be a low version + // number that gets closed when a second higher version number database is + // created. Then the upgradeneeded event for the second database throws an + // exception and triggers an abort/close. + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + request.onupgradeneeded = function (event) { + info("Got upgradeneeded event for db 1"); + }; + let event = yield undefined; + + is(event.type, "success", "Got success event for db 1"); + + let db = event.target.result; + db.onversionchange = function (event) { + info("Got versionchange event for db 1"); + event.target.close(); + }; + + executeSoon(continueToNextStepSync); + yield undefined; + + request = indexedDB.open(name, 2); + request.onerror = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + request.onupgradeneeded = function (event) { + info("Got upgradeneeded event for db 2"); + expectUncaughtException(true); + // eslint-disable-next-line no-undef + trigger_js_exception_by_calling_a_nonexistent_function(); + }; + event = yield undefined; + + event.preventDefault(); + + is(event.type, "error", "Got an error event for db 2"); + ok(event.target.error instanceof DOMException, "Request has a DOMException"); + is(event.target.error.name, "AbortError", "Request has AbortError"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_snappyUpgrade.js b/dom/indexedDB/test/unit/test_snappyUpgrade.js new file mode 100644 index 0000000000..5d73b3c3c0 --- /dev/null +++ b/dom/indexedDB/test/unit/test_snappyUpgrade.js @@ -0,0 +1,47 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = "test_snappyUpgrade.js"; + const objectStoreName = "test"; + const testString = + "Lorem ipsum his ponderum delicatissimi ne, at noster dolores urbanitas pro, cibo elaboraret no his. Ea dicunt maiorum usu. Ad appareat facilisis mediocritatem eos. Tale graeci mentitum in eos, hinc insolens at nam. Graecis nominavi aliquyam eu vix. Id solet assentior sadipscing pro. Et per atqui graecis, usu quot viris repudiandae ei, mollis evertitur an nam. At nam dolor ignota, liber labore omnesque ea mei, has movet voluptaria in. Vel an impetus omittantur. Vim movet option salutandi ex, ne mei ignota corrumpit. Mucius comprehensam id per. Est ea putant maiestatis."; + + info("Installing profile"); + + clearAllDatabases(continueToNextStepSync); + yield undefined; + + installPackagedProfile("snappyUpgrade_profile"); + + info("Opening database"); + + let request = indexedDB.open(name); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = continueToNextStepSync; + yield undefined; + + // success + let db = request.result; + db.onerror = errorHandler; + + info("Getting string"); + + request = db + .transaction([objectStoreName]) + .objectStore(objectStoreName) + .get(1); + request.onsuccess = continueToNextStepSync; + yield undefined; + + is(request.result, testString); + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_storagePersistentUpgrade.js b/dom/indexedDB/test/unit/test_storagePersistentUpgrade.js new file mode 100644 index 0000000000..ebde969344 --- /dev/null +++ b/dom/indexedDB/test/unit/test_storagePersistentUpgrade.js @@ -0,0 +1,53 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const openParams = [ + // This one lives in storage/default/http+++www.mozilla.org + { url: "http://www.mozilla.org", dbName: "dbB", dbVersion: 1 }, + ]; + + clearAllDatabases(continueToNextStepSync); + yield undefined; + + installPackagedProfile("storagePersistentUpgrade_profile"); + + for (let params of openParams) { + let request = indexedDB.openForPrincipal( + getPrincipal(params.url), + params.dbName, + params.dbVersion + ); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + is(event.type, "success", "Correct event type"); + } + + resetAllDatabases(continueToNextStepSync); + yield undefined; + + for (let params of openParams) { + let request = indexedDB.openForPrincipal( + getPrincipal(params.url), + params.dbName, + params.dbVersion + ); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + is(event.type, "success", "Correct event type"); + } + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_storage_manager_estimate.js b/dom/indexedDB/test/unit/test_storage_manager_estimate.js new file mode 100644 index 0000000000..286e70de96 --- /dev/null +++ b/dom/indexedDB/test/unit/test_storage_manager_estimate.js @@ -0,0 +1,89 @@ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window + ? window.location.pathname + : "test_storage_manager_estimate.js"; + const objectStoreName = "storagesManager"; + const arraySize = 1e6; + + ok("estimate" in navigator.storage, "Has estimate function"); + is(typeof navigator.storage.estimate, "function", "estimate is function"); + ok( + navigator.storage.estimate() instanceof Promise, + "estimate() method exists and returns a Promise" + ); + + navigator.storage.estimate().then(estimation => { + testGenerator.next(estimation.usage); + }); + + let before = yield undefined; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = continueToNextStep; + let event = yield undefined; + + let db = event.target.result; + db.onerror = errorHandler; + + let objectStore = db.createObjectStore(objectStoreName, {}); + yield undefined; + + navigator.storage.estimate().then(estimation => { + testGenerator.next(estimation.usage); + }); + let usageAfterCreate = yield undefined; + ok( + usageAfterCreate > before, + "estimated usage must increase after createObjectStore" + ); + + let txn = db.transaction(objectStoreName, "readwrite"); + objectStore = txn.objectStore(objectStoreName); + objectStore.put(new Uint8Array(arraySize), "k"); + txn.oncomplete = continueToNextStep; + txn.onabort = errorHandler; + txn.onerror = errorHandler; + event = yield undefined; + + navigator.storage.estimate().then(estimation => { + testGenerator.next(estimation.usage); + }); + let usageAfterPut = yield undefined; + ok( + usageAfterPut > usageAfterCreate, + "estimated usage must increase after putting large object" + ); + db.close(); + + finishTest(); +} + +/* exported setup */ +async function setup(isXOrigin) { + // Bug 1746646: Make mochitests work with TCP enabled (cookieBehavior = 5) + // Acquire storage access permission here so that the iframe has + // first-party access to the storage estimate. Without this, it is + // isolated and this test will always fail + if (isXOrigin) { + await SpecialPowers.pushPrefEnv({ + set: [ + [ + "privacy.partition.always_partition_third_party_non_cookie_storage", + false, + ], + ], + }); + SpecialPowers.wrap(document).notifyUserGestureActivation(); + await SpecialPowers.addPermission( + "storageAccessAPI", + true, + window.location.href + ); + await SpecialPowers.wrap(document).requestStorageAccess(); + } + runTest(); +} diff --git a/dom/indexedDB/test/unit/test_success_events_after_abort.js b/dom/indexedDB/test/unit/test_success_events_after_abort.js new file mode 100644 index 0000000000..034e8ff658 --- /dev/null +++ b/dom/indexedDB/test/unit/test_success_events_after_abort.js @@ -0,0 +1,55 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + let request = indexedDB.open( + this.window ? window.location.pathname : "Splendid Test", + 1 + ); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + + event.target.onsuccess = continueToNextStep; + + let objectStore = db.createObjectStore("foo"); + objectStore.add({}, 1).onerror = errorHandler; + + yield undefined; + + objectStore = db.transaction("foo").objectStore("foo"); + + let transaction = objectStore.transaction; + transaction.oncomplete = unexpectedSuccessHandler; + transaction.onabort = grabEventAndContinueHandler; + + let sawError = false; + + request = objectStore.get(1); + request.onsuccess = unexpectedSuccessHandler; + request.onerror = function (event) { + is(event.target.error.name, "AbortError", "Good error"); + sawError = true; + event.preventDefault(); + }; + + transaction.abort(); + + event = yield undefined; + + is(event.type, "abort", "Got abort event"); + is(sawError, true, "Saw get() error"); + if (this.window) { + // Make sure the success event isn't queued somehow. + SpecialPowers.Services.tm.spinEventLoopUntilEmpty(); + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_table_locks.js b/dom/indexedDB/test/unit/test_table_locks.js new file mode 100644 index 0000000000..e1f3b5e7d6 --- /dev/null +++ b/dom/indexedDB/test/unit/test_table_locks.js @@ -0,0 +1,123 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +const dbName = "window" in this ? window.location.pathname : "test"; +const dbVersion = 1; +const objName1 = "o1"; +const objName2 = "o2"; +const idxName1 = "i1"; +const idxName2 = "i2"; +const idxKeyPathProp = "idx"; +const objDataProp = "data"; +const objData = "1234567890"; +const objDataCount = 5; +const loopCount = 100; + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + let req = indexedDB.open(dbName, dbVersion); + req.onerror = errorHandler; + req.onupgradeneeded = grabEventAndContinueHandler; + req.onsuccess = grabEventAndContinueHandler; + + let event = yield undefined; + + is(event.type, "upgradeneeded", "Got upgradeneeded event"); + + let db = event.target.result; + + let objectStore1 = db.createObjectStore(objName1); + objectStore1.createIndex(idxName1, idxKeyPathProp); + + let objectStore2 = db.createObjectStore(objName2); + objectStore2.createIndex(idxName2, idxKeyPathProp); + + for (let i = 0; i < objDataCount; i++) { + var data = {}; + data[objDataProp] = objData; + data[idxKeyPathProp] = objDataCount - i - 1; + + objectStore1.add(data, i); + objectStore2.add(data, i); + } + + event = yield undefined; + + is(event.type, "success", "Got success event"); + + doReadOnlyTransaction(db, 0, loopCount); + doReadWriteTransaction(db, 0, loopCount); + + // Wait for readonly and readwrite transaction loops to complete. + yield undefined; + yield undefined; + + finishTest(); +} + +function doReadOnlyTransaction(db, key, remaining) { + if (!remaining) { + info("Finished all readonly transactions"); + continueToNextStep(); + return; + } + + info( + "Starting readonly transaction for key " + + key + + ", " + + remaining + + " loops left" + ); + + let objectStore = db.transaction(objName1, "readonly").objectStore(objName1); + let index = objectStore.index(idxName1); + + index.openKeyCursor(key, "prev").onsuccess = function (event) { + let cursor = event.target.result; + ok(cursor, "Got readonly cursor"); + + objectStore.get(cursor.primaryKey).onsuccess = function (event) { + if (++key == objDataCount) { + key = 0; + } + doReadOnlyTransaction(db, key, remaining - 1); + }; + }; +} + +function doReadWriteTransaction(db, key, remaining) { + if (!remaining) { + info("Finished all readwrite transactions"); + continueToNextStep(); + return; + } + + info( + "Starting readwrite transaction for key " + + key + + ", " + + remaining + + " loops left" + ); + + let objectStore = db.transaction(objName2, "readwrite").objectStore(objName2); + objectStore.openCursor(key).onsuccess = function (event) { + let cursor = event.target.result; + ok(cursor, "Got readwrite cursor"); + + let value = cursor.value; + value[idxKeyPathProp]++; + + cursor.update(value).onsuccess = function (event) { + if (++key == objDataCount) { + key = 0; + } + doReadWriteTransaction(db, key, remaining - 1); + }; + }; +} diff --git a/dom/indexedDB/test/unit/test_table_rollback.js b/dom/indexedDB/test/unit/test_table_rollback.js new file mode 100644 index 0000000000..07262db16c --- /dev/null +++ b/dom/indexedDB/test/unit/test_table_rollback.js @@ -0,0 +1,118 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const dbName = "window" in this ? window.location.pathname : "test"; + const objName1 = "foo"; + const objName2 = "bar"; + const data1 = "1234567890"; + const data2 = "0987654321"; + const dataCount = 500; + + let request = indexedDB.open(dbName, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + + let event = yield undefined; + + is(event.type, "upgradeneeded", "Got upgradeneeded"); + + request.onupgradeneeded = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + let db = request.result; + + let objectStore1 = db.createObjectStore(objName1, { autoIncrement: true }); + let objectStore2 = db.createObjectStore(objName2, { autoIncrement: true }); + + info("Created object stores, adding data"); + + for (let i = 0; i < dataCount; i++) { + objectStore1.add(data1); + objectStore2.add(data2); + } + + info("Done adding data"); + + event = yield undefined; + + is(event.type, "success", "Got success"); + + let readResult = null; + let readError = null; + let writeAborted = false; + + info("Creating readwrite transaction"); + + objectStore1 = db.transaction(objName1, "readwrite").objectStore(objName1); + objectStore1.openCursor().onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + let cursor = event.target.result; + is(cursor.value, data1, "Got correct data for readwrite transaction"); + + info("Modifying object store on readwrite transaction"); + + cursor.update(data2); + cursor.continue(); + + event = yield undefined; + + info( + "Done modifying object store on readwrite transaction, creating " + + "readonly transaction" + ); + + objectStore2 = db.transaction(objName2, "readonly").objectStore(objName2); + request = objectStore2.getAll(); + request.onsuccess = function (event) { + readResult = event.target.result; + is( + readResult.length, + dataCount, + "Got correct number of results on readonly transaction" + ); + for (let i = 0; i < readResult.length; i++) { + is(readResult[i], data2, "Got correct data for readonly transaction"); + } + if (writeAborted) { + continueToNextStep(); + } + }; + request.onerror = function (event) { + readResult = null; + readError = event.target.error; + + ok(false, "Got read error: " + readError.name); + event.preventDefault(); + + if (writeAborted) { + continueToNextStep(); + } + }; + + cursor = event.target.result; + is(cursor.value, data1, "Got correct data for readwrite transaction"); + + info("Aborting readwrite transaction"); + + cursor.source.transaction.abort(); + writeAborted = true; + + if (!readError && !readResult) { + info("Waiting for readonly transaction to complete"); + yield undefined; + } + + ok(readResult, "Got result from readonly transaction"); + is(readError, null, "No read error"); + is(writeAborted, true, "Aborted readwrite transaction"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_temporary_storage.js b/dom/indexedDB/test/unit/test_temporary_storage.js new file mode 100644 index 0000000000..4853ebbd14 --- /dev/null +++ b/dom/indexedDB/test/unit/test_temporary_storage.js @@ -0,0 +1,279 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ +/* eslint-disable mozilla/no-arbitrary-setTimeout */ + +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window + ? window.location.pathname + : "test_temporary_storage.js"; + const finalVersion = 2; + + const tempStorageLimitKB = 1024; + const checkpointSleepTimeSec = 5; + + function getSpec(index) { + return "http://foo" + index + ".com"; + } + + for (let temporary of [true, false]) { + info("Testing '" + (temporary ? "temporary" : "default") + "' storage"); + + setTemporaryStorageLimit(tempStorageLimitKB); + + clearAllDatabases(continueToNextStepSync); + yield undefined; + + info("Stage 1 - Creating empty databases until we reach the quota limit"); + + let databases = []; + let options = { version: finalVersion }; + if (temporary) { + options.storage = "temporary"; + } + + while (true) { + let spec = getSpec(databases.length); + + info("Opening database for " + spec + " with version " + options.version); + + let gotUpgradeIncomplete = false; + let gotUpgradeComplete = false; + + let request = indexedDB.openForPrincipal( + getPrincipal(spec), + name, + options + ); + request.onerror = function (event) { + is( + request.error.name, + gotUpgradeIncomplete ? "AbortError" : "QuotaExceededError", + "Reached quota limit" + ); + event.preventDefault(); + testGenerator.next(false); + }; + request.onupgradeneeded = function (event) { + event.target.transaction.onabort = function (e) { + gotUpgradeIncomplete = true; + is(e.target.error.name, "QuotaExceededError", "Reached quota limit"); + }; + event.target.transaction.oncomplete = function () { + gotUpgradeComplete = true; + }; + }; + request.onsuccess = function (event) { + let db = event.target.result; + is(db.version, finalVersion, "Correct version " + finalVersion); + databases.push(db); + testGenerator.next(true); + }; + + let shouldContinue = yield undefined; + if (shouldContinue) { + is(gotUpgradeComplete, true, "Got upgradeneeded event"); + ok(true, "Got success event"); + } else { + break; + } + } + + while (true) { + info( + "Sleeping for " + + checkpointSleepTimeSec + + " seconds to let all " + + "checkpoints finish so that we know we have reached quota limit" + ); + setTimeout(continueToNextStepSync, checkpointSleepTimeSec * 1000); + yield undefined; + + let spec = getSpec(databases.length); + + info("Opening database for " + spec + " with version " + options.version); + + let gotUpgradeIncomplete = false; + let gotUpgradeComplete = false; + + let request = indexedDB.openForPrincipal( + getPrincipal(spec), + name, + options + ); + request.onerror = function (event) { + is( + request.error.name, + gotUpgradeIncomplete ? "AbortError" : "QuotaExceededError", + "Reached quota limit" + ); + event.preventDefault(); + testGenerator.next(false); + }; + request.onupgradeneeded = function (event) { + event.target.transaction.onabort = function (e) { + gotUpgradeIncomplete = true; + is(e.target.error.name, "QuotaExceededError", "Reached quota limit"); + }; + event.target.transaction.oncomplete = function () { + gotUpgradeComplete = true; + }; + }; + request.onsuccess = function (event) { + let db = event.target.result; + is(db.version, finalVersion, "Correct version " + finalVersion); + databases.push(db); + testGenerator.next(true); + }; + + let shouldContinue = yield undefined; + if (shouldContinue) { + is(gotUpgradeComplete, true, "Got upgradeneeded event"); + ok(true, "Got success event"); + } else { + break; + } + } + + let databaseCount = databases.length; + info("Created " + databaseCount + " databases before quota limit reached"); + + info( + "Stage 2 - " + + "Closing all databases and then attempting to create one more, then " + + "verifying that the oldest origin was cleared" + ); + + for (let i = 0; i < databases.length; i++) { + info("Closing database for " + getSpec(i)); + databases[i].close(); + + // Timer resolution on Windows is low so wait for 40ms just to be safe. + setTimeout(continueToNextStepSync, 40); + yield undefined; + } + databases = null; + + let spec = getSpec(databaseCount); + info("Opening database for " + spec + " with version " + options.version); + + let request = indexedDB.openForPrincipal(getPrincipal(spec), name, options); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + let event = yield undefined; + + is(event.type, "upgradeneeded", "Got upgradeneeded event"); + + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.type, "success", "Got success event"); + + let db = event.target.result; + is(db.version, finalVersion, "Correct version " + finalVersion); + db.close(); + db = null; + + setTemporaryStorageLimit(tempStorageLimitKB * 2); + + resetAllDatabases(continueToNextStepSync); + yield undefined; + + delete options.version; + + spec = getSpec(0); + info("Opening database for " + spec + " with unspecified version"); + + request = indexedDB.openForPrincipal(getPrincipal(spec), name, options); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + event = yield undefined; + + is(event.type, "upgradeneeded", "Got upgradeneeded event"); + + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.type, "success", "Got success event"); + + db = event.target.result; + is(db.version, 1, "Correct version 1 (database was recreated)"); + db.close(); + db = null; + + info( + "Stage 3 - " + + "Cutting storage limit in half to force deletion of some databases" + ); + + setTemporaryStorageLimit(tempStorageLimitKB / 2); + + resetAllDatabases(continueToNextStepSync); + yield undefined; + + info("Opening database for " + spec + " with unspecified version"); + + // Open the same db again to force QM to delete others. The first origin (0) + // should be the most recent so it should not be deleted and we should not + // get an upgradeneeded event here. + request = indexedDB.openForPrincipal(getPrincipal(spec), name, options); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.type, "success", "Got correct event type"); + + db = event.target.result; + is(db.version, 1, "Correct version 1"); + db.close(); + db = null; + + setTemporaryStorageLimit(tempStorageLimitKB * 2); + + resetAllDatabases(continueToNextStepSync); + yield undefined; + + options.version = finalVersion; + + let newDatabaseCount = 0; + for (let i = 0; i < databaseCount; i++) { + let spec = getSpec(i); + info("Opening database for " + spec + " with version " + options.version); + + let request = indexedDB.openForPrincipal( + getPrincipal(spec), + name, + options + ); + request.onerror = errorHandler; + request.onupgradeneeded = function (event) { + if (!event.oldVersion) { + newDatabaseCount++; + } + }; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + is(event.type, "success", "Got correct event type"); + + let db = request.result; + is(db.version, finalVersion, "Correct version " + finalVersion); + db.close(); + } + + info("Needed to recreate " + newDatabaseCount + " databases"); + ok(newDatabaseCount, "Created some new databases"); + ok(newDatabaseCount < databaseCount, "Didn't recreate all databases"); + } + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_traffic_jam.js b/dom/indexedDB/test/unit/test_traffic_jam.js new file mode 100644 index 0000000000..6505b66964 --- /dev/null +++ b/dom/indexedDB/test/unit/test_traffic_jam.js @@ -0,0 +1,99 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + let requests = []; + function doOpen( + version, + errorCallback, + upgradeNeededCallback, + successCallback + ) { + let request = indexedDB.open(name, version); + request.onerror = errorCallback; + request.onupgradeneeded = upgradeNeededCallback; + request.onsuccess = successCallback; + requests.push(request); + } + + doOpen( + 1, + errorHandler, + grabEventAndContinueHandler, + grabEventAndContinueHandler + ); + doOpen(2, errorHandler, unexpectedSuccessHandler, unexpectedSuccessHandler); + + let event = yield undefined; + is(event.type, "upgradeneeded", "expect an upgradeneeded event"); + is(event.target, requests[0], "fired at the right request"); + + let db = event.target.result; + db.createObjectStore("foo"); + + doOpen(3, errorHandler, unexpectedSuccessHandler, unexpectedSuccessHandler); + doOpen(2, errorHandler, unexpectedSuccessHandler, unexpectedSuccessHandler); + doOpen(3, errorHandler, unexpectedSuccessHandler, unexpectedSuccessHandler); + + event.target.transaction.oncomplete = grabEventAndContinueHandler; + + event = yield undefined; + is(event.type, "complete", "expect a complete event"); + is( + event.target, + requests[0].transaction, + "expect it to be fired at the transaction" + ); + + event = yield undefined; + is(event.type, "success", "expect a success event"); + is(event.target, requests[0], "fired at the right request"); + event.target.result.close(); + + requests[1].onupgradeneeded = grabEventAndContinueHandler; + + event = yield undefined; + is(event.type, "upgradeneeded", "expect an upgradeneeded event"); + is(event.target, requests[1], "fired at the right request"); + + requests[1].onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + is(event.type, "success", "expect a success event"); + is(event.target, requests[1], "fired at the right request"); + event.target.result.close(); + + requests[2].onupgradeneeded = grabEventAndContinueHandler; + + event = yield undefined; + is(event.type, "upgradeneeded", "expect an upgradeneeded event"); + is(event.target, requests[2], "fired at the right request"); + + requests[2].onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + is(event.type, "success", "expect a success event"); + is(event.target, requests[2], "fired at the right request"); + event.target.result.close(); + + requests[3].onerror = null; + requests[3].addEventListener("error", new ExpectError("VersionError", true)); + + event = yield undefined; + + requests[4].onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + is(event.type, "success", "expect a success event"); + is(event.target, requests[4], "fired at the right request"); + event.target.result.close(); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_transaction_abort.js b/dom/indexedDB/test/unit/test_transaction_abort.js new file mode 100644 index 0000000000..6829392842 --- /dev/null +++ b/dom/indexedDB/test/unit/test_transaction_abort.js @@ -0,0 +1,377 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +var testGenerator = testSteps(); + +var abortFired = false; + +function abortListener(evt) { + abortFired = true; + is(evt.target.error, null, "Expect a null error for an aborted transaction"); +} + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + db.onabort = abortListener; + + let transaction; + let objectStore; + let index; + + transaction = event.target.transaction; + + is(transaction.error, null, "Expect a null error"); + + objectStore = db.createObjectStore("foo", { autoIncrement: true }); + index = objectStore.createIndex("fooindex", "indexKey", { unique: true }); + + is(transaction.db, db, "Correct database"); + is(transaction.mode, "versionchange", "Correct mode"); + is(transaction.objectStoreNames.length, 1, "Correct names length"); + is(transaction.objectStoreNames.item(0), "foo", "Correct name"); + is(transaction.objectStore("foo"), objectStore, "Can get stores"); + is(transaction.oncomplete, null, "No complete listener"); + is(transaction.onabort, null, "No abort listener"); + + is(objectStore.name, "foo", "Correct name"); + is(objectStore.keyPath, null, "Correct keyPath"); + + is(objectStore.indexNames.length, 1, "Correct indexNames length"); + is(objectStore.indexNames[0], "fooindex", "Correct indexNames name"); + is(objectStore.index("fooindex"), index, "Can get index"); + + // Wait until it's complete! + transaction.oncomplete = grabEventAndContinueHandler; + event = yield undefined; + + is(transaction.db, db, "Correct database"); + is(transaction.mode, "versionchange", "Correct mode"); + is(transaction.objectStoreNames.length, 1, "Correct names length"); + is(transaction.objectStoreNames.item(0), "foo", "Correct name"); + is(transaction.onabort, null, "No abort listener"); + + try { + is(transaction.objectStore("foo").name, "foo", "Can't get stores"); + ok(false, "Should have thrown"); + } catch (e) { + ok(true, "Out of scope transaction can't make stores"); + } + + is(objectStore.name, "foo", "Correct name"); + is(objectStore.keyPath, null, "Correct keyPath"); + + is(objectStore.indexNames.length, 1, "Correct indexNames length"); + is(objectStore.indexNames[0], "fooindex", "Correct indexNames name"); + + try { + objectStore.add({}); + ok(false, "Should have thrown"); + } catch (e) { + ok(true, "Add threw"); + } + + try { + objectStore.put({}, 1); + ok(false, "Should have thrown"); + } catch (e) { + ok(true, "Put threw"); + } + + try { + objectStore.put({}, 1); + ok(false, "Should have thrown"); + } catch (e) { + ok(true, "Put threw"); + } + + try { + objectStore.delete(1); + ok(false, "Should have thrown"); + } catch (e) { + ok(true, "Remove threw"); + } + + try { + objectStore.get(1); + ok(false, "Should have thrown"); + } catch (e) { + ok(true, "Get threw"); + } + + try { + objectStore.getAll(null); + ok(false, "Should have thrown"); + } catch (e) { + ok(true, "GetAll threw"); + } + + try { + objectStore.openCursor(); + ok(false, "Should have thrown"); + } catch (e) { + ok(true, "OpenCursor threw"); + } + + try { + objectStore.createIndex("bar", "id"); + ok(false, "Should have thrown"); + } catch (e) { + ok(true, "CreateIndex threw"); + } + + try { + objectStore.index("bar"); + ok(false, "Should have thrown"); + } catch (e) { + ok(true, "Index threw"); + } + + try { + objectStore.deleteIndex("bar"); + ok(false, "Should have thrown"); + } catch (e) { + ok(true, "RemoveIndex threw"); + } + + yield undefined; + + request = db.transaction("foo", "readwrite").objectStore("foo").add({}); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + event.target.transaction.onabort = function (event) { + ok(false, "Shouldn't see an abort event!"); + }; + event.target.transaction.oncomplete = grabEventAndContinueHandler; + event = yield undefined; + + is(event.type, "complete", "Right kind of event"); + + let key; + + request = db.transaction("foo", "readwrite").objectStore("foo").add({}); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + key = event.target.result; + + event.target.transaction.onabort = grabEventAndContinueHandler; + event.target.transaction.oncomplete = function (event) { + ok(false, "Shouldn't see a complete event here!"); + }; + + event.target.transaction.abort(); + + event = yield undefined; + + is(event.type, "abort", "Right kind of event"); + + request = db.transaction("foo").objectStore("foo").get(key); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, undefined, "Object was removed"); + + executeSoon(function () { + testGenerator.next(); + }); + yield undefined; + + let keys = []; + let abortEventCount = 0; + function abortErrorHandler(event) { + is(event.target.error.name, "AbortError", "Good error"); + abortEventCount++; + event.preventDefault(); + } + objectStore = db.transaction("foo", "readwrite").objectStore("foo"); + + for (let i = 0; i < 10; i++) { + request = objectStore.add({}); + request.onerror = abortErrorHandler; + request.onsuccess = function (event) { + keys.push(event.target.result); + if (keys.length == 5) { + event.target.transaction.onabort = grabEventAndContinueHandler; + event.target.transaction.abort(); + } + }; + } + event = yield undefined; + + is(event.type, "abort", "Got abort event"); + is(keys.length, 5, "Added 5 items in this transaction"); + is(abortEventCount, 5, "Got 5 abort error events"); + + for (let i in keys) { + request = db.transaction("foo").objectStore("foo").get(keys[i]); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(event.target.result, undefined, "Object was removed by abort"); + } + + // Set up some predictible data + transaction = db.transaction("foo", "readwrite"); + objectStore = transaction.objectStore("foo"); + objectStore.clear(); + objectStore.add({}, 1); + objectStore.add({}, 2); + request = objectStore.add({}, 1); + request.onsuccess = function () { + ok(false, "inserting duplicate key should fail"); + }; + request.onerror = function (event) { + ok(true, "inserting duplicate key should fail"); + event.preventDefault(); + }; + transaction.oncomplete = grabEventAndContinueHandler; + yield undefined; + + // Check when aborting is allowed + abortEventCount = 0; + let expectedAbortEventCount = 0; + + // During INITIAL + transaction = db.transaction("foo"); + transaction.abort(); + try { + transaction.abort(); + ok(false, "second abort should throw an error"); + } catch (ex) { + ok(true, "second abort should throw an error"); + } + + // During LOADING + transaction = db.transaction("foo"); + transaction.objectStore("foo").get(1).onerror = abortErrorHandler; + expectedAbortEventCount++; + transaction.abort(); + try { + transaction.abort(); + ok(false, "second abort should throw an error"); + } catch (ex) { + ok(true, "second abort should throw an error"); + } + + // During LOADING from callback + transaction = db.transaction("foo"); + transaction.objectStore("foo").get(1).onsuccess = grabEventAndContinueHandler; + event = yield undefined; + transaction.objectStore("foo").get(1).onerror = abortErrorHandler; + expectedAbortEventCount++; + transaction.abort(); + try { + transaction.abort(); + ok(false, "second abort should throw an error"); + } catch (ex) { + ok(true, "second abort should throw an error"); + } + + // During LOADING from error callback + transaction = db.transaction("foo", "readwrite"); + transaction.objectStore("foo").add({}, 1).onerror = function (event) { + event.preventDefault(); + + transaction.objectStore("foo").get(1).onerror = abortErrorHandler; + expectedAbortEventCount++; + + transaction.abort(); + continueToNextStep(); + }; + yield undefined; + + // In between callbacks + transaction = db.transaction("foo"); + function makeNewRequest() { + let r = transaction.objectStore("foo").get(1); + r.onsuccess = makeNewRequest; + r.onerror = abortErrorHandler; + } + makeNewRequest(); + transaction.objectStore("foo").get(1).onsuccess = function (event) { + executeSoon(function () { + transaction.abort(); + expectedAbortEventCount++; + continueToNextStep(); + }); + }; + yield undefined; + + // During COMMITTING + transaction = db.transaction("foo", "readwrite"); + transaction.objectStore("foo").put({ hello: "world" }, 1).onsuccess = + function (event) { + continueToNextStep(); + }; + yield undefined; + try { + transaction.abort(); + ok(false, "second abort should throw an error"); + } catch (ex) { + ok(true, "second abort should throw an error"); + } + transaction.oncomplete = grabEventAndContinueHandler; + event = yield undefined; + + // Since the previous transaction shouldn't have caused any error events, + // we know that all events should have fired by now. + is(abortEventCount, expectedAbortEventCount, "All abort errors fired"); + + // Abort both failing and succeeding requests + transaction = db.transaction("foo", "readwrite"); + transaction.onabort = transaction.oncomplete = grabEventAndContinueHandler; + transaction.objectStore("foo").add({ indexKey: "key" }).onsuccess = function ( + event + ) { + transaction.abort(); + }; + let request1 = transaction.objectStore("foo").add({ indexKey: "key" }); + request1.onsuccess = grabEventAndContinueHandler; + request1.onerror = grabEventAndContinueHandler; + let request2 = transaction.objectStore("foo").get(1); + request2.onsuccess = grabEventAndContinueHandler; + request2.onerror = grabEventAndContinueHandler; + + event = yield undefined; + is(event.type, "error", "abort() should make all requests fail"); + is(event.target, request1, "abort() should make all requests fail"); + is( + event.target.error.name, + "AbortError", + "abort() should make all requests fail" + ); + event.preventDefault(); + + event = yield undefined; + is(event.type, "error", "abort() should make all requests fail"); + is(event.target, request2, "abort() should make all requests fail"); + is( + event.target.error.name, + "AbortError", + "abort() should make all requests fail" + ); + event.preventDefault(); + + event = yield undefined; + is(event.type, "abort", "transaction should fail"); + is(event.target, transaction, "transaction should fail"); + + ok(abortFired, "Abort should have fired!"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_transaction_abort_hang.js b/dom/indexedDB/test/unit/test_transaction_abort_hang.js new file mode 100644 index 0000000000..6a2c61128b --- /dev/null +++ b/dom/indexedDB/test/unit/test_transaction_abort_hang.js @@ -0,0 +1,108 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ +"use strict"; + +var self = this; + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const dbName = self.window + ? window.location.pathname + : "test_transaction_abort_hang"; + const objStoreName = "foo"; + const transactionCount = 30; + + let completedTransactionCount = 0; + let caughtError = false; + + let abortedTransactionIndex = Math.floor(transactionCount / 2); + if (abortedTransactionIndex % 2 == 0) { + abortedTransactionIndex++; + } + + let request = indexedDB.open(dbName, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + let event = yield undefined; + + request.result.createObjectStore(objStoreName, { autoIncrement: true }); + + request.onupgradeneeded = null; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + let db = event.target.result; + + for (let i = 0; i < transactionCount; i++) { + const readonly = i % 2 == 0; + const mode = readonly ? "readonly" : "readwrite"; + + let transaction = db.transaction(objStoreName, mode); + + if (i == transactionCount - 1) { + // Last one, finish the test. + transaction.oncomplete = grabEventAndContinueHandler; + } else if (i == abortedTransactionIndex - 1) { + transaction.oncomplete = function (event) { + ok( + true, + "Completed transaction " + + ++completedTransactionCount + + " (We may hang after this!)" + ); + }; + } else if (i == abortedTransactionIndex) { + // Special transaction that we abort outside the normal event flow. + transaction.onerror = function (event) { + ok( + true, + "Aborted transaction " + + ++completedTransactionCount + + " (We didn't hang!)" + ); + is( + event.target.error.name, + "AbortError", + "AbortError set as the error on the request" + ); + is( + event.target.transaction.error, + null, + "No error set on the transaction" + ); + ok(!caughtError, "Haven't seen the error event yet"); + caughtError = true; + event.preventDefault(); + }; + // This has to happen after the we return to the event loop but before the + // transaction starts running. + executeSoon(function () { + transaction.abort(); + }); + } else { + transaction.oncomplete = function (event) { + ok(true, "Completed transaction " + ++completedTransactionCount); + }; + } + + if (readonly) { + transaction.objectStore(objStoreName).get(0); + } else { + try { + transaction.objectStore(objStoreName).add({}); + } catch (e) {} + } + } + ok(true, "Created all transactions"); + + event = yield undefined; + + ok(true, "Completed transaction " + ++completedTransactionCount); + ok(caughtError, "Caught the error event when we aborted the transaction"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_transaction_duplicate_store_names.js b/dom/indexedDB/test/unit/test_transaction_duplicate_store_names.js new file mode 100644 index 0000000000..6b084fa143 --- /dev/null +++ b/dom/indexedDB/test/unit/test_transaction_duplicate_store_names.js @@ -0,0 +1,45 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const dbName = this.window + ? window.location.pathname + : "test_transaction_duplicate_store_names"; + const dbVersion = 1; + const objectStoreName = "foo"; + const data = {}; + const dataKey = 1; + + let request = indexedDB.open(dbName, dbVersion); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + + let event = yield undefined; + + let db = event.target.result; + let objectStore = db.createObjectStore(objectStoreName); + objectStore.add(data, dataKey); + + event = yield undefined; + + db = event.target.result; + + let transaction = db.transaction( + [objectStoreName, objectStoreName], + "readwrite" + ); + transaction.onerror = errorHandler; + transaction.oncomplete = grabEventAndContinueHandler; + + event = yield undefined; + + ok(true, "Transaction created successfully"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_transaction_error.js b/dom/indexedDB/test/unit/test_transaction_error.js new file mode 100644 index 0000000000..6b134a97ae --- /dev/null +++ b/dom/indexedDB/test/unit/test_transaction_error.js @@ -0,0 +1,131 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const dbName = this.window + ? window.location.pathname + : "test_transaction_error"; + const dbVersion = 1; + const objectStoreName = "foo"; + const data = {}; + const dataKey = 1; + const expectedError = "ConstraintError"; + + let request = indexedDB.open(dbName, dbVersion); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + + let event = yield undefined; + + info("Creating database"); + + let db = event.target.result; + let objectStore = db.createObjectStore(objectStoreName); + objectStore.add(data, dataKey); + + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + db = event.target.result; + + try { + db.transaction(objectStoreName, "versionchange"); + ok(false, "TypeError shall be thrown if transaction mode is wrong."); + } catch (e) { + ok(e instanceof TypeError, "got a database exception"); + is(e.name, "TypeError", "correct error"); + } + + let transaction = db.transaction(objectStoreName, "readwrite"); + transaction.onerror = grabEventAndContinueHandler; + transaction.oncomplete = grabEventAndContinueHandler; + + objectStore = transaction.objectStore(objectStoreName); + + info("Adding duplicate entry with preventDefault()"); + + request = objectStore.add(data, dataKey); + request.onsuccess = unexpectedSuccessHandler; + request.onerror = grabEventAndContinueHandler; + event = yield undefined; + + is(event.type, "error", "Got an error event"); + is(event.target, request, "Error event targeted request"); + is(event.currentTarget, request, "Got request error first"); + is( + event.currentTarget.error.name, + expectedError, + "Request has correct error" + ); + event.preventDefault(); + + event = yield undefined; + + is(event.type, "error", "Got an error event"); + is(event.target, request, "Error event targeted request"); + is(event.currentTarget, transaction, "Got transaction error second"); + is(event.currentTarget.error, null, "Transaction has null error"); + + event = yield undefined; + + is(event.type, "complete", "Got a complete event"); + is(event.target, transaction, "Complete event targeted transaction"); + is( + event.currentTarget, + transaction, + "Complete event only targeted transaction" + ); + is(event.currentTarget.error, null, "Transaction has null error"); + + // Try again without preventDefault(). + + transaction = db.transaction(objectStoreName, "readwrite"); + transaction.onerror = grabEventAndContinueHandler; + transaction.onabort = grabEventAndContinueHandler; + + objectStore = transaction.objectStore(objectStoreName); + + info("Adding duplicate entry without preventDefault()"); + + request = objectStore.add(data, dataKey); + request.onsuccess = unexpectedSuccessHandler; + request.onerror = grabEventAndContinueHandler; + event = yield undefined; + + is(event.type, "error", "Got an error event"); + is(event.target, request, "Error event targeted request"); + is(event.currentTarget, request, "Got request error first"); + is( + event.currentTarget.error.name, + expectedError, + "Request has correct error" + ); + + event = yield undefined; + + is(event.type, "error", "Got an error event"); + is(event.target, request, "Error event targeted request"); + is(event.currentTarget, transaction, "Got transaction error second"); + is(event.currentTarget.error, null, "Transaction has null error"); + + event = yield undefined; + + is(event.type, "abort", "Got an abort event"); + is(event.target, transaction, "Abort event targeted transaction"); + is(event.currentTarget, transaction, "Abort event only targeted transaction"); + is( + event.currentTarget.error.name, + expectedError, + "Transaction has correct error" + ); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_transaction_lifetimes.js b/dom/indexedDB/test/unit/test_transaction_lifetimes.js new file mode 100644 index 0000000000..12150397b9 --- /dev/null +++ b/dom/indexedDB/test/unit/test_transaction_lifetimes.js @@ -0,0 +1,97 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + let request = indexedDB.open( + this.window ? window.location.pathname : "Splendid Test", + 1 + ); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = unexpectedSuccessHandler; + let event = yield undefined; + + let db = event.target.result; + db.onerror = errorHandler; + + event.target.transaction.onerror = errorHandler; + event.target.transaction.oncomplete = grabEventAndContinueHandler; + + let os = db.createObjectStore("foo", { autoIncrement: true }); + os.createIndex("bar", "foo.bar"); + event = yield undefined; + + is( + request.transaction, + event.target, + "request.transaction should still be set" + ); + + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + is(request.transaction, null, "request.transaction should be cleared"); + + let transaction = db.transaction("foo", "readwrite"); + + os = transaction.objectStore("foo"); + // Place a request to keep the transaction alive long enough for our + // executeSoon. + let requestComplete = false; + + let wasAbleToGrabObjectStoreOutsideOfCallback = false; + let wasAbleToGrabIndexOutsideOfCallback = false; + executeSoon(function () { + ok(!requestComplete, "Ordering is correct."); + wasAbleToGrabObjectStoreOutsideOfCallback = + !!transaction.objectStore("foo"); + wasAbleToGrabIndexOutsideOfCallback = !!transaction + .objectStore("foo") + .index("bar"); + }); + + request = os.add({}); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + + event = yield undefined; + + requestComplete = true; + + ok( + wasAbleToGrabObjectStoreOutsideOfCallback, + "Should be able to get objectStore" + ); + ok(wasAbleToGrabIndexOutsideOfCallback, "Should be able to get index"); + + transaction.oncomplete = grabEventAndContinueHandler; + yield undefined; + + try { + transaction.objectStore("foo"); + ok(false, "Should have thrown!"); + } catch (e) { + ok(e instanceof DOMException, "Got database exception."); + is(e.name, "InvalidStateError", "Good error."); + is(e.code, DOMException.INVALID_STATE_ERR, "Good error code."); + } + + continueToNextStep(); + yield undefined; + + try { + transaction.objectStore("foo"); + ok(false, "Should have thrown!"); + } catch (e) { + ok(e instanceof DOMException, "Got database exception."); + is(e.name, "InvalidStateError", "Good error."); + is(e.code, DOMException.INVALID_STATE_ERR, "Good error code."); + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_transaction_lifetimes_nested.js b/dom/indexedDB/test/unit/test_transaction_lifetimes_nested.js new file mode 100644 index 0000000000..88ac61b58c --- /dev/null +++ b/dom/indexedDB/test/unit/test_transaction_lifetimes_nested.js @@ -0,0 +1,52 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator, disableWorkerTest */ +var disableWorkerTest = "This test uses SpecialPowers"; + +var testGenerator = testSteps(); + +function* testSteps() { + let request = indexedDB.open( + this.window ? window.location.pathname : "Splendid Test", + 1 + ); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + db.onerror = errorHandler; + + event.target.onsuccess = continueToNextStep; + db.createObjectStore("foo"); + yield undefined; + + db.transaction("foo"); + + let transaction2; + + let eventHasRun; + + let tm = SpecialPowers.Services ? SpecialPowers.Services.tm : Services.tm; + + tm.dispatchToMainThread(function () { + eventHasRun = true; + + transaction2 = db.transaction("foo"); + }); + + tm.spinEventLoopUntil( + "Test(test_transaction_lifetimes_nested.js:testSteps)", + () => eventHasRun + ); + + ok(transaction2, "Non-null transaction2"); + + continueToNextStep(); + yield undefined; + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_transaction_ordering.js b/dom/indexedDB/test/unit/test_transaction_ordering.js new file mode 100644 index 0000000000..beb9dcfdc3 --- /dev/null +++ b/dom/indexedDB/test/unit/test_transaction_ordering.js @@ -0,0 +1,50 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + let request = indexedDB.open( + this.window ? window.location.pathname : "Splendid Test", + 1 + ); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + db.onerror = errorHandler; + + request.onsuccess = continueToNextStep; + + db.createObjectStore("foo"); + yield undefined; + + let trans1 = db.transaction("foo", "readwrite"); + let trans2 = db.transaction("foo", "readwrite"); + + let request1 = trans2.objectStore("foo").put("2", 42); + let request2 = trans1.objectStore("foo").put("1", 42); + + request1.onerror = errorHandler; + request2.onerror = errorHandler; + + trans1.oncomplete = grabEventAndContinueHandler; + trans2.oncomplete = grabEventAndContinueHandler; + + yield undefined; + yield undefined; + + let trans3 = db.transaction("foo", "readonly"); + request = trans3.objectStore("foo").get(42); + request.onsuccess = grabEventAndContinueHandler; + request.onerror = errorHandler; + + event = yield undefined; + is(event.target.result, "2", "Transactions were ordered properly."); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_unexpectedDirectory.js b/dom/indexedDB/test/unit/test_unexpectedDirectory.js new file mode 100644 index 0000000000..5af56da1c8 --- /dev/null +++ b/dom/indexedDB/test/unit/test_unexpectedDirectory.js @@ -0,0 +1,63 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +function getTestingFiles() { + const filenameBase = "unexpectedDirectory"; + let baseDir = getRelativeFile("storage/permanent/chrome/idb"); + + let unexpectedDirWithoutSuffix = baseDir.clone(); + unexpectedDirWithoutSuffix.append(filenameBase); + + let unexpectedDir = baseDir.clone(); + unexpectedDir.append(filenameBase + ".files"); + + return { unexpectedDirWithoutSuffix, unexpectedDir }; +} + +function createTestingEnvironment() { + let testingFiles = getTestingFiles(); + testingFiles.unexpectedDir.create( + Ci.nsIFile.DIRECTORY_TYPE, + parseInt("0755", 8) + ); + + testingFiles.unexpectedDirWithoutSuffix.create( + Ci.nsIFile.DIRECTORY_TYPE, + parseInt("0755", 8) + ); +} + +/** + * This test verifies unexpected directories won't block idb's initialization. + */ + +/* exported testSteps */ +async function testSteps() { + info("Verifying open shouldn't be blocked by unexpected files"); + + createTestingEnvironment(); + + let request = indexedDB.open( + this.window ? window.location.pathname : "Splendid Test", + 1 + ); + await expectingUpgrade(request); + + // Waiting for a success event for indexedDB.open() + let event = await expectingSuccess(request); + + let testingFiles = getTestingFiles(); + ok( + !testingFiles.unexpectedDir.exists(), + "The unexpected directory doesn't exist" + ); + ok( + !testingFiles.unexpectedDirWithoutSuffix.exists(), + "The unexpected directory without the suffix doesn't exist" + ); + + let db = event.target.result; + db.close(); +} diff --git a/dom/indexedDB/test/unit/test_unique_index_update.js b/dom/indexedDB/test/unit/test_unique_index_update.js new file mode 100644 index 0000000000..736344ae5e --- /dev/null +++ b/dom/indexedDB/test/unit/test_unique_index_update.js @@ -0,0 +1,71 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + let request = indexedDB.open( + this.window ? window.location.pathname : "Splendid Test", + 1 + ); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + + let event = yield undefined; + + let db = event.target.result; + + for (let autoIncrement of [false, true]) { + let objectStore = db.createObjectStore(autoIncrement, { + keyPath: "id", + autoIncrement, + }); + objectStore.createIndex("", "index", { unique: true }); + + for (let i = 0; i < 10; i++) { + objectStore.add({ id: i, index: i }); + } + } + + event = yield undefined; + is(event.type, "success", "expect a success event"); + + for (let autoIncrement of [false, true]) { + let objectStore = db + .transaction(autoIncrement, "readwrite") + .objectStore(autoIncrement); + + request = objectStore.put({ id: 5, index: 6 }); + request.onsuccess = unexpectedSuccessHandler; + request.addEventListener("error", new ExpectError("ConstraintError", true)); + event = yield undefined; + + event.preventDefault(); + + let keyRange = IDBKeyRange.only(5); + + objectStore.index("").openCursor(keyRange).onsuccess = function (event) { + let cursor = event.target.result; + ok(cursor, "Must have a cursor here"); + + is(cursor.value.index, 5, "Still have the right index value"); + + cursor.value.index = 6; + + request = cursor.update(cursor.value); + request.onsuccess = unexpectedSuccessHandler; + request.addEventListener( + "error", + new ExpectError("ConstraintError", true) + ); + }; + + yield undefined; + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_upgrade_add_index.js b/dom/indexedDB/test/unit/test_upgrade_add_index.js new file mode 100644 index 0000000000..06b9ae7bff --- /dev/null +++ b/dom/indexedDB/test/unit/test_upgrade_add_index.js @@ -0,0 +1,107 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function generateKey() { + let algorithm = { + name: "RSASSA-PKCS1-v1_5", + hash: "SHA-256", + modulusLength: 1024, + publicExponent: new Uint8Array([0x01, 0x00, 0x01]), + }; + + return crypto.subtle.generateKey(algorithm, true, ["sign", "verify"]); +} + +const hasCrypto = "crypto" in this; + +/** + * Test addition of a new index when the existing values in the referenced + * object store have potentially unusual structured clone participants. + * + * When a new index is created, the existing object store's contents need to be + * processed to derive the index values. This is a special event because + * normally index values are extracted at add()/put() time in the content + * process using the page/worker's JS context (modulo some spec stuff). But + * the index creation operation is actually running in the parent process on the + * I/O thread for the given database. So the JS context scenario is suddenly + * a lot more complicated, and we need extra test coverage, in particular for + * unusual structured clone payloads. + * + * Relationship to other test: + * - test_create_index_with_integer_keys.js: This test is derived from that one. + */ +function* testSteps() { + // -- Create our fancy data that has interesting structured clone issues. + const allData = []; + + // the xpcshell tests normalize self into existence. + if (hasCrypto) { + info("creating crypto key"); + // (all IDB tests badly need a test driver update...) + generateKey().then(grabEventAndContinueHandler); + let key = yield undefined; + allData.push({ + id: 1, + what: "crypto", + data: key, + }); + } else { + info("not storing crypto key"); + } + + // -- Create the IDB and populate it with the base data. + info("opening initial database"); + let request = indexedDB.open( + this.window ? window.location.pathname : "Splendid Test", + 1 + ); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; // advance onupgradeneeded + let event = yield undefined; // wait for onupgradeneeded. + + let db = event.target.result; + db.onerror = errorHandler; + + event.target.onsuccess = continueToNextStep; // advance when the open completes + + // Make object store, add data. + let objectStore = db.createObjectStore("foo", { keyPath: "id" }); + for (let datum of allData) { + info(`add()ing ${datum.what}`); + objectStore.add(datum); + } + // wait for the open to complete following our upgrade transaction self-closing + yield undefined; + // explicitly close the database so we can open it again. We don't wait for + // this, but the upgrade open will block until the close actually happens. + info("closing initial database"); + db.close(); + + // -- Trigger an upgrade, adding a new index. + info("opening database for upgrade to v2"); + request = indexedDB.open( + this.window ? window.location.pathname : "Splendid Test", + 2 + ); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; // advance onupgradeneeded + event = yield undefined; // wait for onupgradeneeded + + let db2 = event.target.result; + db2.onerror = errorHandler; + + event.target.onsuccess = continueToNextStep; // advance when the open completes + + // Create index. + info("in upgrade, creating index"); + event.target.transaction.objectStore("foo").createIndex("foo", "what"); + yield undefined; // wait for the open to complete + info("upgrade completed"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_view_put_get_values.js b/dom/indexedDB/test/unit/test_view_put_get_values.js new file mode 100644 index 0000000000..a270e65f2f --- /dev/null +++ b/dom/indexedDB/test/unit/test_view_put_get_values.js @@ -0,0 +1,151 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator, disableWorkerTest */ +var disableWorkerTest = "Need a way to set temporary prefs from a worker"; + +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window + ? window.location.pathname + : "test_view_put_get_values.js"; + + const objectStoreName = "Views"; + + const viewData = { key: 1, view: getRandomView(100000) }; + + const tests = [ + { + external: false, + preprocessing: false, + }, + { + external: true, + preprocessing: false, + }, + { + external: true, + preprocessing: true, + }, + ]; + + for (let test of tests) { + if (test.external) { + if (this.window) { + info("Setting data threshold pref"); + + SpecialPowers.pushPrefEnv( + { set: [["dom.indexedDB.dataThreshold", 0]] }, + continueToNextStep + ); + yield undefined; + } else { + setDataThreshold(0); + } + } + + if (test.preprocessing) { + if (this.window) { + info("Setting preprocessing pref"); + + SpecialPowers.pushPrefEnv( + { set: [["dom.indexedDB.preprocessing", true]] }, + continueToNextStep + ); + yield undefined; + } else { + enablePreprocessing(); + } + } + + info("Opening database"); + + let request = indexedDB.open(name); + request.onerror = errorHandler; + request.onupgradeneeded = continueToNextStepSync; + request.onsuccess = unexpectedSuccessHandler; + yield undefined; + + // upgradeneeded + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = continueToNextStepSync; + + info("Creating objectStore"); + + request.result.createObjectStore(objectStoreName); + + yield undefined; + + // success + let db = request.result; + db.onerror = errorHandler; + + info("Storing view"); + + let objectStore = db + .transaction([objectStoreName], "readwrite") + .objectStore(objectStoreName); + request = objectStore.add(viewData.view, viewData.key); + request.onsuccess = continueToNextStepSync; + yield undefined; + + is(request.result, viewData.key, "Got correct key"); + + info("Getting view"); + + request = objectStore.get(viewData.key); + request.onsuccess = continueToNextStepSync; + yield undefined; + + verifyView(request.result, viewData.view); + yield undefined; + + info("Getting view in new transaction"); + + request = db + .transaction([objectStoreName]) + .objectStore(objectStoreName) + .get(viewData.key); + request.onsuccess = continueToNextStepSync; + yield undefined; + + verifyView(request.result, viewData.view); + yield undefined; + + getCurrentUsage(grabFileUsageAndContinueHandler); + let fileUsage = yield undefined; + + if (test.external) { + ok(fileUsage > 0, "File usage is not zero"); + } else { + ok(fileUsage == 0, "File usage is zero"); + } + + db.close(); + + request = indexedDB.deleteDatabase(name); + request.onerror = errorHandler; + request.onsuccess = continueToNextStepSync; + yield undefined; + + if (this.window) { + info("Resetting prefs"); + + SpecialPowers.popPrefEnv(continueToNextStep); + yield undefined; + } else { + if (test.external) { + resetDataThreshold(); + } + + if (test.preprocessing) { + resetPreprocessing(); + } + } + } + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_wasm_get_values.js b/dom/indexedDB/test/unit/test_wasm_get_values.js new file mode 100644 index 0000000000..676cb1662b --- /dev/null +++ b/dom/indexedDB/test/unit/test_wasm_get_values.js @@ -0,0 +1,59 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = "test_wasm_recompile.js"; + + const objectStoreName = "Wasm"; + + const wasmData = { key: 1 }; + + // The goal of this test is to prove that stored wasm is never deserialized. + + info("Installing profile"); + + clearAllDatabases(continueToNextStepSync); + yield undefined; + + // The profile was created with a mythical build (buildId: 20180309213541, + // cpuId: X64=0x2). It contains one stored wasm module (file id 1 - bytecode + // and file id 2 - compiled/machine code). The file create_db.js in the + // package was run locally (specifically it was temporarily added to + // xpcshell-parent-process.ini and then executed: + // mach xpcshell-test dom/indexedDB/test/unit/create_db.js + installPackagedProfile("wasm_get_values_profile"); + + info("Opening database"); + + let request = indexedDB.open(name); + request.onerror = errorHandler; + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = continueToNextStepSync; + yield undefined; + + // success + let db = request.result; + db.onerror = errorHandler; + + info("Getting wasm"); + + request = db + .transaction([objectStoreName]) + .objectStore(objectStoreName) + .get(wasmData.key); + request.onsuccess = continueToNextStepSync; + yield undefined; + + info("Verifying wasm"); + + let isWasmModule = request.result instanceof WebAssembly.Module; + ok(!isWasmModule, "Object is not wasm module"); + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/test_wasm_put_get_values.js b/dom/indexedDB/test/unit/test_wasm_put_get_values.js new file mode 100644 index 0000000000..13d35c7d7a --- /dev/null +++ b/dom/indexedDB/test/unit/test_wasm_put_get_values.js @@ -0,0 +1,69 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +/* exported testGenerator */ +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window + ? window.location.pathname + : "test_wasm_put_get_values.js"; + + const objectStoreName = "Wasm"; + + const wasmData = { key: 1, value: null }; + + if (!isWasmSupported()) { + finishTest(); + return; + } + + // js -e 'print(wasmTextToBinary(`(module (func (export "run") (result i32) (i32.const 13)))`))' + // prettier-ignore + let binary = new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,127,3,2,1,0,7,7,1,3,114,117,110,0,0,10,6,1,4,0,65,13,11]); + + wasmData.value = getWasmModule(binary); + + info("Opening database"); + + let request = indexedDB.open(name); + request.onerror = errorHandler; + request.onupgradeneeded = continueToNextStepSync; + request.onsuccess = unexpectedSuccessHandler; + yield undefined; + + // upgradeneeded + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = continueToNextStepSync; + + info("Creating objectStore"); + + request.result.createObjectStore(objectStoreName); + + yield undefined; + + // success + let db = request.result; + db.onerror = errorHandler; + + info("Testing failure to store wasm"); + + let objectStore = db + .transaction([objectStoreName], "readwrite") + .objectStore(objectStoreName); + + // storing a wasm module in IDB should now fail + let failed = false; + try { + objectStore.add(wasmData.value, wasmData.key); + } catch (err) { + failed = true; + ok(err instanceof DOMException, "caught right error type"); + is(err.name, "DataCloneError", "caught right error name"); + } + ok(failed, "error was thrown"); + + finishTest(); +} diff --git a/dom/indexedDB/test/unit/test_writer_starvation.js b/dom/indexedDB/test/unit/test_writer_starvation.js new file mode 100644 index 0000000000..aa036671d9 --- /dev/null +++ b/dom/indexedDB/test/unit/test_writer_starvation.js @@ -0,0 +1,117 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ +/* eslint-disable mozilla/no-arbitrary-setTimeout */ + +if (!this.window) { + this.runTest = function () { + todo(false, "Test disabled in xpcshell test suite for now"); + finishTest(); + }; +} + +var testGenerator = testSteps(); + +function* testSteps() { + const name = this.window ? window.location.pathname : "Splendid Test"; + + // Needs to be enough to saturate the thread pool. + const SYNC_REQUEST_COUNT = 25; + + let request = indexedDB.open(name, 1); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler; + request.onsuccess = grabEventAndContinueHandler; + let event = yield undefined; + + let db = event.target.result; + db.onerror = errorHandler; + + is(event.target.transaction.mode, "versionchange", "Correct mode"); + + let objectStore = db.createObjectStore("foo", { autoIncrement: true }); + + request = objectStore.add({}); + request.onerror = errorHandler; + request.onsuccess = grabEventAndContinueHandler; + event = yield undefined; + + let key = event.target.result; + ok(key, "Got a key"); + + yield undefined; + + let continueReading = true; + let readerCount = 0; + let writerCount = 0; + let callbackCount = 0; + + // Generate a bunch of reads right away without returning to the event + // loop. + info("Generating " + SYNC_REQUEST_COUNT + " readonly requests"); + + for (let i = 0; i < SYNC_REQUEST_COUNT; i++) { + readerCount++; + let request = db.transaction("foo").objectStore("foo").get(key); + request.onsuccess = function (event) { + is(event.target.transaction.mode, "readonly", "Correct mode"); + callbackCount++; + }; + } + + while (continueReading) { + readerCount++; + info("Generating additional readonly request (" + readerCount + ")"); + let request = db.transaction("foo").objectStore("foo").get(key); + request.onsuccess = function (event) { + callbackCount++; + info("Received readonly request callback (" + callbackCount + ")"); + is(event.target.transaction.mode, "readonly", "Correct mode"); + if (callbackCount == SYNC_REQUEST_COUNT) { + writerCount++; + info( + "Generating 1 readwrite request with " + + readerCount + + " previous readonly requests" + ); + let request = db + .transaction("foo", "readwrite") + .objectStore("foo") + .add({}, readerCount); + request.onsuccess = function (event) { + callbackCount++; + info("Received readwrite request callback (" + callbackCount + ")"); + is(event.target.transaction.mode, "readwrite", "Correct mode"); + is( + event.target.result, + callbackCount, + "write callback came before later reads" + ); + }; + } else if (callbackCount == SYNC_REQUEST_COUNT + 5) { + continueReading = false; + } + }; + + setTimeout( + function () { + testGenerator.next(); + }, + writerCount ? 1000 : 100 + ); + yield undefined; + } + + while (callbackCount < readerCount + writerCount) { + executeSoon(function () { + testGenerator.next(); + }); + yield undefined; + } + + is(callbackCount, readerCount + writerCount, "All requests accounted for"); + + finishTest(); + yield undefined; +} diff --git a/dom/indexedDB/test/unit/wasm_get_values_profile.zip b/dom/indexedDB/test/unit/wasm_get_values_profile.zip Binary files differnew file mode 100644 index 0000000000..916f7414d4 --- /dev/null +++ b/dom/indexedDB/test/unit/wasm_get_values_profile.zip diff --git a/dom/indexedDB/test/unit/xpcshell-child-process.toml b/dom/indexedDB/test/unit/xpcshell-child-process.toml new file mode 100644 index 0000000000..7ae70730d0 --- /dev/null +++ b/dom/indexedDB/test/unit/xpcshell-child-process.toml @@ -0,0 +1,14 @@ +[DEFAULT] +dupe-manifest = "" +head = "xpcshell-head-child-process.js" +tail = "" +skip-if = ["os == 'android'"] +support-files = [ + "GlobalObjectsChild.js", + "GlobalObjectsModule.sys.mjs", + "GlobalObjectsSandbox.js", + "xpcshell-head-parent-process.js", + "xpcshell-shared.toml", +] + +["include:xpcshell-shared.toml"] diff --git a/dom/indexedDB/test/unit/xpcshell-head-child-process.js b/dom/indexedDB/test/unit/xpcshell-head-child-process.js new file mode 100644 index 0000000000..4b40bc5c73 --- /dev/null +++ b/dom/indexedDB/test/unit/xpcshell-head-child-process.js @@ -0,0 +1,23 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +function run_test() { + const INDEXEDDB_HEAD_FILE = "xpcshell-head-parent-process.js"; + const INDEXEDDB_PREF_EXPERIMENTAL = "dom.indexedDB.experimental"; + + // IndexedDB needs a profile. + do_get_profile(); + + let thisTest = _TEST_FILE.toString().replace(/\\/g, "/"); + thisTest = thisTest.substring(thisTest.lastIndexOf("/") + 1); + + // This is defined globally via xpcshell. + /* global _HEAD_FILES */ + _HEAD_FILES.push(do_get_file(INDEXEDDB_HEAD_FILE).path.replace(/\\/g, "/")); + + Services.prefs.setBoolPref(INDEXEDDB_PREF_EXPERIMENTAL, true); + + run_test_in_child(thisTest); +} diff --git a/dom/indexedDB/test/unit/xpcshell-head-parent-process.js b/dom/indexedDB/test/unit/xpcshell-head-parent-process.js new file mode 100644 index 0000000000..f297b72d25 --- /dev/null +++ b/dom/indexedDB/test/unit/xpcshell-head-parent-process.js @@ -0,0 +1,736 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +// Tests using testGenerator are expected to define it themselves. +// Testing functions are expected to call testSteps and its type should either +// be GeneratorFunction or AsyncFunction +/* global testGenerator, testSteps:false */ + +var { classes: Cc, interfaces: Ci, utils: Cu } = Components; + +if (!("self" in this)) { + this.self = this; +} + +var bufferCache = []; + +function is(a, b, msg) { + Assert.equal(a, b, msg); +} + +function ok(cond, msg) { + Assert.ok(!!cond, msg); +} + +function isnot(a, b, msg) { + Assert.notEqual(a, b, msg); +} + +function todo(condition, name, diag) { + todo_check_true(condition); +} + +function run_test() { + runTest(); +} + +if (!this.runTest) { + this.runTest = function () { + if (SpecialPowers.isMainProcess()) { + // XPCShell does not get a profile by default. + do_get_profile(); + + enableTesting(); + enableExperimental(); + } + + // In order to support converting tests to using async functions from using + // generator functions, we detect async functions by checking the name of + // function's constructor. + Assert.ok( + typeof testSteps === "function", + "There should be a testSteps function" + ); + if (testSteps.constructor.name === "AsyncFunction") { + // Do run our existing cleanup function that would normally be called by + // the generator's call to finishTest(). + registerCleanupFunction(resetTesting); + + add_task(testSteps); + + // Since we defined run_test, we must invoke run_next_test() to start the + // async test. + run_next_test(); + } else { + Assert.ok( + testSteps.constructor.name === "GeneratorFunction", + "Unsupported function type" + ); + + do_test_pending(); + testGenerator.next(); + } + }; +} + +function finishTest() { + if (SpecialPowers.isMainProcess()) { + resetExperimental(); + resetTesting(); + } + + SpecialPowers.removeFiles(); + + executeSoon(function () { + do_test_finished(); + }); +} + +function grabEventAndContinueHandler(event) { + testGenerator.next(event); +} + +function continueToNextStep() { + executeSoon(function () { + testGenerator.next(); + }); +} + +function errorHandler(event) { + try { + dump("indexedDB error: " + event.target.error.name); + } catch (e) { + dump("indexedDB error: " + e); + } + Assert.ok(false); + finishTest(); +} + +function unexpectedSuccessHandler() { + Assert.ok(false); + finishTest(); +} + +function expectedErrorHandler(name) { + return function (event) { + Assert.equal(event.type, "error"); + Assert.equal(event.target.error.name, name); + event.preventDefault(); + grabEventAndContinueHandler(event); + }; +} + +function expectUncaughtException(expecting) { + // This is dummy for xpcshell test. +} + +function ExpectError(name, preventDefault) { + this._name = name; + this._preventDefault = preventDefault; +} +ExpectError.prototype = { + handleEvent(event) { + Assert.equal(event.type, "error"); + Assert.equal(this._name, event.target.error.name); + if (this._preventDefault) { + event.preventDefault(); + event.stopPropagation(); + } + grabEventAndContinueHandler(event); + }, +}; + +function continueToNextStepSync() { + testGenerator.next(); +} + +// TODO compareKeys is duplicated in ../helpers.js, can we import that here? +// the same applies to many other functions in this file +// this duplication should be avoided (bug 1565986) +function compareKeys(k1, k2) { + let t = typeof k1; + if (t != typeof k2) { + return false; + } + + if (t !== "object") { + return k1 === k2; + } + + if (k1 instanceof Date) { + return k2 instanceof Date && k1.getTime() === k2.getTime(); + } + + if (k1 instanceof Array) { + if (!(k2 instanceof Array) || k1.length != k2.length) { + return false; + } + + for (let i = 0; i < k1.length; ++i) { + if (!compareKeys(k1[i], k2[i])) { + return false; + } + } + + return true; + } + + if (k1 instanceof ArrayBuffer) { + if (!(k2 instanceof ArrayBuffer)) { + return false; + } + + function arrayBuffersAreEqual(a, b) { + if (a.byteLength != b.byteLength) { + return false; + } + let ui8b = new Uint8Array(b); + return new Uint8Array(a).every((val, i) => val === ui8b[i]); + } + + return arrayBuffersAreEqual(k1, k2); + } + + return false; +} + +function addPermission(permission, url) { + throw new Error("addPermission"); +} + +function removePermission(permission, url) { + throw new Error("removePermission"); +} + +function allowIndexedDB(url) { + throw new Error("allowIndexedDB"); +} + +function disallowIndexedDB(url) { + throw new Error("disallowIndexedDB"); +} + +function enableExperimental() { + SpecialPowers.setBoolPref("dom.indexedDB.experimental", true); +} + +function resetExperimental() { + SpecialPowers.clearUserPref("dom.indexedDB.experimental"); +} + +function enableTesting() { + SpecialPowers.setBoolPref("dom.indexedDB.testing", true); +} + +function resetTesting() { + SpecialPowers.clearUserPref("dom.indexedDB.testing"); +} + +function gc() { + Cu.forceGC(); + Cu.forceCC(); +} + +function scheduleGC() { + SpecialPowers.exactGC(continueToNextStep); +} + +function setTimeout(fun, timeout) { + let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); + var event = { + notify(timer) { + fun(); + }, + }; + timer.initWithCallback(event, timeout, Ci.nsITimer.TYPE_ONE_SHOT); + return timer; +} + +function initStorage() { + return Services.qms.init(); +} + +function initPersistentOrigin(principal) { + return Services.qms.initializePersistentOrigin(principal); +} + +function resetOrClearAllDatabases(callback, clear) { + if (!SpecialPowers.isMainProcess()) { + throw new Error("clearAllDatabases not implemented for child processes!"); + } + + const quotaPref = "dom.quotaManager.testing"; + + let oldPrefValue; + if (Services.prefs.prefHasUserValue(quotaPref)) { + oldPrefValue = SpecialPowers.getBoolPref(quotaPref); + } + + SpecialPowers.setBoolPref(quotaPref, true); + + let request; + + try { + if (clear) { + request = Services.qms.clear(); + } else { + request = Services.qms.reset(); + } + } catch (e) { + if (oldPrefValue !== undefined) { + SpecialPowers.setBoolPref(quotaPref, oldPrefValue); + } else { + SpecialPowers.clearUserPref(quotaPref); + } + throw e; + } + + request.callback = callback; + + return request; +} + +function resetAllDatabases(callback) { + return resetOrClearAllDatabases(callback, false); +} + +function clearAllDatabases(callback) { + return resetOrClearAllDatabases(callback, true); +} + +function installPackagedProfile(packageName) { + let profileDir = Services.dirsvc.get("ProfD", Ci.nsIFile); + + let currentDir = Services.dirsvc.get("CurWorkD", Ci.nsIFile); + + let packageFile = currentDir.clone(); + packageFile.append(packageName + ".zip"); + + let zipReader = Cc["@mozilla.org/libjar/zip-reader;1"].createInstance( + Ci.nsIZipReader + ); + zipReader.open(packageFile); + + let entryNames = []; + for (let entry of zipReader.findEntries(null)) { + if (entry != "create_db.html") { + entryNames.push(entry); + } + } + entryNames.sort(); + + for (let entryName of entryNames) { + let zipentry = zipReader.getEntry(entryName); + + let file = profileDir.clone(); + let split = entryName.split("/"); + for (let i = 0; i < split.length; i++) { + file.append(split[i]); + } + + if (zipentry.isDirectory) { + file.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt("0755", 8)); + } else { + let istream = zipReader.getInputStream(entryName); + + var ostream = Cc[ + "@mozilla.org/network/file-output-stream;1" + ].createInstance(Ci.nsIFileOutputStream); + ostream.init(file, -1, parseInt("0644", 8), 0); + + let bostream = Cc[ + "@mozilla.org/network/buffered-output-stream;1" + ].createInstance(Ci.nsIBufferedOutputStream); + bostream.init(ostream, 32768); + + bostream.writeFrom(istream, istream.available()); + + istream.close(); + bostream.close(); + } + } + + zipReader.close(); +} + +function getChromeFilesDir() { + let profileDir = Services.dirsvc.get("ProfD", Ci.nsIFile); + + let idbDir = profileDir.clone(); + idbDir.append("storage"); + idbDir.append("permanent"); + idbDir.append("chrome"); + idbDir.append("idb"); + + let idbEntries = idbDir.directoryEntries; + while (idbEntries.hasMoreElements()) { + let file = idbEntries.nextFile; + if (file.isDirectory()) { + return file; + } + } + + throw new Error("files directory doesn't exist!"); +} + +function getView(size) { + let buffer = new ArrayBuffer(size); + let view = new Uint8Array(buffer); + is(buffer.byteLength, size, "Correct byte length"); + return view; +} + +function getRandomView(size) { + let view = getView(size); + for (let i = 0; i < size; i++) { + view[i] = parseInt(Math.random() * 255); + } + return view; +} + +function getBlob(str) { + return new Blob([str], { type: "type/text" }); +} + +function getFile(name, type, str) { + return new File([str], name, { type }); +} + +function isWasmSupported() { + let testingFunctions = Cu.getJSTestingFunctions(); + return testingFunctions.wasmIsSupported(); +} + +function getWasmModule(binary) { + let module = new WebAssembly.Module(binary); + return module; +} + +function compareBuffers(buffer1, buffer2) { + if (buffer1.byteLength != buffer2.byteLength) { + return false; + } + + let view1 = buffer1 instanceof Uint8Array ? buffer1 : new Uint8Array(buffer1); + let view2 = buffer2 instanceof Uint8Array ? buffer2 : new Uint8Array(buffer2); + for (let i = 0; i < buffer1.byteLength; i++) { + if (view1[i] != view2[i]) { + return false; + } + } + return true; +} + +function verifyBuffers(buffer1, buffer2) { + ok(compareBuffers(buffer1, buffer2), "Correct buffer data"); +} + +function verifyBlob(blob1, blob2) { + is(Blob.isInstance(blob1), true, "Instance of nsIDOMBlob"); + is(File.isInstance(blob1), File.isInstance(blob2), "Instance of DOM File"); + is(blob1.size, blob2.size, "Correct size"); + is(blob1.type, blob2.type, "Correct type"); + if (File.isInstance(blob2)) { + is(blob1.name, blob2.name, "Correct name"); + } + + let buffer1; + let buffer2; + + for (let i = 0; i < bufferCache.length; i++) { + if (bufferCache[i].blob == blob2) { + buffer2 = bufferCache[i].buffer; + break; + } + } + + if (!buffer2) { + let reader = new FileReader(); + reader.readAsArrayBuffer(blob2); + reader.onload = function (event) { + buffer2 = event.target.result; + bufferCache.push({ blob: blob2, buffer: buffer2 }); + if (buffer1) { + verifyBuffers(buffer1, buffer2); + testGenerator.next(); + } + }; + } + + let reader = new FileReader(); + reader.readAsArrayBuffer(blob1); + reader.onload = function (event) { + buffer1 = event.target.result; + if (buffer2) { + verifyBuffers(buffer1, buffer2); + testGenerator.next(); + } + }; +} + +function verifyView(view1, view2) { + is(view1.byteLength, view2.byteLength, "Correct byteLength"); + verifyBuffers(view1, view2); + continueToNextStep(); +} + +function grabFileUsageAndContinueHandler(request) { + testGenerator.next(request.result.fileUsage); +} + +function getCurrentUsage(usageHandler) { + let principal = Cc["@mozilla.org/systemprincipal;1"].createInstance( + Ci.nsIPrincipal + ); + Services.qms.getUsageForPrincipal(principal, usageHandler); +} + +function setTemporaryStorageLimit(limit) { + const pref = "dom.quotaManager.temporaryStorage.fixedLimit"; + if (limit) { + info("Setting temporary storage limit to " + limit); + SpecialPowers.setIntPref(pref, limit); + } else { + info("Removing temporary storage limit"); + SpecialPowers.clearUserPref(pref); + } +} + +function setDataThreshold(threshold) { + info("Setting data threshold to " + threshold); + SpecialPowers.setIntPref("dom.indexedDB.dataThreshold", threshold); +} + +function resetDataThreshold() { + info("Clearing data threshold pref"); + SpecialPowers.clearUserPref("dom.indexedDB.dataThreshold"); +} + +function setMaxSerializedMsgSize(aSize) { + info("Setting maximal size of a serialized message to " + aSize); + SpecialPowers.setIntPref("dom.indexedDB.maxSerializedMsgSize", aSize); +} + +function enablePreprocessing() { + info("Setting preprocessing pref"); + SpecialPowers.setBoolPref("dom.indexedDB.preprocessing", true); +} + +function resetPreprocessing() { + info("Clearing preprocessing pref"); + SpecialPowers.clearUserPref("dom.indexedDB.preprocessing"); +} + +function getSystemPrincipal() { + return Cc["@mozilla.org/systemprincipal;1"].createInstance(Ci.nsIPrincipal); +} + +function getPrincipal(url) { + let uri = Services.io.newURI(url); + return Services.scriptSecurityManager.createContentPrincipal(uri, {}); +} + +class RequestError extends Error { + constructor(resultCode, resultName) { + super(`Request failed (code: ${resultCode}, name: ${resultName})`); + this.name = "RequestError"; + this.resultCode = resultCode; + this.resultName = resultName; + } +} + +async function requestFinished(request) { + await new Promise(function (resolve) { + request.callback = function () { + resolve(); + }; + }); + + if (request.resultCode !== Cr.NS_OK) { + throw new RequestError(request.resultCode, request.resultName); + } + + return request.result; +} + +// TODO: Rename to openDBRequestSucceeded ? +function expectingSuccess(request) { + return new Promise(function (resolve, reject) { + request.onerror = function (event) { + ok(false, "indexedDB error, '" + event.target.error.name + "'"); + reject(event); + }; + request.onsuccess = function (event) { + resolve(event); + }; + request.onupgradeneeded = function (event) { + ok(false, "Got upgrade, but did not expect it!"); + reject(event); + }; + }); +} + +// TODO: Rename to openDBRequestUpgradeNeeded ? +function expectingUpgrade(request) { + return new Promise(function (resolve, reject) { + request.onerror = function (event) { + ok(false, "indexedDB error, '" + event.target.error.name + "'"); + reject(event); + }; + request.onupgradeneeded = function (event) { + resolve(event); + }; + request.onsuccess = function (event) { + ok(false, "Got success, but did not expect it!"); + reject(event); + }; + }); +} + +function requestSucceeded(request) { + return new Promise(function (resolve, reject) { + request.onerror = function (event) { + ok(false, "indexedDB error, '" + event.target.error.name + "'"); + reject(event); + }; + request.onsuccess = function (event) { + resolve(event); + }; + }); +} + +// Given a "/"-delimited path relative to the profile directory, +// return an nsIFile representing the path. This does not test +// for the existence of the file or parent directories. +// It is safe even on Windows where the directory separator is not "/", +// but make sure you're not passing in a "\"-delimited path. +function getRelativeFile(relativePath) { + let profileDir = Services.dirsvc.get("ProfD", Ci.nsIFile); + + let file = profileDir.clone(); + relativePath.split("/").forEach(function (component) { + file.append(component); + }); + + return file; +} + +var SpecialPowers = { + isMainProcess() { + return ( + Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT + ); + }, + notifyObservers(subject, topic, data) { + Services.obs.notifyObservers(subject, topic, data); + }, + notifyObserversInParentProcess(subject, topic, data) { + if (subject) { + throw new Error("Can't send subject to another process!"); + } + return this.notifyObservers(subject, topic, data); + }, + getBoolPref(prefName) { + return Services.prefs.getBoolPref(prefName); + }, + setBoolPref(prefName, value) { + Services.prefs.setBoolPref(prefName, value); + }, + setIntPref(prefName, value) { + Services.prefs.setIntPref(prefName, value); + }, + clearUserPref(prefName) { + Services.prefs.clearUserPref(prefName); + }, + // Copied (and slightly adjusted) from testing/specialpowers/content/SpecialPowersAPI.jsm + exactGC(callback) { + let count = 0; + + function doPreciseGCandCC() { + function scheduledGCCallback() { + Cu.forceCC(); + + if (++count < 3) { + doPreciseGCandCC(); + } else { + callback(); + } + } + + Cu.schedulePreciseGC(scheduledGCCallback); + } + + doPreciseGCandCC(); + }, + + get Cc() { + return Cc; + }, + + get Ci() { + return Ci; + }, + + get Cu() { + return Cu; + }, + + // Based on SpecialPowersObserver.prototype.receiveMessage + createFiles(requests, callback) { + let filePaths = []; + if (!this._createdFiles) { + this._createdFiles = []; + } + let createdFiles = this._createdFiles; + let promises = []; + requests.forEach(function (request) { + const filePerms = 0o666; + let testFile = Services.dirsvc.get("ProfD", Ci.nsIFile); + if (request.name) { + testFile.append(request.name); + } else { + testFile.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, filePerms); + } + let outStream = Cc[ + "@mozilla.org/network/file-output-stream;1" + ].createInstance(Ci.nsIFileOutputStream); + outStream.init( + testFile, + 0x02 | 0x08 | 0x20, // PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE + filePerms, + 0 + ); + if (request.data) { + outStream.write(request.data, request.data.length); + outStream.close(); + } + promises.push( + File.createFromFileName(testFile.path, request.options).then(function ( + file + ) { + filePaths.push(file); + }) + ); + createdFiles.push(testFile); + }); + + Promise.all(promises).then(function () { + setTimeout(function () { + callback(filePaths); + }, 0); + }); + }, + + removeFiles() { + if (this._createdFiles) { + this._createdFiles.forEach(function (testFile) { + try { + testFile.remove(false); + } catch (e) {} + }); + this._createdFiles = null; + } + }, +}; diff --git a/dom/indexedDB/test/unit/xpcshell-parent-process.toml b/dom/indexedDB/test/unit/xpcshell-parent-process.toml new file mode 100644 index 0000000000..d63e3d6bf2 --- /dev/null +++ b/dom/indexedDB/test/unit/xpcshell-parent-process.toml @@ -0,0 +1,104 @@ +[DEFAULT] +dupe-manifest = "" +head = "xpcshell-head-parent-process.js" +tail = "" +support-files = [ + "URLSearchParams_profile.zip", + "bug1056939_profile.zip", + "idbSubdirUpgrade1_profile.zip", + "idbSubdirUpgrade2_profile.zip", + "mutableFileUpgrade_profile.zip", + "obsoleteOriginAttributes_profile.zip", + "orphaned_files_profile.zip", + "oldDirectories_profile.zip", + "GlobalObjectsChild.js", + "GlobalObjectsModule.sys.mjs", + "GlobalObjectsSandbox.js", + "metadata2Restore_profile.zip", + "metadataRestore_profile.zip", + "schema18upgrade_profile.zip", + "schema21upgrade_profile.zip", + "schema23upgrade_profile.zip", + "snappyUpgrade_profile.zip", + "storagePersistentUpgrade_profile.zip", + "wasm_get_values_profile.zip", + "xpcshell-shared.toml", +] + +["include:xpcshell-shared.toml"] + +["make_URLSearchParams.js"] +skip-if = ["true"] # Only used for recreating URLSearchParams_profile.zip + +["test_URLSearchParams.js"] + +["test_bad_origin_directory.js"] + +["test_blob_file_backed.js"] + +["test_bug1056939.js"] + +["test_cleanup_transaction.js"] + +["test_clear_object_store_with_indexes.js"] +requesttimeoutfactor = 2 +skip-if = ["tsan"] + +["test_database_close_without_onclose.js"] + +["test_database_onclose.js"] + +["test_file_copy_failure.js"] + +["test_globalObjects_ipc.js"] +skip-if = ["os == 'android'"] + +["test_idbSubdirUpgrade.js"] + +["test_idle_maintenance.js"] + +["test_invalidate.js"] +# disabled for the moment. +skip-if = ["true"] + +["test_marker_file.js"] + +["test_maximal_serialized_object_size.js"] + +["test_metadata2Restore.js"] + +["test_metadataRestore.js"] + +["test_mutableFileUpgrade.js"] + +["test_obsoleteOriginAttributesUpgrade.js"] + +["test_oldDirectories.js"] + +["test_orphaned_files.js"] + +["test_quotaExceeded_recovery.js"] + +["test_readwriteflush_disabled.js"] + +["test_schema18upgrade.js"] + +["test_schema21upgrade.js"] + +["test_schema23upgrade.js"] + +["test_snappyUpgrade.js"] + +["test_storagePersistentUpgrade.js"] + +["test_temporary_storage.js"] +# bug 951017: intermittent failure on Android x86 emulator +skip-if = ["os == 'android' && processor == 'x86'"] + +["test_unexpectedDirectory.js"] + +["test_view_put_get_values.js"] + +["test_wasm_get_values.js"] + +["test_wasm_put_get_values.js"] diff --git a/dom/indexedDB/test/unit/xpcshell-shared.toml b/dom/indexedDB/test/unit/xpcshell-shared.toml new file mode 100644 index 0000000000..ac1183ab2d --- /dev/null +++ b/dom/indexedDB/test/unit/xpcshell-shared.toml @@ -0,0 +1,183 @@ +[DEFAULT] + +["test_abort_deleted_index.js"] + +["test_abort_deleted_objectStore.js"] + +["test_add_put.js"] + +["test_add_twice_failure.js"] + +["test_advance.js"] + +["test_autoIncrement.js"] + +["test_autoIncrement_indexes.js"] + +["test_blocked_order.js"] + +["test_clear.js"] +skip-if = ["os == 'win' && debug"] # Bug 1785080 + +["test_complex_keyPaths.js"] + +["test_count.js"] + +["test_create_index.js"] + +["test_create_index_with_integer_keys.js"] + +["test_create_locale_aware_index.js"] +skip-if = ["os == 'android'"] # bug 864843 + +["test_create_objectStore.js"] + +["test_cursor_cycle.js"] + +["test_cursor_mutation.js"] + +["test_cursor_update_updates_indexes.js"] + +["test_cursors.js"] + +["test_deleteDatabase.js"] + +["test_deleteDatabase_interactions.js"] + +["test_deleteDatabase_onblocked.js"] + +["test_deleteDatabase_onblocked_duringVersionChange.js"] + +["test_event_source.js"] + +["test_getAll.js"] + +["test_globalObjects_other.js"] +skip-if = ["os == 'android'"] # bug 1079278 + +["test_globalObjects_xpc.js"] + +["test_global_data.js"] + +["test_index_empty_keyPath.js"] + +["test_index_getAll.js"] + +["test_index_getAllObjects.js"] + +["test_index_object_cursors.js"] + +["test_index_update_delete.js"] + +["test_indexes.js"] + +["test_indexes_bad_values.js"] + +["test_indexes_funny_things.js"] + +["test_invalid_cursor.js"] + +["test_invalid_version.js"] + +["test_key_requirements.js"] + +["test_keys.js"] +skip-if = [ + "tsan", # Uncatched OOM crashes + "asan", +] # bug 1796753 + +["test_locale_aware_index_getAll.js"] +skip-if = ["os == 'android'"] # bug 864843 + +["test_locale_aware_index_getAllObjects.js"] +skip-if = ["os == 'android'"] # bug 864843 + +["test_multientry.js"] + +["test_names_sorted.js"] + +["test_objectCursors.js"] + +["test_objectStore_getAllKeys.js"] + +["test_objectStore_inline_autoincrement_key_added_on_put.js"] + +["test_objectStore_openKeyCursor.js"] + +["test_objectStore_remove_values.js"] + +["test_object_identity.js"] + +["test_odd_result_order.js"] + +["test_open_empty_db.js"] + +["test_open_for_principal.js"] + +["test_open_objectStore.js"] + +["test_optionalArguments.js"] + +["test_overlapping_transactions.js"] + +["test_put_get_values.js"] + +["test_put_get_values_autoIncrement.js"] +skip-if = ["verify && debug && os == 'win'"] + +["test_readonly_transactions.js"] + +["test_remove_index.js"] + +["test_remove_objectStore.js"] + +["test_rename_index.js"] + +["test_rename_index_errors.js"] + +["test_rename_objectStore.js"] + +["test_rename_objectStore_errors.js"] + +["test_request_readyState.js"] + +["test_sandbox.js"] + +["test_setVersion.js"] + +["test_setVersion_abort.js"] + +["test_setVersion_events.js"] + +["test_setVersion_exclusion.js"] + +["test_setVersion_throw.js"] + +["test_success_events_after_abort.js"] + +["test_table_locks.js"] + +["test_table_rollback.js"] + +["test_traffic_jam.js"] + +["test_transaction_abort.js"] + +["test_transaction_abort_hang.js"] + +["test_transaction_duplicate_store_names.js"] + +["test_transaction_error.js"] + +["test_transaction_lifetimes.js"] + +["test_transaction_lifetimes_nested.js"] + +["test_transaction_ordering.js"] + +["test_unique_index_update.js"] + +["test_upgrade_add_index.js"] + +["test_writer_starvation.js"] |