Bug 1316500 - remove use of tasks and promise.jsm promises from Sync tests. r=tcsc

MozReview-Commit-ID: 5itPSLBKguc

--HG--
extra : rebase_source : 2b16f697902736ef39cded96c1bd98b547136263
This commit is contained in:
Mark Hammond 2016-11-10 14:34:38 +11:00
parent 92b6927b24
commit 682d81fa5d
32 changed files with 1520 additions and 1730 deletions

View File

@ -16,7 +16,8 @@ this.EXPORTED_SYMBOLS = [
"configureIdentity",
"SyncTestingInfrastructure",
"waitForZeroTimer",
"Promise", // from a module import
"promiseZeroTimer",
"promiseNamedTimer",
"add_identity_test",
"MockFxaStorageManager",
"AccountState", // from a module import
@ -36,7 +37,6 @@ Cu.import("resource://testing-common/services/sync/fakeservices.js");
Cu.import("resource://gre/modules/FxAccounts.jsm");
Cu.import("resource://gre/modules/FxAccountsClient.jsm");
Cu.import("resource://gre/modules/FxAccountsCommon.js");
Cu.import("resource://gre/modules/Promise.jsm");
Cu.import("resource://gre/modules/Services.jsm");
// and grab non-exported stuff via a backstage pass.
@ -96,6 +96,18 @@ this.waitForZeroTimer = function waitForZeroTimer(callback) {
CommonUtils.namedTimer(wait, 150, {}, "timer");
}
this.promiseZeroTimer = function() {
return new Promise(resolve => {
waitForZeroTimer(resolve);
});
}
this.promiseNamedTimer = function(wait, thisObj, name) {
return new Promise(resolve => {
Utils.namedTimer(resolve, wait, thisObj, name);
});
}
/**
* Return true if Sync is configured with the "legacy" identity provider.
*/
@ -237,7 +249,7 @@ this.configureFxAccountIdentity = function(authService,
authService._account = config.fxaccount.user.email;
}
this.configureIdentity = function(identityOverrides) {
this.configureIdentity = async function(identityOverrides) {
let config = makeIdentityConfig(identityOverrides);
let ns = {};
Cu.import("resource://services-sync/service.js", ns);
@ -245,16 +257,13 @@ this.configureIdentity = function(identityOverrides) {
if (ns.Service.identity instanceof BrowserIDManager) {
// do the FxAccounts thang...
configureFxAccountIdentity(ns.Service.identity, config);
return ns.Service.identity.initializeWithCurrentIdentity().then(() => {
// need to wait until this identity manager is readyToAuthenticate.
return ns.Service.identity.whenReadyToAuthenticate.promise;
});
await ns.Service.identity.initializeWithCurrentIdentity();
// need to wait until this identity manager is readyToAuthenticate.
await ns.Service.identity.whenReadyToAuthenticate.promise;
return;
}
// old style identity provider.
setBasicCredentials(config.username, config.sync.password, config.sync.syncKey);
let deferred = Promise.defer();
deferred.resolve();
return deferred.promise;
}
this.SyncTestingInfrastructure = function (server, username, password, syncKey) {
@ -320,19 +329,19 @@ this.add_identity_test = function(test, testFunction) {
let ns = {};
Cu.import("resource://services-sync/service.js", ns);
// one task for the "old" identity manager.
test.add_task(function* () {
test.add_task(async function() {
note("sync");
let oldIdentity = Status._authManager;
ensureLegacyIdentityManager();
yield testFunction();
await testFunction();
Status.__authManager = ns.Service.identity = oldIdentity;
});
// another task for the FxAccounts identity manager.
test.add_task(function* () {
test.add_task(async function() {
note("FxAccounts");
let oldIdentity = Status._authManager;
Status.__authManager = ns.Service.identity = new BrowserIDManager();
yield testFunction();
await testFunction();
Status.__authManager = ns.Service.identity = oldIdentity;
});
}

View File

@ -92,15 +92,11 @@ const EHTestsCommon = {
keys.upload(Service.resource(Service.cryptoKeysURL));
},
setUp(server) {
return configureIdentity({ username: "johndoe" }).then(
() => {
Service.serverURL = server.baseURI + "/";
Service.clusterURL = server.baseURI + "/";
}
).then(
() => EHTestsCommon.generateAndUploadKeys()
);
async setUp(server) {
await configureIdentity({ username: "johndoe" });
Service.serverURL = server.baseURI + "/";
Service.clusterURL = server.baseURI + "/";
return EHTestsCommon.generateAndUploadKeys()
},
generateAndUploadKeys() {

View File

@ -436,6 +436,27 @@ function sync_engine_and_validate_telem(engine, allowErrorPings, onError) {
});
}
// Returns a promise that resolves once the specified observer notification
// has fired.
function promiseOneObserver(topic, callback) {
return new Promise((resolve, reject) => {
let observer = function(subject, data) {
Svc.Obs.remove(topic, observer);
resolve({ subject: subject, data: data });
}
Svc.Obs.add(topic, observer)
});
}
function promiseStopServer(server) {
return new Promise(resolve => server.stop(resolve));
}
function promiseNextTick() {
return new Promise(resolve => {
Utils.nextTick(resolve);
});
}
// Avoid an issue where `client.name2` containing unicode characters causes
// a number of tests to fail, due to them assuming that we do not need to utf-8
// encode or decode data sent through the mocked server (see bug 1268912).

View File

@ -23,16 +23,6 @@ const store = engine._store;
store._log.level = Log.Level.Trace;
engine._log.level = Log.Level.Trace;
function promiseOneObserver(topic) {
return new Promise((resolve, reject) => {
let observer = function(subject, topic, data) {
Services.obs.removeObserver(observer, topic);
resolve({ subject: subject, data: data });
}
Services.obs.addObserver(observer, topic, false);
});
}
function setup() {
let server = serverForUsers({"foo": "password"}, {
meta: {global: {engines: {bookmarks: {version: engine.version,
@ -51,14 +41,14 @@ function setup() {
return { server, collection };
}
function* cleanup(server) {
async function cleanup(server) {
Svc.Obs.notify("weave:engine:stop-tracking");
Services.prefs.setBoolPref("services.sync-testing.startOverKeepIdentity", true);
let promiseStartOver = promiseOneObserver("weave:service:start-over:finish");
Service.startOver();
yield promiseStartOver;
yield new Promise(resolve => server.stop(resolve));
yield bms.eraseEverything();
await promiseStartOver;
await promiseStopServer(server);
await bms.eraseEverything();
}
function getFolderChildrenIDs(folderId) {
@ -94,15 +84,15 @@ function getServerRecord(collection, id) {
return JSON.parse(JSON.parse(JSON.parse(wbo).payload).ciphertext);
}
function* promiseNoLocalItem(guid) {
async function promiseNoLocalItem(guid) {
// Check there's no item with the specified guid.
let got = yield bms.fetch({ guid });
let got = await bms.fetch({ guid });
ok(!got, `No record remains with GUID ${guid}`);
// and while we are here ensure the places cache doesn't still have it.
yield Assert.rejects(PlacesUtils.promiseItemId(guid));
await Assert.rejects(PlacesUtils.promiseItemId(guid));
}
function* validate(collection, expectedFailures = []) {
async function validate(collection, expectedFailures = []) {
let validator = new BookmarkValidator();
let records = collection.payloads();
@ -131,13 +121,13 @@ function* validate(collection, expectedFailures = []) {
do_print(JSON.stringify(problems, undefined, 2));
// All server records and the entire bookmark tree.
do_print("Server records:\n" + JSON.stringify(collection.payloads(), undefined, 2));
let tree = yield PlacesUtils.promiseBookmarksTree("", { includeItemIds: true });
let tree = await PlacesUtils.promiseBookmarksTree("", { includeItemIds: true });
do_print("Local bookmark tree:\n" + JSON.stringify(tree, undefined, 2));
ok(false);
}
}
add_task(function* test_dupe_bookmark() {
add_task(async function test_dupe_bookmark() {
_("Ensure that a bookmark we consider a dupe is handled correctly.");
let { server, collection } = this.setup();
@ -173,7 +163,7 @@ add_task(function* test_dupe_bookmark() {
equal(collection.count(), 7);
ok(getServerRecord(collection, bmk1_guid).deleted);
// and physically removed from the local store.
yield promiseNoLocalItem(bmk1_guid);
await promiseNoLocalItem(bmk1_guid);
// Parent should still only have 1 item.
equal(getFolderChildrenIDs(folder1_id).length, 1);
// The parent record on the server should now reference the new GUID and not the old.
@ -182,13 +172,13 @@ add_task(function* test_dupe_bookmark() {
ok(serverRecord.children.includes(newGUID));
// and a final sanity check - use the validator
yield validate(collection);
await validate(collection);
} finally {
yield cleanup(server);
await cleanup(server);
}
});
add_task(function* test_dupe_reparented_bookmark() {
add_task(async function test_dupe_reparented_bookmark() {
_("Ensure that a bookmark we consider a dupe from a different parent is handled correctly");
let { server, collection } = this.setup();
@ -231,7 +221,7 @@ add_task(function* test_dupe_reparented_bookmark() {
equal(collection.count(), 8);
ok(getServerRecord(collection, bmk1_guid).deleted);
// and physically removed from the local store.
yield promiseNoLocalItem(bmk1_guid);
await promiseNoLocalItem(bmk1_guid);
// The original folder no longer has the item
equal(getFolderChildrenIDs(folder1_id).length, 0);
// But the second dupe folder does.
@ -248,13 +238,13 @@ add_task(function* test_dupe_reparented_bookmark() {
ok(serverRecord2.children.includes(newGUID));
// and a final sanity check - use the validator
yield validate(collection);
await validate(collection);
} finally {
yield cleanup(server);
await cleanup(server);
}
});
add_task(function* test_dupe_reparented_locally_changed_bookmark() {
add_task(async function test_dupe_reparented_locally_changed_bookmark() {
_("Ensure that a bookmark with local changes we consider a dupe from a different parent is handled correctly");
let { server, collection } = this.setup();
@ -293,7 +283,7 @@ add_task(function* test_dupe_reparented_locally_changed_bookmark() {
// time further in the future than the incoming record. This will cause
// us to issue the infamous "DATA LOSS" warning in the logs but cause us
// to *not* apply the incoming record.
yield PlacesTestUtils.setBookmarkSyncFields({
await PlacesTestUtils.setBookmarkSyncFields({
guid: bmk1_guid,
syncChangeCounter: 1,
lastModified: Date.now() + 60000,
@ -307,7 +297,7 @@ add_task(function* test_dupe_reparented_locally_changed_bookmark() {
equal(collection.count(), 8);
ok(getServerRecord(collection, bmk1_guid).deleted);
// and physically removed from the local store.
yield promiseNoLocalItem(bmk1_guid);
await promiseNoLocalItem(bmk1_guid);
// The original folder still longer has the item
equal(getFolderChildrenIDs(folder1_id).length, 1);
// The second folder does not.
@ -324,13 +314,13 @@ add_task(function* test_dupe_reparented_locally_changed_bookmark() {
ok(!serverRecord2.children.includes(newGUID));
// and a final sanity check - use the validator
yield validate(collection);
await validate(collection);
} finally {
yield cleanup(server);
await cleanup(server);
}
});
add_task(function* test_dupe_reparented_to_earlier_appearing_parent_bookmark() {
add_task(async function test_dupe_reparented_to_earlier_appearing_parent_bookmark() {
_("Ensure that a bookmark we consider a dupe from a different parent that " +
"appears in the same sync before the dupe item");
@ -401,13 +391,13 @@ add_task(function* test_dupe_reparented_to_earlier_appearing_parent_bookmark() {
deepEqual(getFolderChildrenIDs(newParentID), [newID]);
// Make sure the validator thinks everything is hunky-dory.
yield validate(collection);
await validate(collection);
} finally {
yield cleanup(server);
await cleanup(server);
}
});
add_task(function* test_dupe_reparented_to_later_appearing_parent_bookmark() {
add_task(async function test_dupe_reparented_to_later_appearing_parent_bookmark() {
_("Ensure that a bookmark we consider a dupe from a different parent that " +
"doesn't exist locally as we process the child, but does appear in the same sync");
@ -478,13 +468,13 @@ add_task(function* test_dupe_reparented_to_later_appearing_parent_bookmark() {
deepEqual(getFolderChildrenIDs(newParentID), [newID]);
// Make sure the validator thinks everything is hunky-dory.
yield validate(collection);
await validate(collection);
} finally {
yield cleanup(server);
await cleanup(server);
}
});
add_task(function* test_dupe_reparented_to_future_arriving_parent_bookmark() {
add_task(async function test_dupe_reparented_to_future_arriving_parent_bookmark() {
_("Ensure that a bookmark we consider a dupe from a different parent that " +
"doesn't exist locally and doesn't appear in this Sync is handled correctly");
@ -529,7 +519,7 @@ add_task(function* test_dupe_reparented_to_future_arriving_parent_bookmark() {
equal(collection.count(), 8);
ok(getServerRecord(collection, bmk1_guid).deleted);
// and physically removed from the local store.
yield promiseNoLocalItem(bmk1_guid);
await promiseNoLocalItem(bmk1_guid);
// The intended parent doesn't exist, so it remains in the original folder
equal(getFolderChildrenIDs(folder1_id).length, 1);
@ -549,7 +539,7 @@ add_task(function* test_dupe_reparented_to_future_arriving_parent_bookmark() {
// We haven't fixed the incoming record that referenced the missing parent.
{ name: "orphans", count: 1 },
];
yield validate(collection, expected);
await validate(collection, expected);
// Now have the parent magically appear in a later sync - but
// it appears as being in a different parent from our existing "Folder 1",
@ -597,14 +587,14 @@ add_task(function* test_dupe_reparented_to_future_arriving_parent_bookmark() {
// Hence, newGUID is a child of both those server records :(
{ name: "multipleParents", count: 1 },
];
yield validate(collection, expected);
await validate(collection, expected);
} finally {
yield cleanup(server);
await cleanup(server);
}
});
add_task(function* test_dupe_empty_folder() {
add_task(async function test_dupe_empty_folder() {
_("Ensure that an empty folder we consider a dupe is handled correctly.");
// Empty folders aren't particularly interesting in practice (as that seems
// an edge-case) but duping folders with items is broken - bug 1293163.
@ -634,15 +624,15 @@ add_task(function* test_dupe_empty_folder() {
engine.lastSync = engine.lastSync - 0.01;
engine.sync();
yield validate(collection);
await validate(collection);
// Collection now has one additional record - the logically deleted dupe.
equal(collection.count(), 6);
// original folder should be logically deleted.
ok(getServerRecord(collection, folder1_guid).deleted);
yield promiseNoLocalItem(folder1_guid);
await promiseNoLocalItem(folder1_guid);
} finally {
yield cleanup(server);
await cleanup(server);
}
});
// XXX - TODO - folders with children. Bug 1293163

View File

@ -11,21 +11,20 @@ Cu.import("resource://services-sync/engines/bookmarks.js");
Cu.import("resource://services-sync/service.js");
Cu.import("resource://services-sync/util.js");
Cu.import("resource://testing-common/services/sync/utils.js");
Cu.import("resource://gre/modules/Promise.jsm");
initTestLogging("Trace");
Service.engineManager.register(BookmarksEngine);
function* assertChildGuids(folderGuid, expectedChildGuids, message) {
let tree = yield PlacesUtils.promiseBookmarksTree(folderGuid);
async function assertChildGuids(folderGuid, expectedChildGuids, message) {
let tree = await PlacesUtils.promiseBookmarksTree(folderGuid);
let childGuids = tree.children.map(child => child.guid);
deepEqual(childGuids, expectedChildGuids, message);
}
function* fetchAllSyncIds() {
let db = yield PlacesUtils.promiseDBConnection();
let rows = yield db.executeCached(`
async function fetchAllSyncIds() {
let db = await PlacesUtils.promiseDBConnection();
let rows = await db.executeCached(`
WITH RECURSIVE
syncedItems(id, guid) AS (
SELECT b.id, b.guid FROM moz_bookmarks b
@ -45,7 +44,7 @@ function* fetchAllSyncIds() {
return syncIds;
}
add_task(function* test_delete_invalid_roots_from_server() {
add_task(async function test_delete_invalid_roots_from_server() {
_("Ensure that we delete the Places and Reading List roots from the server.");
let engine = new BookmarksEngine(Service);
@ -85,7 +84,7 @@ add_task(function* test_delete_invalid_roots_from_server() {
deepEqual(collection.keys().sort(), ["places", "readinglist", listBmk.id, newBmk.id].sort(),
"Should store Places root, reading list items, and new bookmark on server");
yield sync_engine_and_validate_telem(engine, false);
await sync_engine_and_validate_telem(engine, false);
ok(!store.itemExists("readinglist"), "Should not apply Reading List root");
ok(!store.itemExists(listBmk.id), "Should not apply items in Reading List");
@ -97,12 +96,12 @@ add_task(function* test_delete_invalid_roots_from_server() {
store.wipe();
Svc.Prefs.resetBranch("");
Service.recordManager.clearCache();
yield new Promise(resolve => server.stop(resolve));
await promiseStopServer(server);
Svc.Obs.notify("weave:engine:stop-tracking");
}
});
add_task(function* test_change_during_sync() {
add_task(async function test_change_during_sync() {
_("Ensure that we track changes made during a sync.");
let engine = new BookmarksEngine(Service);
@ -116,10 +115,10 @@ add_task(function* test_change_during_sync() {
let bz_id = PlacesUtils.bookmarks.insertBookmark(
PlacesUtils.bookmarksMenuFolderId, Utils.makeURI("https://bugzilla.mozilla.org/"),
PlacesUtils.bookmarks.DEFAULT_INDEX, "Bugzilla");
let bz_guid = yield PlacesUtils.promiseItemGuid(bz_id);
let bz_guid = await PlacesUtils.promiseItemGuid(bz_id);
_(`Bugzilla GUID: ${bz_guid}`);
yield PlacesTestUtils.markBookmarksAsSynced();
await PlacesTestUtils.markBookmarksAsSynced();
Svc.Obs.notify("weave:engine:start-tracking");
try {
@ -199,14 +198,14 @@ add_task(function* test_change_during_sync() {
collection.insert(bmk4_guid, encryptPayload(localTaggedBmk.cleartext));
}
yield* assertChildGuids(folder1_guid, [bmk1_guid], "Folder should have 1 child before first sync");
await assertChildGuids(folder1_guid, [bmk1_guid], "Folder should have 1 child before first sync");
_("Perform first sync");
{
let changes = engine.pullNewChanges();
deepEqual(changes.ids().sort(), [folder1_guid, bmk1_guid, "toolbar"].sort(),
"Should track bookmark and folder created before first sync");
yield sync_engine_and_validate_telem(engine, false);
await sync_engine_and_validate_telem(engine, false);
}
let bmk2_id = store.idForGUID(bmk2_guid);
@ -220,9 +219,9 @@ add_task(function* test_change_during_sync() {
ok(!collection.wbo(bmk3_guid),
"Bookmark created during first sync shouldn't be uploaded yet");
yield* assertChildGuids(folder1_guid, [bmk1_guid, bmk3_guid, bmk2_guid],
await assertChildGuids(folder1_guid, [bmk1_guid, bmk3_guid, bmk2_guid],
"Folder 1 should have 3 children after first sync");
yield* assertChildGuids(folder2_guid, [bmk4_guid, tagQuery_guid],
await assertChildGuids(folder2_guid, [bmk4_guid, tagQuery_guid],
"Folder 2 should have 2 children after first sync");
let taggedURIs = PlacesUtils.tagging.getURIsForTag("taggy");
equal(taggedURIs.length, 1, "Should have 1 tagged URI");
@ -235,26 +234,26 @@ add_task(function* test_change_during_sync() {
let changes = engine.pullNewChanges();
deepEqual(changes.ids().sort(), [bmk3_guid, folder1_guid].sort(),
"Should track bookmark added during last sync and its parent");
yield sync_engine_and_validate_telem(engine, false);
await sync_engine_and_validate_telem(engine, false);
ok(collection.wbo(bmk3_guid),
"Bookmark created during first sync should be uploaded during second sync");
yield* assertChildGuids(folder1_guid, [bmk1_guid, bmk3_guid, bmk2_guid],
await assertChildGuids(folder1_guid, [bmk1_guid, bmk3_guid, bmk2_guid],
"Folder 1 should have same children after second sync");
yield* assertChildGuids(folder2_guid, [bmk4_guid, tagQuery_guid],
await assertChildGuids(folder2_guid, [bmk4_guid, tagQuery_guid],
"Folder 2 should have same children after second sync");
}
} finally {
store.wipe();
Svc.Prefs.resetBranch("");
Service.recordManager.clearCache();
yield new Promise(resolve => server.stop(resolve));
await promiseStopServer(server);
Svc.Obs.notify("weave:engine:stop-tracking");
}
});
add_task(function* bad_record_allIDs() {
add_task(async function bad_record_allIDs() {
let server = new SyncServer();
server.start();
let syncTesting = new SyncTestingInfrastructure(server.server);
@ -273,7 +272,7 @@ add_task(function* bad_record_allIDs() {
_("Type: " + PlacesUtils.bookmarks.getItemType(badRecordID));
_("Fetching all IDs.");
let all = yield* fetchAllSyncIds();
let all = await fetchAllSyncIds();
_("All IDs: " + JSON.stringify([...all]));
do_check_true(all.has("menu"));
@ -281,8 +280,8 @@ add_task(function* bad_record_allIDs() {
_("Clean up.");
PlacesUtils.bookmarks.removeItem(badRecordID);
yield PlacesSyncUtils.bookmarks.reset();
yield new Promise(r => server.stop(r));
await PlacesSyncUtils.bookmarks.reset();
await promiseStopServer(server);
});
function serverForFoo(engine) {
@ -293,7 +292,7 @@ function serverForFoo(engine) {
});
}
add_task(function* test_processIncoming_error_orderChildren() {
add_task(async function test_processIncoming_error_orderChildren() {
_("Ensure that _orderChildren() is called even when _processIncoming() throws an error.");
let engine = new BookmarksEngine(Service);
@ -340,7 +339,7 @@ add_task(function* test_processIncoming_error_orderChildren() {
let error;
try {
yield sync_engine_and_validate_telem(engine, true)
await sync_engine_and_validate_telem(engine, true)
} catch(ex) {
error = ex;
}
@ -359,12 +358,12 @@ add_task(function* test_processIncoming_error_orderChildren() {
store.wipe();
Svc.Prefs.resetBranch("");
Service.recordManager.clearCache();
yield PlacesSyncUtils.bookmarks.reset();
yield new Promise(resolve => server.stop(resolve));
await PlacesSyncUtils.bookmarks.reset();
await promiseStopServer(server);
}
});
add_task(function* test_restorePromptsReupload() {
add_task(async function test_restorePromptsReupload() {
_("Ensure that restoring from a backup will reupload all records.");
let engine = new BookmarksEngine(Service);
let store = engine._store;
@ -401,7 +400,7 @@ add_task(function* test_restorePromptsReupload() {
backupFile.append("t_b_e_" + Date.now() + ".json");
_("Backing up to file " + backupFile.path);
yield BookmarkJSONUtils.exportToFile(backupFile.path);
await BookmarkJSONUtils.exportToFile(backupFile.path);
_("Create a different record and sync.");
let bmk2_id = PlacesUtils.bookmarks.insertBookmark(
@ -413,7 +412,7 @@ add_task(function* test_restorePromptsReupload() {
let error;
try {
yield sync_engine_and_validate_telem(engine, false);
await sync_engine_and_validate_telem(engine, false);
} catch(ex) {
error = ex;
_("Got error: " + Log.exceptionStr(ex));
@ -429,10 +428,10 @@ add_task(function* test_restorePromptsReupload() {
do_check_eq(wbos[0], bmk2_guid);
_("Now restore from a backup.");
yield BookmarkJSONUtils.importFromFile(backupFile, true);
await BookmarkJSONUtils.importFromFile(backupFile, true);
_("Ensure we have the bookmarks we expect locally.");
let guids = yield* fetchAllSyncIds();
let guids = await fetchAllSyncIds();
_("GUIDs: " + JSON.stringify([...guids]));
let found = false;
let count = 0;
@ -457,7 +456,7 @@ add_task(function* test_restorePromptsReupload() {
_("Sync again. This'll wipe bookmarks from the server.");
try {
yield sync_engine_and_validate_telem(engine, false);
await sync_engine_and_validate_telem(engine, false);
} catch(ex) {
error = ex;
_("Got error: " + Log.exceptionStr(ex));
@ -491,8 +490,8 @@ add_task(function* test_restorePromptsReupload() {
store.wipe();
Svc.Prefs.resetBranch("");
Service.recordManager.clearCache();
yield PlacesSyncUtils.bookmarks.reset();
yield new Promise(r => server.stop(r));
await PlacesSyncUtils.bookmarks.reset();
await promiseStopServer(server);
}
});
@ -506,7 +505,7 @@ function FakeRecord(constructor, r) {
}
// Bug 632287.
add_task(function* test_mismatched_types() {
add_task(async function test_mismatched_types() {
_("Ensure that handling a record that changes type causes deletion " +
"then re-adding.");
@ -571,12 +570,12 @@ add_task(function* test_mismatched_types() {
store.wipe();
Svc.Prefs.resetBranch("");
Service.recordManager.clearCache();
yield PlacesSyncUtils.bookmarks.reset();
yield new Promise(r => server.stop(r));
await PlacesSyncUtils.bookmarks.reset();
await promiseStopServer(server);
}
});
add_task(function* test_bookmark_guidMap_fail() {
add_task(async function test_bookmark_guidMap_fail() {
_("Ensure that failures building the GUID map cause early death.");
let engine = new BookmarksEngine(Service);
@ -625,11 +624,11 @@ add_task(function* test_bookmark_guidMap_fail() {
do_check_eq(err, "Nooo");
PlacesUtils.promiseBookmarksTree = pbt;
yield PlacesSyncUtils.bookmarks.reset();
yield new Promise(r => server.stop(r));
await PlacesSyncUtils.bookmarks.reset();
await promiseStopServer(server);
});
add_task(function* test_bookmark_tag_but_no_uri() {
add_task(async function test_bookmark_tag_but_no_uri() {
_("Ensure that a bookmark record with tags, but no URI, doesn't throw an exception.");
let engine = new BookmarksEngine(Service);
@ -638,21 +637,21 @@ add_task(function* test_bookmark_tag_but_no_uri() {
// We're simply checking that no exception is thrown, so
// no actual checks in this test.
yield PlacesSyncUtils.bookmarks.insert({
await PlacesSyncUtils.bookmarks.insert({
kind: PlacesSyncUtils.bookmarks.KINDS.BOOKMARK,
syncId: Utils.makeGUID(),
parentSyncId: "toolbar",
url: "http://example.com",
tags: ["foo"],
});
yield PlacesSyncUtils.bookmarks.insert({
await PlacesSyncUtils.bookmarks.insert({
kind: PlacesSyncUtils.bookmarks.KINDS.BOOKMARK,
syncId: Utils.makeGUID(),
parentSyncId: "toolbar",
url: "http://example.org",
tags: null,
});
yield PlacesSyncUtils.bookmarks.insert({
await PlacesSyncUtils.bookmarks.insert({
kind: PlacesSyncUtils.bookmarks.KINDS.BOOKMARK,
syncId: Utils.makeGUID(),
url: "about:fake",
@ -674,7 +673,7 @@ add_task(function* test_bookmark_tag_but_no_uri() {
store.update(record);
});
add_task(function* test_misreconciled_root() {
add_task(async function test_misreconciled_root() {
_("Ensure that we don't reconcile an arbitrary record with a root.");
let engine = new BookmarksEngine(Service);
@ -738,8 +737,8 @@ add_task(function* test_misreconciled_root() {
do_check_eq(parentGUIDBefore, parentGUIDAfter);
do_check_eq(parentIDBefore, parentIDAfter);
yield PlacesSyncUtils.bookmarks.reset();
yield new Promise(r => server.stop(r));
await PlacesSyncUtils.bookmarks.reset();
await promiseStopServer(server);
});
function run_test() {

View File

@ -1,6 +1,5 @@
Cu.import("resource://gre/modules/PlacesUtils.jsm");
Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://services-sync/engines.js");
Cu.import("resource://services-sync/engines/bookmarks.js");
Cu.import("resource://services-sync/service.js");
@ -12,7 +11,7 @@ var engine = Service.engineManager.get("bookmarks");
var store = engine._store;
var tracker = engine._tracker;
add_task(function* test_ignore_invalid_uri() {
add_task(async function test_ignore_invalid_uri() {
_("Ensure that we don't die with invalid bookmarks.");
// First create a valid bookmark.
@ -22,20 +21,20 @@ add_task(function* test_ignore_invalid_uri() {
"the title");
// Now update moz_places with an invalid url.
yield PlacesUtils.withConnectionWrapper("test_ignore_invalid_uri", Task.async(function* (db) {
yield db.execute(
await PlacesUtils.withConnectionWrapper("test_ignore_invalid_uri", async function(db) {
await db.execute(
`UPDATE moz_places SET url = :url, url_hash = hash(:url)
WHERE id = (SELECT b.fk FROM moz_bookmarks b
WHERE b.id = :id LIMIT 1)`,
{ id: bmid, url: "<invalid url>" });
}));
});
// Ensure that this doesn't throw even though the DB is now in a bad state (a
// bookmark has an illegal url).
engine._buildGUIDMap();
});
add_task(function* test_ignore_missing_uri() {
add_task(async function test_ignore_missing_uri() {
_("Ensure that we don't die with a bookmark referencing an invalid bookmark id.");
// First create a valid bookmark.
@ -45,12 +44,12 @@ add_task(function* test_ignore_missing_uri() {
"the title");
// Now update moz_bookmarks to reference a non-existing places ID
yield PlacesUtils.withConnectionWrapper("test_ignore_missing_uri", Task.async(function* (db) {
yield db.execute(
await PlacesUtils.withConnectionWrapper("test_ignore_missing_uri", async function(db) {
await db.execute(
`UPDATE moz_bookmarks SET fk = 999999
WHERE id = :id`
, { id: bmid });
}));
});
// Ensure that this doesn't throw even though the DB is now in a bad state (a
// bookmark has an illegal url).

View File

@ -3,13 +3,12 @@
_("Making sure after processing incoming bookmarks, they show up in the right order");
Cu.import("resource://gre/modules/PlacesUtils.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://services-sync/engines/bookmarks.js");
Cu.import("resource://services-sync/service.js");
Cu.import("resource://services-sync/util.js");
var check = Task.async(function* (expected, message) {
let root = yield PlacesUtils.promiseBookmarksTree();
var check = async function(expected, message) {
let root = await PlacesUtils.promiseBookmarksTree();
let bookmarks = (function mapTree(children) {
return children.map(child => {
@ -34,15 +33,15 @@ var check = Task.async(function* (expected, message) {
_("Checking if the bookmark structure is", JSON.stringify(expected));
_("Got bookmarks:", JSON.stringify(bookmarks));
deepEqual(bookmarks, expected);
});
};
add_task(function* test_bookmark_order() {
add_task(async function test_bookmark_order() {
let store = new BookmarksEngine(Service)._store;
initTestLogging("Trace");
_("Starting with a clean slate of no bookmarks");
store.wipe();
yield check([{
await check([{
guid: PlacesUtils.bookmarks.menuGuid,
index: 0,
}, {
@ -86,7 +85,7 @@ add_task(function* test_bookmark_order() {
let id10 = "10_aaaaaaaaa";
_("basic add first bookmark");
apply(bookmark(id10, ""));
yield check([{
await check([{
guid: PlacesUtils.bookmarks.menuGuid,
index: 0,
}, {
@ -106,7 +105,7 @@ add_task(function* test_bookmark_order() {
let id20 = "20_aaaaaaaaa";
_("basic append behind 10");
apply(bookmark(id20, ""));
yield check([{
await check([{
guid: PlacesUtils.bookmarks.menuGuid,
index: 0,
}, {
@ -133,7 +132,7 @@ add_task(function* test_bookmark_order() {
apply(bookmark(id31, id30));
let f30 = folder(id30, "", [id31]);
apply(f30);
yield check([{
await check([{
guid: PlacesUtils.bookmarks.menuGuid,
index: 0,
}, {
@ -165,7 +164,7 @@ add_task(function* test_bookmark_order() {
let id40 = "f40_aaaaaaaa";
_("insert missing parent -> append to unfiled");
apply(bookmark(id41, id40));
yield check([{
await check([{
guid: PlacesUtils.bookmarks.menuGuid,
index: 0,
}, {
@ -201,7 +200,7 @@ add_task(function* test_bookmark_order() {
_("insert another missing parent -> append");
apply(bookmark(id42, id40));
yield check([{
await check([{
guid: PlacesUtils.bookmarks.menuGuid,
index: 0,
}, {
@ -240,7 +239,7 @@ add_task(function* test_bookmark_order() {
_("insert folder -> move children and followers");
let f40 = folder(id40, "", [id41, id42]);
apply(f40);
yield check([{
await check([{
guid: PlacesUtils.bookmarks.menuGuid,
index: 0,
}, {
@ -281,7 +280,7 @@ add_task(function* test_bookmark_order() {
_("Moving 41 behind 42 -> update f40");
f40.children = [id42, id41];
apply(f40);
yield check([{
await check([{
guid: PlacesUtils.bookmarks.menuGuid,
index: 0,
}, {
@ -322,7 +321,7 @@ add_task(function* test_bookmark_order() {
_("Moving 10 back to front -> update 10, 20");
f40.children = [id41, id42];
apply(f40);
yield check([{
await check([{
guid: PlacesUtils.bookmarks.menuGuid,
index: 0,
}, {
@ -362,7 +361,7 @@ add_task(function* test_bookmark_order() {
_("Moving 20 behind 42 in f40 -> update 50");
apply(bookmark(id20, id40));
yield check([{
await check([{
guid: PlacesUtils.bookmarks.menuGuid,
index: 0,
}, {
@ -404,7 +403,7 @@ add_task(function* test_bookmark_order() {
apply(bookmark(id10, id30));
f30.children = [id10, id31];
apply(f30);
yield check([{
await check([{
guid: PlacesUtils.bookmarks.menuGuid,
index: 0,
}, {
@ -446,7 +445,7 @@ add_task(function* test_bookmark_order() {
apply(bookmark(id20, id30));
f30.children = [id10, id20, id31];
apply(f30);
yield check([{
await check([{
guid: PlacesUtils.bookmarks.menuGuid,
index: 0,
}, {
@ -488,7 +487,7 @@ add_task(function* test_bookmark_order() {
apply(bookmark(id20, ""));
f30.children = [id10, id31];
apply(f30);
yield check([{
await check([{
guid: PlacesUtils.bookmarks.menuGuid,
index: 0,
}, {

View File

@ -57,7 +57,7 @@ function serverForFoo(engine) {
// Verify that Places smart bookmarks have their annotation uploaded and
// handled locally.
add_task(function *test_annotation_uploaded() {
add_task(async function test_annotation_uploaded() {
let server = serverForFoo(engine);
new SyncTestingInfrastructure(server.server);
@ -110,7 +110,7 @@ add_task(function *test_annotation_uploaded() {
let collection = server.user("foo").collection("bookmarks");
try {
yield sync_engine_and_validate_telem(engine, false);
await sync_engine_and_validate_telem(engine, false);
let wbos = collection.keys(function (id) {
return ["menu", "toolbar", "mobile", "unfiled"].indexOf(id) == -1;
});
@ -141,7 +141,7 @@ add_task(function *test_annotation_uploaded() {
do_check_eq(smartBookmarkCount(), startCount);
_("Sync. Verify that the downloaded record carries the annotation.");
yield sync_engine_and_validate_telem(engine, false);
await sync_engine_and_validate_telem(engine, false);
_("Verify that the Places DB now has an annotated bookmark.");
_("Our count has increased again.");

View File

@ -21,7 +21,7 @@ tracker.persistChangedIDs = false;
var fxuri = Utils.makeURI("http://getfirefox.com/");
var tburi = Utils.makeURI("http://getthunderbird.com/");
add_task(function* test_ignore_specials() {
add_task(async function test_ignore_specials() {
_("Ensure that we can't delete bookmark roots.");
// Belt...
@ -30,7 +30,7 @@ add_task(function* test_ignore_specials() {
do_check_neq(null, store.idForGUID("toolbar"));
store.applyIncoming(record);
yield store.deletePending();
await store.deletePending();
// Ensure that the toolbar exists.
do_check_neq(null, store.idForGUID("toolbar"));
@ -40,7 +40,7 @@ add_task(function* test_ignore_specials() {
// Braces...
store.remove(record);
yield store.deletePending();
await store.deletePending();
do_check_neq(null, store.idForGUID("toolbar"));
engine._buildGUIDMap();
@ -244,7 +244,7 @@ add_test(function test_folder_createRecord() {
}
});
add_task(function* test_deleted() {
add_task(async function test_deleted() {
try {
_("Create a bookmark that will be deleted.");
let bmk1_id = PlacesUtils.bookmarks.insertBookmark(
@ -256,7 +256,7 @@ add_task(function* test_deleted() {
let record = new PlacesItem("bookmarks", bmk1_guid);
record.deleted = true;
store.applyIncoming(record);
yield store.deletePending();
await store.deletePending();
_("Ensure it has been deleted.");
let error;
try {
@ -438,9 +438,9 @@ function assertDeleted(id) {
equal(error.result, Cr.NS_ERROR_ILLEGAL_VALUE)
}
add_task(function* test_delete_buffering() {
add_task(async function test_delete_buffering() {
store.wipe();
yield PlacesTestUtils.markBookmarksAsSynced();
await PlacesTestUtils.markBookmarksAsSynced();
try {
_("Create a folder with two bookmarks.");
@ -510,7 +510,7 @@ add_task(function* test_delete_buffering() {
ok(!store._itemsToDelete.has(tbRecord.id));
_("Process pending deletions and ensure that the right things are deleted.");
let newChangeRecords = yield store.deletePending();
let newChangeRecords = await store.deletePending();
deepEqual(Object.keys(newChangeRecords).sort(), ["get-tndrbrd1", "toolbar"]);

File diff suppressed because it is too large Load Diff

View File

@ -318,13 +318,13 @@ function validationPing(server, client, duration) {
}, true); // Allow "failing" pings, since having validation info indicates failure.
}
add_task(function *test_telemetry_integration() {
add_task(async function test_telemetry_integration() {
let {server, client} = getDummyServerAndClient();
// remove "c"
server.pop();
server[0].children.pop();
const duration = 50;
let ping = yield validationPing(server, client, duration);
let ping = await validationPing(server, client, duration);
ok(ping.engines);
let bme = ping.engines.find(e => e.name === "bookmarks");
ok(bme);

View File

@ -77,17 +77,17 @@ add_test(function test_initial_state() {
}
);
add_task(function* test_initialializeWithCurrentIdentity() {
add_task(async function test_initialializeWithCurrentIdentity() {
_("Verify start after initializeWithCurrentIdentity");
browseridManager.initializeWithCurrentIdentity();
yield browseridManager.whenReadyToAuthenticate.promise;
await browseridManager.whenReadyToAuthenticate.promise;
do_check_true(!!browseridManager._token);
do_check_true(browseridManager.hasValidToken());
do_check_eq(browseridManager.account, identityConfig.fxaccount.user.email);
}
);
add_task(function* test_initialializeWithAuthErrorAndDeletedAccount() {
add_task(async function test_initialializeWithAuthErrorAndDeletedAccount() {
_("Verify sync unpair after initializeWithCurrentIdentity with auth error + account deleted");
var identityConfig = makeIdentityConfig();
@ -125,8 +125,8 @@ add_task(function* test_initialializeWithAuthErrorAndDeletedAccount() {
let mockFxAClient = new MockFxAccountsClient();
browseridManager._fxaService.internal._fxAccountsClient = mockFxAClient;
yield browseridManager.initializeWithCurrentIdentity();
yield Assert.rejects(browseridManager.whenReadyToAuthenticate.promise,
await browseridManager.initializeWithCurrentIdentity();
await Assert.rejects(browseridManager.whenReadyToAuthenticate.promise,
"should reject due to an auth error");
do_check_true(signCertificateCalled);
@ -137,7 +137,7 @@ add_task(function* test_initialializeWithAuthErrorAndDeletedAccount() {
do_check_false(browseridManager.account);
});
add_task(function* test_initialializeWithNoKeys() {
add_task(async function test_initialializeWithNoKeys() {
_("Verify start after initializeWithCurrentIdentity without kA, kB or keyFetchToken");
let identityConfig = makeIdentityConfig();
delete identityConfig.fxaccount.user.kA;
@ -145,8 +145,8 @@ add_task(function* test_initialializeWithNoKeys() {
// there's no keyFetchToken by default, so the initialize should fail.
configureFxAccountIdentity(browseridManager, identityConfig);
yield browseridManager.initializeWithCurrentIdentity();
yield browseridManager.whenReadyToAuthenticate.promise;
await browseridManager.initializeWithCurrentIdentity();
await browseridManager.whenReadyToAuthenticate.promise;
do_check_eq(Status.login, LOGIN_SUCCEEDED, "login succeeded even without keys");
do_check_false(browseridManager._canFetchKeys(), "_canFetchKeys reflects lack of keys");
do_check_eq(browseridManager._token, null, "we don't have a token");
@ -306,12 +306,12 @@ add_test(function test_RESTResourceAuthenticatorSkew() {
run_next_test();
});
add_task(function* test_ensureLoggedIn() {
add_task(async function test_ensureLoggedIn() {
configureFxAccountIdentity(browseridManager);
yield browseridManager.initializeWithCurrentIdentity();
yield browseridManager.whenReadyToAuthenticate.promise;
await browseridManager.initializeWithCurrentIdentity();
await browseridManager.whenReadyToAuthenticate.promise;
Assert.equal(Status.login, LOGIN_SUCCEEDED, "original initialize worked");
yield browseridManager.ensureLoggedIn();
await browseridManager.ensureLoggedIn();
Assert.equal(Status.login, LOGIN_SUCCEEDED, "original ensureLoggedIn worked");
Assert.ok(browseridManager._shouldHaveSyncKeyBundle,
"_shouldHaveSyncKeyBundle should always be true after ensureLogin completes.");
@ -324,18 +324,18 @@ add_task(function* test_ensureLoggedIn() {
Assert.ok(!browseridManager._shouldHaveSyncKeyBundle,
"_shouldHaveSyncKeyBundle should be false so we know we are testing what we think we are.");
Status.login = LOGIN_FAILED_NO_USERNAME;
yield Assert.rejects(browseridManager.ensureLoggedIn(), "expecting rejection due to no user");
await Assert.rejects(browseridManager.ensureLoggedIn(), "expecting rejection due to no user");
Assert.ok(browseridManager._shouldHaveSyncKeyBundle,
"_shouldHaveSyncKeyBundle should always be true after ensureLogin completes.");
// Restore the logged in user to what it was.
fxa.internal.currentAccountState.storageManager.accountData = signedInUser;
Status.login = LOGIN_FAILED_LOGIN_REJECTED;
yield Assert.rejects(browseridManager.ensureLoggedIn(),
await Assert.rejects(browseridManager.ensureLoggedIn(),
"LOGIN_FAILED_LOGIN_REJECTED should have caused immediate rejection");
Assert.equal(Status.login, LOGIN_FAILED_LOGIN_REJECTED,
"status should remain LOGIN_FAILED_LOGIN_REJECTED");
Status.login = LOGIN_FAILED_NETWORK_ERROR;
yield browseridManager.ensureLoggedIn();
await browseridManager.ensureLoggedIn();
Assert.equal(Status.login, LOGIN_SUCCEEDED, "final ensureLoggedIn worked");
});
@ -404,7 +404,7 @@ add_test(function test_computeXClientStateHeader() {
run_next_test();
});
add_task(function* test_getTokenErrors() {
add_task(async function test_getTokenErrors() {
_("BrowserIDManager correctly handles various failures to get a token.");
_("Arrange for a 401 - Sync should reflect an auth error.");
@ -415,8 +415,8 @@ add_task(function* test_getTokenErrors() {
});
let browseridManager = Service.identity;
yield browseridManager.initializeWithCurrentIdentity();
yield Assert.rejects(browseridManager.whenReadyToAuthenticate.promise,
await browseridManager.initializeWithCurrentIdentity();
await Assert.rejects(browseridManager.whenReadyToAuthenticate.promise,
"should reject due to 401");
Assert.equal(Status.login, LOGIN_FAILED_LOGIN_REJECTED, "login was rejected");
@ -431,13 +431,13 @@ add_task(function* test_getTokenErrors() {
body: "",
});
browseridManager = Service.identity;
yield browseridManager.initializeWithCurrentIdentity();
yield Assert.rejects(browseridManager.whenReadyToAuthenticate.promise,
await browseridManager.initializeWithCurrentIdentity();
await Assert.rejects(browseridManager.whenReadyToAuthenticate.promise,
"should reject due to non-JSON response");
Assert.equal(Status.login, LOGIN_FAILED_NETWORK_ERROR, "login state is LOGIN_FAILED_NETWORK_ERROR");
});
add_task(function* test_refreshCertificateOn401() {
add_task(async function test_refreshCertificateOn401() {
_("BrowserIDManager refreshes the FXA certificate after a 401.");
var identityConfig = makeIdentityConfig();
var browseridManager = new BrowserIDManager();
@ -491,8 +491,8 @@ add_task(function* test_refreshCertificateOn401() {
browseridManager._tokenServerClient = mockTSC;
yield browseridManager.initializeWithCurrentIdentity();
yield browseridManager.whenReadyToAuthenticate.promise;
await browseridManager.initializeWithCurrentIdentity();
await browseridManager.whenReadyToAuthenticate.promise;
do_check_eq(getCertCount, 2);
do_check_true(didReturn401);
@ -505,7 +505,7 @@ add_task(function* test_refreshCertificateOn401() {
add_task(function* test_getTokenErrorWithRetry() {
add_task(async function test_getTokenErrorWithRetry() {
_("tokenserver sends an observer notification on various backoff headers.");
// Set Sync's backoffInterval to zero - after we simulated the backoff header
@ -520,8 +520,8 @@ add_task(function* test_getTokenErrorWithRetry() {
});
let browseridManager = Service.identity;
yield browseridManager.initializeWithCurrentIdentity();
yield Assert.rejects(browseridManager.whenReadyToAuthenticate.promise,
await browseridManager.initializeWithCurrentIdentity();
await Assert.rejects(browseridManager.whenReadyToAuthenticate.promise,
"should reject due to 503");
// The observer should have fired - check it got the value in the response.
@ -539,15 +539,15 @@ add_task(function* test_getTokenErrorWithRetry() {
});
browseridManager = Service.identity;
yield browseridManager.initializeWithCurrentIdentity();
yield Assert.rejects(browseridManager.whenReadyToAuthenticate.promise,
await browseridManager.initializeWithCurrentIdentity();
await Assert.rejects(browseridManager.whenReadyToAuthenticate.promise,
"should reject due to no token in response");
// The observer should have fired - check it got the value in the response.
Assert.ok(Status.backoffInterval >= 200000);
});
add_task(function* test_getKeysErrorWithBackoff() {
add_task(async function test_getKeysErrorWithBackoff() {
_("Auth server (via hawk) sends an observer notification on backoff headers.");
// Set Sync's backoffInterval to zero - after we simulated the backoff header
@ -560,7 +560,7 @@ add_task(function* test_getKeysErrorWithBackoff() {
delete config.fxaccount.user.kA;
delete config.fxaccount.user.kB;
config.fxaccount.user.keyFetchToken = "keyfetchtoken";
yield initializeIdentityWithHAWKResponseFactory(config, function(method, data, uri) {
await initializeIdentityWithHAWKResponseFactory(config, function(method, data, uri) {
Assert.equal(method, "get");
Assert.equal(uri, "http://mockedserver:9999/account/keys")
return {
@ -572,7 +572,7 @@ add_task(function* test_getKeysErrorWithBackoff() {
});
let browseridManager = Service.identity;
yield Assert.rejects(browseridManager.whenReadyToAuthenticate.promise,
await Assert.rejects(browseridManager.whenReadyToAuthenticate.promise,
"should reject due to 503");
// The observer should have fired - check it got the value in the response.
@ -581,7 +581,7 @@ add_task(function* test_getKeysErrorWithBackoff() {
Assert.ok(Status.backoffInterval >= 100000);
});
add_task(function* test_getKeysErrorWithRetry() {
add_task(async function test_getKeysErrorWithRetry() {
_("Auth server (via hawk) sends an observer notification on retry headers.");
// Set Sync's backoffInterval to zero - after we simulated the backoff header
@ -594,7 +594,7 @@ add_task(function* test_getKeysErrorWithRetry() {
delete config.fxaccount.user.kA;
delete config.fxaccount.user.kB;
config.fxaccount.user.keyFetchToken = "keyfetchtoken";
yield initializeIdentityWithHAWKResponseFactory(config, function(method, data, uri) {
await initializeIdentityWithHAWKResponseFactory(config, function(method, data, uri) {
Assert.equal(method, "get");
Assert.equal(uri, "http://mockedserver:9999/account/keys")
return {
@ -606,7 +606,7 @@ add_task(function* test_getKeysErrorWithRetry() {
});
let browseridManager = Service.identity;
yield Assert.rejects(browseridManager.whenReadyToAuthenticate.promise,
await Assert.rejects(browseridManager.whenReadyToAuthenticate.promise,
"should reject due to 503");
// The observer should have fired - check it got the value in the response.
@ -615,12 +615,12 @@ add_task(function* test_getKeysErrorWithRetry() {
Assert.ok(Status.backoffInterval >= 100000);
});
add_task(function* test_getHAWKErrors() {
add_task(async function test_getHAWKErrors() {
_("BrowserIDManager correctly handles various HAWK failures.");
_("Arrange for a 401 - Sync should reflect an auth error.");
let config = makeIdentityConfig();
yield initializeIdentityWithHAWKResponseFactory(config, function(method, data, uri) {
await initializeIdentityWithHAWKResponseFactory(config, function(method, data, uri) {
Assert.equal(method, "post");
Assert.equal(uri, "http://mockedserver:9999/certificate/sign")
return {
@ -636,7 +636,7 @@ add_task(function* test_getHAWKErrors() {
// And for good measure, some totally "unexpected" errors - we generally
// assume these problems are going to magically go away at some point.
_("Arrange for an empty body with a 200 response - should reflect a network error.");
yield initializeIdentityWithHAWKResponseFactory(config, function(method, data, uri) {
await initializeIdentityWithHAWKResponseFactory(config, function(method, data, uri) {
Assert.equal(method, "post");
Assert.equal(uri, "http://mockedserver:9999/certificate/sign")
return {
@ -648,7 +648,7 @@ add_task(function* test_getHAWKErrors() {
Assert.equal(Status.login, LOGIN_FAILED_NETWORK_ERROR, "login state is LOGIN_FAILED_NETWORK_ERROR");
});
add_task(function* test_getGetKeysFailing401() {
add_task(async function test_getGetKeysFailing401() {
_("BrowserIDManager correctly handles 401 responses fetching keys.");
_("Arrange for a 401 - Sync should reflect an auth error.");
@ -657,7 +657,7 @@ add_task(function* test_getGetKeysFailing401() {
delete config.fxaccount.user.kA;
delete config.fxaccount.user.kB;
config.fxaccount.user.keyFetchToken = "keyfetchtoken";
yield initializeIdentityWithHAWKResponseFactory(config, function(method, data, uri) {
await initializeIdentityWithHAWKResponseFactory(config, function(method, data, uri) {
Assert.equal(method, "get");
Assert.equal(uri, "http://mockedserver:9999/account/keys")
return {
@ -669,7 +669,7 @@ add_task(function* test_getGetKeysFailing401() {
Assert.equal(Status.login, LOGIN_FAILED_LOGIN_REJECTED, "login was rejected");
});
add_task(function* test_getGetKeysFailing503() {
add_task(async function test_getGetKeysFailing503() {
_("BrowserIDManager correctly handles 5XX responses fetching keys.");
_("Arrange for a 503 - Sync should reflect a network error.");
@ -678,7 +678,7 @@ add_task(function* test_getGetKeysFailing503() {
delete config.fxaccount.user.kA;
delete config.fxaccount.user.kB;
config.fxaccount.user.keyFetchToken = "keyfetchtoken";
yield initializeIdentityWithHAWKResponseFactory(config, function(method, data, uri) {
await initializeIdentityWithHAWKResponseFactory(config, function(method, data, uri) {
Assert.equal(method, "get");
Assert.equal(uri, "http://mockedserver:9999/account/keys")
return {
@ -690,7 +690,7 @@ add_task(function* test_getGetKeysFailing503() {
Assert.equal(Status.login, LOGIN_FAILED_NETWORK_ERROR, "state reflects network error");
});
add_task(function* test_getKeysMissing() {
add_task(async function test_getKeysMissing() {
_("BrowserIDManager correctly handles getKeys succeeding but not returning keys.");
let browseridManager = new BrowserIDManager();
@ -732,11 +732,11 @@ add_task(function* test_getKeysMissing() {
browseridManager._fxaService = fxa;
yield browseridManager.initializeWithCurrentIdentity();
await browseridManager.initializeWithCurrentIdentity();
let ex;
try {
yield browseridManager.whenReadyToAuthenticate.promise;
await browseridManager.whenReadyToAuthenticate.promise;
} catch (e) {
ex = e;
}
@ -744,7 +744,7 @@ add_task(function* test_getKeysMissing() {
Assert.ok(ex.message.indexOf("missing kA or kB") >= 0);
});
add_task(function* test_signedInUserMissing() {
add_task(async function test_signedInUserMissing() {
_("BrowserIDManager detects getSignedInUser returning incomplete account data");
let browseridManager = new BrowserIDManager();
@ -775,7 +775,7 @@ add_task(function* test_signedInUserMissing() {
browseridManager._fxaService = fxa;
let status = yield browseridManager.unlockAndVerifyAuthState();
let status = await browseridManager.unlockAndVerifyAuthState();
Assert.equal(status, LOGIN_FAILED_LOGIN_REJECTED);
});
@ -789,7 +789,7 @@ add_task(function* test_signedInUserMissing() {
// object that will be returned to hawk.
// A token server mock will be used that doesn't hit a server, so we move
// directly to a hawk request.
function* initializeIdentityWithHAWKResponseFactory(config, cbGetResponse) {
async function initializeIdentityWithHAWKResponseFactory(config, cbGetResponse) {
// A mock request object.
function MockRESTRequest(uri, credentials, extra) {
this._uri = uri;
@ -848,8 +848,8 @@ function* initializeIdentityWithHAWKResponseFactory(config, cbGetResponse) {
browseridManager._fxaService = fxa;
browseridManager._signedInUser = null;
yield browseridManager.initializeWithCurrentIdentity();
yield Assert.rejects(browseridManager.whenReadyToAuthenticate.promise,
await browseridManager.initializeWithCurrentIdentity();
await Assert.rejects(browseridManager.whenReadyToAuthenticate.promise,
"expecting rejection due to hawk error");
}

View File

@ -6,7 +6,7 @@ Cu.import("resource://services-sync/service.js");
Cu.import("resource://services-sync/util.js");
Cu.import("resource://testing-common/services/sync/utils.js");
add_identity_test(this, function* test_missing_crypto_collection() {
add_identity_test(this, async function test_missing_crypto_collection() {
let johnHelper = track_collections_helper();
let johnU = johnHelper.with_updated_collection;
let johnColls = johnHelper.collections;
@ -24,7 +24,7 @@ add_identity_test(this, function* test_missing_crypto_collection() {
};
}
yield configureIdentity({username: "johndoe"});
await configureIdentity({username: "johndoe"});
let handlers = {
"/1.1/johndoe/info/collections": maybe_empty(johnHelper.handler),
@ -53,7 +53,7 @@ add_identity_test(this, function* test_missing_crypto_collection() {
};
_("Startup, no meta/global: freshStart called once.");
yield sync_and_validate_telem();
await sync_and_validate_telem();
do_check_eq(fresh, 1);
fresh = 0;
@ -63,19 +63,17 @@ add_identity_test(this, function* test_missing_crypto_collection() {
_("Simulate a bad info/collections.");
delete johnColls.crypto;
yield sync_and_validate_telem();
await sync_and_validate_telem();
do_check_eq(fresh, 1);
fresh = 0;
_("Regular sync: no need to freshStart.");
yield sync_and_validate_telem();
await sync_and_validate_telem();
do_check_eq(fresh, 0);
} finally {
Svc.Prefs.resetBranch("");
let deferred = Promise.defer();
server.stop(deferred.resolve);
yield deferred.promise;
await promiseStopServer(server);
}
});

View File

@ -12,9 +12,8 @@ Cu.import("resource://services-sync/service.js");
Cu.import("resource://services-sync/status.js");
Cu.import("resource://services-sync/util.js");
Cu.import("resource://testing-common/services/sync/utils.js");
Cu.import("resource://gre/modules/Promise.jsm");
add_task(function* test_locally_changed_keys() {
add_task(async function test_locally_changed_keys() {
let passphrase = "abcdeabcdeabcdeabcdeabcdea";
let hmacErrorCount = 0;
@ -87,7 +86,7 @@ add_task(function* test_locally_changed_keys() {
do_check_true(Service.isLoggedIn);
// Sync should upload records.
yield sync_and_validate_telem();
await sync_and_validate_telem();
// Tabs exist.
_("Tabs modified: " + johndoe.modified("tabs"));
@ -140,7 +139,7 @@ add_task(function* test_locally_changed_keys() {
_("HMAC error count: " + hmacErrorCount);
// Now syncing should succeed, after one HMAC error.
let ping = yield wait_for_ping(() => Service.sync(), true);
let ping = await wait_for_ping(() => Service.sync(), true);
equal(ping.engines.find(e => e.name == "history").incoming.applied, 5);
do_check_eq(hmacErrorCount, 1);
@ -148,11 +147,11 @@ add_task(function* test_locally_changed_keys() {
// And look! We downloaded history!
let store = Service.engineManager.get("history")._store;
do_check_true(yield promiseIsURIVisited("http://foo/bar?record-no--0"));
do_check_true(yield promiseIsURIVisited("http://foo/bar?record-no--1"));
do_check_true(yield promiseIsURIVisited("http://foo/bar?record-no--2"));
do_check_true(yield promiseIsURIVisited("http://foo/bar?record-no--3"));
do_check_true(yield promiseIsURIVisited("http://foo/bar?record-no--4"));
do_check_true(await promiseIsURIVisited("http://foo/bar?record-no--0"));
do_check_true(await promiseIsURIVisited("http://foo/bar?record-no--1"));
do_check_true(await promiseIsURIVisited("http://foo/bar?record-no--2"));
do_check_true(await promiseIsURIVisited("http://foo/bar?record-no--3"));
do_check_true(await promiseIsURIVisited("http://foo/bar?record-no--4"));
do_check_eq(hmacErrorCount, 1);
_("Busting some new server values.");
@ -186,23 +185,21 @@ add_task(function* test_locally_changed_keys() {
Service.lastHMACEvent = 0;
_("Syncing...");
ping = yield sync_and_validate_telem(true);
ping = await sync_and_validate_telem(true);
do_check_eq(ping.engines.find(e => e.name == "history").incoming.failed, 5);
_("Keys now: " + Service.collectionKeys.keyForCollection("history").keyPair);
_("Server keys have been updated, and we skipped over 5 more HMAC errors without adjusting history.");
do_check_true(johndoe.modified("crypto") > old_key_time);
do_check_eq(hmacErrorCount, 6);
do_check_false(yield promiseIsURIVisited("http://foo/bar?record-no--5"));
do_check_false(yield promiseIsURIVisited("http://foo/bar?record-no--6"));
do_check_false(yield promiseIsURIVisited("http://foo/bar?record-no--7"));
do_check_false(yield promiseIsURIVisited("http://foo/bar?record-no--8"));
do_check_false(yield promiseIsURIVisited("http://foo/bar?record-no--9"));
do_check_false(await promiseIsURIVisited("http://foo/bar?record-no--5"));
do_check_false(await promiseIsURIVisited("http://foo/bar?record-no--6"));
do_check_false(await promiseIsURIVisited("http://foo/bar?record-no--7"));
do_check_false(await promiseIsURIVisited("http://foo/bar?record-no--8"));
do_check_false(await promiseIsURIVisited("http://foo/bar?record-no--9"));
} finally {
Svc.Prefs.resetBranch("");
let deferred = Promise.defer();
server.stop(deferred.resolve);
yield deferred.promise;
await promiseStopServer(server);
}
});
@ -224,10 +221,9 @@ function run_test() {
* @rejects JavaScript exception.
*/
function promiseIsURIVisited(url) {
let deferred = Promise.defer();
PlacesUtils.asyncHistory.isURIVisited(Utils.makeURI(url), function(aURI, aIsVisited) {
deferred.resolve(aIsVisited);
return new Promise(resolve => {
PlacesUtils.asyncHistory.isURIVisited(Utils.makeURI(url), function(aURI, aIsVisited) {
resolve(aIsVisited);
});
});
return deferred.promise;
}

View File

@ -11,6 +11,7 @@ Cu.import("resource://services-sync/status.js");
Cu.import("resource://services-sync/util.js");
Cu.import("resource://testing-common/services/sync/utils.js");
Cu.import("resource://gre/modules/FileUtils.jsm");
Cu.import("resource://gre/modules/PromiseUtils.jsm");
var fakeServer = new SyncServer();
fakeServer.start();
@ -64,16 +65,16 @@ function clean() {
errorHandler.didReportProlongedError = false;
}
add_identity_test(this, function* test_401_logout() {
add_identity_test(this, async function test_401_logout() {
let server = EHTestsCommon.sync_httpd_setup();
yield EHTestsCommon.setUp(server);
await EHTestsCommon.setUp(server);
// By calling sync, we ensure we're logged in.
yield sync_and_validate_telem();
await sync_and_validate_telem();
do_check_eq(Status.sync, SYNC_SUCCEEDED);
do_check_true(Service.isLoggedIn);
let deferred = Promise.defer();
let deferred = PromiseUtils.defer();
Svc.Obs.add("weave:service:sync:error", onSyncError);
function onSyncError() {
_("Got weave:service:sync:error in first sync.");
@ -100,28 +101,28 @@ add_identity_test(this, function* test_401_logout() {
}
// Make sync fail due to login rejected.
yield configureIdentity({username: "janedoe"});
await configureIdentity({username: "janedoe"});
Service._updateCachedURLs();
_("Starting first sync.");
let ping = yield sync_and_validate_telem(true);
let ping = await sync_and_validate_telem(true);
deepEqual(ping.failureReason, { name: "httperror", code: 401 });
_("First sync done.");
yield deferred.promise;
await deferred.promise;
});
add_identity_test(this, function* test_credentials_changed_logout() {
add_identity_test(this, async function test_credentials_changed_logout() {
let server = EHTestsCommon.sync_httpd_setup();
yield EHTestsCommon.setUp(server);
await EHTestsCommon.setUp(server);
// By calling sync, we ensure we're logged in.
yield sync_and_validate_telem();
await sync_and_validate_telem();
do_check_eq(Status.sync, SYNC_SUCCEEDED);
do_check_true(Service.isLoggedIn);
EHTestsCommon.generateCredentialsChangedFailure();
let ping = yield sync_and_validate_telem(true);
let ping = await sync_and_validate_telem(true);
equal(ping.status.sync, CREDENTIALS_CHANGED);
deepEqual(ping.failureReason, {
name: "unexpectederror",
@ -133,9 +134,7 @@ add_identity_test(this, function* test_credentials_changed_logout() {
// Clean up.
Service.startOver();
let deferred = Promise.defer();
server.stop(deferred.resolve);
yield deferred.promise;
await promiseStopServer(server);
});
add_identity_test(this, function test_no_lastSync_pref() {
@ -366,10 +365,10 @@ add_identity_test(this, function test_shouldReportError() {
do_check_false(errorHandler.didReportProlongedError);
});
add_identity_test(this, function* test_shouldReportError_master_password() {
add_identity_test(this, async function test_shouldReportError_master_password() {
_("Test error ignored due to locked master password");
let server = EHTestsCommon.sync_httpd_setup();
yield EHTestsCommon.setUp(server);
await EHTestsCommon.setUp(server);
// Monkey patch Service.verifyLogin to imitate
// master password being locked.
@ -386,9 +385,7 @@ add_identity_test(this, function* test_shouldReportError_master_password() {
// Clean up.
Service.verifyLogin = Service._verifyLogin;
clean();
let deferred = Promise.defer();
server.stop(deferred.resolve);
yield deferred.promise;
await promiseStopServer(server);
});
// Test that even if we don't have a cluster URL, a login failure due to
@ -411,32 +408,29 @@ add_identity_test(this, function test_shouldReportLoginFailureWithNoCluster() {
// XXX - how to arrange for 'Service.identity.basicPassword = null;' in
// an fxaccounts environment?
add_task(function* test_login_syncAndReportErrors_non_network_error() {
add_task(async function test_login_syncAndReportErrors_non_network_error() {
// Test non-network errors are reported
// when calling syncAndReportErrors
let server = EHTestsCommon.sync_httpd_setup();
yield EHTestsCommon.setUp(server);
await EHTestsCommon.setUp(server);
Service.identity.basicPassword = null;
let deferred = Promise.defer();
Svc.Obs.add("weave:ui:login:error", function onSyncError() {
Svc.Obs.remove("weave:ui:login:error", onSyncError);
do_check_eq(Status.login, LOGIN_FAILED_NO_PASSWORD);
clean();
server.stop(deferred.resolve);
});
let promiseObserved = promiseOneObserver("weave:ui:login:error");
setLastSync(NON_PROLONGED_ERROR_DURATION);
errorHandler.syncAndReportErrors();
yield deferred.promise;
await promiseObserved;
do_check_eq(Status.login, LOGIN_FAILED_NO_PASSWORD);
clean();
await promiseStopServer(server);
});
add_identity_test(this, function* test_sync_syncAndReportErrors_non_network_error() {
add_identity_test(this, async function test_sync_syncAndReportErrors_non_network_error() {
// Test non-network errors are reported
// when calling syncAndReportErrors
let server = EHTestsCommon.sync_httpd_setup();
yield EHTestsCommon.setUp(server);
await EHTestsCommon.setUp(server);
// By calling sync, we ensure we're logged in.
Service.sync();
@ -445,55 +439,48 @@ add_identity_test(this, function* test_sync_syncAndReportErrors_non_network_erro
EHTestsCommon.generateCredentialsChangedFailure();
let deferred = Promise.defer();
Svc.Obs.add("weave:ui:sync:error", function onSyncError() {
Svc.Obs.remove("weave:ui:sync:error", onSyncError);
do_check_eq(Status.sync, CREDENTIALS_CHANGED);
// If we clean this tick, telemetry won't get the right error
server.stop(() => {
clean();
deferred.resolve();
});
});
let promiseObserved = promiseOneObserver("weave:ui:sync:error");
setLastSync(NON_PROLONGED_ERROR_DURATION);
let ping = yield wait_for_ping(() => errorHandler.syncAndReportErrors(), true);
let ping = await wait_for_ping(() => errorHandler.syncAndReportErrors(), true);
equal(ping.status.sync, CREDENTIALS_CHANGED);
deepEqual(ping.failureReason, {
name: "unexpectederror",
error: "Error: Aborting sync, remote setup failed"
});
yield deferred.promise;
await promiseObserved;
do_check_eq(Status.sync, CREDENTIALS_CHANGED);
// If we clean this tick, telemetry won't get the right error
await promiseStopServer(server);
clean();
});
// XXX - how to arrange for 'Service.identity.basicPassword = null;' in
// an fxaccounts environment?
add_task(function* test_login_syncAndReportErrors_prolonged_non_network_error() {
add_task(async function test_login_syncAndReportErrors_prolonged_non_network_error() {
// Test prolonged, non-network errors are
// reported when calling syncAndReportErrors.
let server = EHTestsCommon.sync_httpd_setup();
yield EHTestsCommon.setUp(server);
await EHTestsCommon.setUp(server);
Service.identity.basicPassword = null;
let deferred = Promise.defer();
Svc.Obs.add("weave:ui:login:error", function onSyncError() {
Svc.Obs.remove("weave:ui:login:error", onSyncError);
do_check_eq(Status.login, LOGIN_FAILED_NO_PASSWORD);
clean();
server.stop(deferred.resolve);
});
let promiseObserved = promiseOneObserver("weave:ui:login:error");
setLastSync(PROLONGED_ERROR_DURATION);
errorHandler.syncAndReportErrors();
yield deferred.promise;
await promiseObserved;
do_check_eq(Status.login, LOGIN_FAILED_NO_PASSWORD);
clean();
await promiseStopServer(server);
});
add_identity_test(this, function* test_sync_syncAndReportErrors_prolonged_non_network_error() {
add_identity_test(this, async function test_sync_syncAndReportErrors_prolonged_non_network_error() {
// Test prolonged, non-network errors are
// reported when calling syncAndReportErrors.
let server = EHTestsCommon.sync_httpd_setup();
yield EHTestsCommon.setUp(server);
await EHTestsCommon.setUp(server);
// By calling sync, we ensure we're logged in.
Service.sync();
@ -502,45 +489,38 @@ add_identity_test(this, function* test_sync_syncAndReportErrors_prolonged_non_ne
EHTestsCommon.generateCredentialsChangedFailure();
let deferred = Promise.defer();
Svc.Obs.add("weave:ui:sync:error", function onSyncError() {
Svc.Obs.remove("weave:ui:sync:error", onSyncError);
do_check_eq(Status.sync, CREDENTIALS_CHANGED);
// If we clean this tick, telemetry won't get the right error
server.stop(() => {
clean();
deferred.resolve();
});
});
let promiseObserved = promiseOneObserver("weave:ui:sync:error");
setLastSync(PROLONGED_ERROR_DURATION);
let ping = yield wait_for_ping(() => errorHandler.syncAndReportErrors(), true);
let ping = await wait_for_ping(() => errorHandler.syncAndReportErrors(), true);
equal(ping.status.sync, CREDENTIALS_CHANGED);
deepEqual(ping.failureReason, {
name: "unexpectederror",
error: "Error: Aborting sync, remote setup failed"
});
yield deferred.promise;
await promiseObserved;
do_check_eq(Status.sync, CREDENTIALS_CHANGED);
// If we clean this tick, telemetry won't get the right error
await promiseStopServer(server);
clean();
});
add_identity_test(this, function* test_login_syncAndReportErrors_network_error() {
add_identity_test(this, async function test_login_syncAndReportErrors_network_error() {
// Test network errors are reported when calling syncAndReportErrors.
yield configureIdentity({username: "broken.wipe"});
await configureIdentity({username: "broken.wipe"});
Service.serverURL = fakeServerUrl;
Service.clusterURL = fakeServerUrl;
let deferred = Promise.defer();
Svc.Obs.add("weave:ui:login:error", function onSyncError() {
Svc.Obs.remove("weave:ui:login:error", onSyncError);
do_check_eq(Status.login, LOGIN_FAILED_NETWORK_ERROR);
clean();
deferred.resolve();
});
let promiseObserved = promiseOneObserver("weave:ui:login:error");
setLastSync(NON_PROLONGED_ERROR_DURATION);
errorHandler.syncAndReportErrors();
yield deferred.promise;
await promiseObserved;
do_check_eq(Status.login, LOGIN_FAILED_NETWORK_ERROR);
clean();
});
@ -561,26 +541,22 @@ add_test(function test_sync_syncAndReportErrors_network_error() {
errorHandler.syncAndReportErrors();
});
add_identity_test(this, function* test_login_syncAndReportErrors_prolonged_network_error() {
add_identity_test(this, async function test_login_syncAndReportErrors_prolonged_network_error() {
// Test prolonged, network errors are reported
// when calling syncAndReportErrors.
yield configureIdentity({username: "johndoe"});
await configureIdentity({username: "johndoe"});
Service.serverURL = fakeServerUrl;
Service.clusterURL = fakeServerUrl;
let deferred = Promise.defer();
Svc.Obs.add("weave:ui:login:error", function onSyncError() {
Svc.Obs.remove("weave:ui:login:error", onSyncError);
do_check_eq(Status.login, LOGIN_FAILED_NETWORK_ERROR);
clean();
deferred.resolve();
});
let promiseObserved = promiseOneObserver("weave:ui:login:error");
setLastSync(PROLONGED_ERROR_DURATION);
errorHandler.syncAndReportErrors();
yield deferred.promise;
await promiseObserved;
do_check_eq(Status.login, LOGIN_FAILED_NETWORK_ERROR);
clean();
});
add_test(function test_sync_syncAndReportErrors_prolonged_network_error() {
@ -601,31 +577,28 @@ add_test(function test_sync_syncAndReportErrors_prolonged_network_error() {
errorHandler.syncAndReportErrors();
});
add_task(function* test_login_prolonged_non_network_error() {
add_task(async function test_login_prolonged_non_network_error() {
// Test prolonged, non-network errors are reported
let server = EHTestsCommon.sync_httpd_setup();
yield EHTestsCommon.setUp(server);
await EHTestsCommon.setUp(server);
Service.identity.basicPassword = null;
let deferred = Promise.defer();
Svc.Obs.add("weave:ui:login:error", function onSyncError() {
Svc.Obs.remove("weave:ui:login:error", onSyncError);
do_check_eq(Status.sync, PROLONGED_SYNC_FAILURE);
do_check_true(errorHandler.didReportProlongedError);
clean();
server.stop(deferred.resolve);
});
let promiseObserved = promiseOneObserver("weave:ui:login:error");
setLastSync(PROLONGED_ERROR_DURATION);
Service.sync();
yield deferred.promise;
await promiseObserved;
do_check_eq(Status.sync, PROLONGED_SYNC_FAILURE);
do_check_true(errorHandler.didReportProlongedError);
clean();
await promiseStopServer(server);
});
add_task(function* test_sync_prolonged_non_network_error() {
add_task(async function test_sync_prolonged_non_network_error() {
// Test prolonged, non-network errors are reported
let server = EHTestsCommon.sync_httpd_setup();
yield EHTestsCommon.setUp(server);
await EHTestsCommon.setUp(server);
// By calling sync, we ensure we're logged in.
Service.sync();
@ -634,47 +607,38 @@ add_task(function* test_sync_prolonged_non_network_error() {
EHTestsCommon.generateCredentialsChangedFailure();
let deferred = Promise.defer();
Svc.Obs.add("weave:ui:sync:error", function onSyncError() {
Svc.Obs.remove("weave:ui:sync:error", onSyncError);
do_check_eq(Status.sync, PROLONGED_SYNC_FAILURE);
do_check_true(errorHandler.didReportProlongedError);
server.stop(() => {
clean();
deferred.resolve();
});
});
let promiseObserved = promiseOneObserver("weave:ui:sync:error");
setLastSync(PROLONGED_ERROR_DURATION);
let ping = yield sync_and_validate_telem(true);
let ping = await sync_and_validate_telem(true);
equal(ping.status.sync, PROLONGED_SYNC_FAILURE);
deepEqual(ping.failureReason, {
name: "unexpectederror",
error: "Error: Aborting sync, remote setup failed"
});
yield deferred.promise;
await promiseObserved;
do_check_eq(Status.sync, PROLONGED_SYNC_FAILURE);
do_check_true(errorHandler.didReportProlongedError);
await promiseStopServer(server);
clean();
});
add_identity_test(this, function* test_login_prolonged_network_error() {
add_identity_test(this, async function test_login_prolonged_network_error() {
// Test prolonged, network errors are reported
yield configureIdentity({username: "johndoe"});
await configureIdentity({username: "johndoe"});
Service.serverURL = fakeServerUrl;
Service.clusterURL = fakeServerUrl;
let deferred = Promise.defer();
Svc.Obs.add("weave:ui:login:error", function onSyncError() {
Svc.Obs.remove("weave:ui:login:error", onSyncError);
do_check_eq(Status.sync, PROLONGED_SYNC_FAILURE);
do_check_true(errorHandler.didReportProlongedError);
clean();
deferred.resolve();
});
let promiseObserved = promiseOneObserver("weave:ui:login:error");
setLastSync(PROLONGED_ERROR_DURATION);
Service.sync();
yield deferred.promise;
await promiseObserved;
do_check_eq(Status.sync, PROLONGED_SYNC_FAILURE);
do_check_true(errorHandler.didReportProlongedError);
clean();
});
add_test(function test_sync_prolonged_network_error() {
@ -695,31 +659,28 @@ add_test(function test_sync_prolonged_network_error() {
Service.sync();
});
add_task(function* test_login_non_network_error() {
add_task(async function test_login_non_network_error() {
// Test non-network errors are reported
let server = EHTestsCommon.sync_httpd_setup();
yield EHTestsCommon.setUp(server);
await EHTestsCommon.setUp(server);
Service.identity.basicPassword = null;
let deferred = Promise.defer();
Svc.Obs.add("weave:ui:login:error", function onSyncError() {
Svc.Obs.remove("weave:ui:login:error", onSyncError);
do_check_eq(Status.login, LOGIN_FAILED_NO_PASSWORD);
do_check_false(errorHandler.didReportProlongedError);
clean();
server.stop(deferred.resolve);
});
let promiseObserved = promiseOneObserver("weave:ui:login:error");
setLastSync(NON_PROLONGED_ERROR_DURATION);
Service.sync();
yield deferred.promise;
await promiseObserved;
do_check_eq(Status.login, LOGIN_FAILED_NO_PASSWORD);
do_check_false(errorHandler.didReportProlongedError);
clean();
await promiseStopServer(server);
});
add_task(function* test_sync_non_network_error() {
add_task(async function test_sync_non_network_error() {
// Test non-network errors are reported
let server = EHTestsCommon.sync_httpd_setup();
yield EHTestsCommon.setUp(server);
await EHTestsCommon.setUp(server);
// By calling sync, we ensure we're logged in.
Service.sync();
@ -728,42 +689,34 @@ add_task(function* test_sync_non_network_error() {
EHTestsCommon.generateCredentialsChangedFailure();
let deferred = Promise.defer();
Svc.Obs.add("weave:ui:sync:error", function onSyncError() {
Svc.Obs.remove("weave:ui:sync:error", onSyncError);
do_check_eq(Status.sync, CREDENTIALS_CHANGED);
do_check_false(errorHandler.didReportProlongedError);
clean();
server.stop(deferred.resolve);
});
let promiseObserved = promiseOneObserver("weave:ui:sync:error");
setLastSync(NON_PROLONGED_ERROR_DURATION);
Service.sync();
yield deferred.promise;
await promiseObserved;
do_check_eq(Status.sync, CREDENTIALS_CHANGED);
do_check_false(errorHandler.didReportProlongedError);
clean();
await promiseStopServer(server);
});
add_identity_test(this, function* test_login_network_error() {
yield configureIdentity({username: "johndoe"});
add_identity_test(this, async function test_login_network_error() {
await configureIdentity({username: "johndoe"});
Service.serverURL = fakeServerUrl;
Service.clusterURL = fakeServerUrl;
let deferred = Promise.defer();
let promiseObserved = promiseOneObserver("weave:ui:clear-error");
// Test network errors are not reported.
Svc.Obs.add("weave:ui:clear-error", function onClearError() {
Svc.Obs.remove("weave:ui:clear-error", onClearError);
do_check_eq(Status.login, LOGIN_FAILED_NETWORK_ERROR);
do_check_false(errorHandler.didReportProlongedError);
Services.io.offline = false;
clean();
deferred.resolve()
});
setLastSync(NON_PROLONGED_ERROR_DURATION);
Service.sync();
yield deferred.promise;
await promiseObserved;
do_check_eq(Status.login, LOGIN_FAILED_NETWORK_ERROR);
do_check_false(errorHandler.didReportProlongedError);
Services.io.offline = false;
clean();
});
add_test(function test_sync_network_error() {
@ -784,10 +737,10 @@ add_test(function test_sync_network_error() {
Service.sync();
});
add_identity_test(this, function* test_sync_server_maintenance_error() {
add_identity_test(this, async function test_sync_server_maintenance_error() {
// Test server maintenance errors are not reported.
let server = EHTestsCommon.sync_httpd_setup();
yield EHTestsCommon.setUp(server);
await EHTestsCommon.setUp(server);
const BACKOFF = 42;
let engine = engineManager.get("catapult");
@ -802,36 +755,29 @@ add_identity_test(this, function* test_sync_server_maintenance_error() {
do_check_eq(Status.service, STATUS_OK);
let deferred = Promise.defer();
Svc.Obs.add("weave:ui:sync:finish", function onSyncFinish() {
Svc.Obs.remove("weave:ui:sync:finish", onSyncFinish);
do_check_eq(Status.service, SYNC_FAILED_PARTIAL);
do_check_eq(Status.sync, SERVER_MAINTENANCE);
do_check_false(errorHandler.didReportProlongedError);
Svc.Obs.remove("weave:ui:sync:error", onSyncError);
server.stop(() => {
clean();
deferred.resolve();
})
});
let promiseObserved = promiseOneObserver("weave:ui:sync:finish");
setLastSync(NON_PROLONGED_ERROR_DURATION);
let ping = yield sync_and_validate_telem(true);
let ping = await sync_and_validate_telem(true);
equal(ping.status.sync, SERVER_MAINTENANCE);
deepEqual(ping.engines.find(e => e.failureReason).failureReason, { name: "httperror", code: 503 })
yield deferred.promise;
await promiseObserved;
do_check_eq(Status.service, SYNC_FAILED_PARTIAL);
do_check_eq(Status.sync, SERVER_MAINTENANCE);
do_check_false(errorHandler.didReportProlongedError);
await promiseStopServer(server);
clean();
});
add_identity_test(this, function* test_info_collections_login_server_maintenance_error() {
add_identity_test(this, async function test_info_collections_login_server_maintenance_error() {
// Test info/collections server maintenance errors are not reported.
let server = EHTestsCommon.sync_httpd_setup();
yield EHTestsCommon.setUp(server);
await EHTestsCommon.setUp(server);
Service.username = "broken.info";
yield configureIdentity({username: "broken.info"});
await configureIdentity({username: "broken.info"});
Service.serverURL = server.baseURI + "/maintenance/";
Service.clusterURL = server.baseURI + "/maintenance/";
@ -849,32 +795,29 @@ add_identity_test(this, function* test_info_collections_login_server_maintenance
do_check_false(Status.enforceBackoff);
do_check_eq(Status.service, STATUS_OK);
let deferred = Promise.defer();
Svc.Obs.add("weave:ui:clear-error", function onLoginFinish() {
Svc.Obs.remove("weave:ui:clear-error", onLoginFinish);
do_check_true(Status.enforceBackoff);
do_check_eq(backoffInterval, 42);
do_check_eq(Status.service, LOGIN_FAILED);
do_check_eq(Status.login, SERVER_MAINTENANCE);
do_check_false(errorHandler.didReportProlongedError);
Svc.Obs.remove("weave:ui:login:error", onUIUpdate);
clean();
server.stop(deferred.resolve);
});
let promiseObserved = promiseOneObserver("weave:ui:clear-error")
setLastSync(NON_PROLONGED_ERROR_DURATION);
Service.sync();
yield deferred.promise;
await promiseObserved;
do_check_true(Status.enforceBackoff);
do_check_eq(backoffInterval, 42);
do_check_eq(Status.service, LOGIN_FAILED);
do_check_eq(Status.login, SERVER_MAINTENANCE);
do_check_false(errorHandler.didReportProlongedError);
Svc.Obs.remove("weave:ui:login:error", onUIUpdate);
clean();
await promiseStopServer(server);
});
add_identity_test(this, function* test_meta_global_login_server_maintenance_error() {
add_identity_test(this, async function test_meta_global_login_server_maintenance_error() {
// Test meta/global server maintenance errors are not reported.
let server = EHTestsCommon.sync_httpd_setup();
yield EHTestsCommon.setUp(server);
await EHTestsCommon.setUp(server);
yield configureIdentity({username: "broken.meta"});
await configureIdentity({username: "broken.meta"});
Service.serverURL = server.baseURI + "/maintenance/";
Service.clusterURL = server.baseURI + "/maintenance/";
@ -892,22 +835,19 @@ add_identity_test(this, function* test_meta_global_login_server_maintenance_erro
do_check_false(Status.enforceBackoff);
do_check_eq(Status.service, STATUS_OK);
let deferred = Promise.defer();
Svc.Obs.add("weave:ui:clear-error", function onLoginFinish() {
Svc.Obs.remove("weave:ui:clear-error", onLoginFinish);
do_check_true(Status.enforceBackoff);
do_check_eq(backoffInterval, 42);
do_check_eq(Status.service, LOGIN_FAILED);
do_check_eq(Status.login, SERVER_MAINTENANCE);
do_check_false(errorHandler.didReportProlongedError);
Svc.Obs.remove("weave:ui:login:error", onUIUpdate);
clean();
server.stop(deferred.resolve);
});
let promiseObserved = promiseOneObserver("weave:ui:clear-error");
setLastSync(NON_PROLONGED_ERROR_DURATION);
Service.sync();
yield deferred.promise;
await promiseObserved;
do_check_true(Status.enforceBackoff);
do_check_eq(backoffInterval, 42);
do_check_eq(Status.service, LOGIN_FAILED);
do_check_eq(Status.login, SERVER_MAINTENANCE);
do_check_false(errorHandler.didReportProlongedError);
Svc.Obs.remove("weave:ui:login:error", onUIUpdate);
clean();
await promiseStopServer(server);
});

File diff suppressed because it is too large Load Diff

View File

@ -43,8 +43,8 @@ function sync_httpd_setup(infoHandler) {
return httpd_setup(handlers);
}
function* setUp(server) {
yield configureIdentity({username: "johndoe"});
async function setUp(server) {
await configureIdentity({username: "johndoe"});
Service.serverURL = server.baseURI + "/";
Service.clusterURL = server.baseURI + "/";
new FakeCryptoService();
@ -66,72 +66,63 @@ function do_check_hard_eol(eh, start) {
do_check_true(Status.eol);
}
add_identity_test(this, function* test_200_hard() {
add_identity_test(this, async function test_200_hard() {
let eh = Service.errorHandler;
let start = Date.now();
let server = sync_httpd_setup(handler200("hard-eol"));
yield setUp(server);
await setUp(server);
let deferred = Promise.defer();
let obs = function (subject, topic, data) {
Svc.Obs.remove("weave:eol", obs);
do_check_eq("hard-eol", subject.code);
do_check_hard_eol(eh, start);
do_check_eq(Service.scheduler.eolInterval, Service.scheduler.syncInterval);
eh.clearServerAlerts();
server.stop(deferred.resolve);
};
let promiseObserved = promiseOneObserver("weave:eol");
Svc.Obs.add("weave:eol", obs);
Service._fetchInfo();
Service.scheduler.adjustSyncInterval(); // As if we failed or succeeded in syncing.
yield deferred.promise;
let { subject } = await promiseObserved;
do_check_eq("hard-eol", subject.code);
do_check_hard_eol(eh, start);
do_check_eq(Service.scheduler.eolInterval, Service.scheduler.syncInterval);
eh.clearServerAlerts();
await promiseStopServer(server);
});
add_identity_test(this, function* test_513_hard() {
add_identity_test(this, async function test_513_hard() {
let eh = Service.errorHandler;
let start = Date.now();
let server = sync_httpd_setup(handler513);
yield setUp(server);
await setUp(server);
let deferred = Promise.defer();
let obs = function (subject, topic, data) {
Svc.Obs.remove("weave:eol", obs);
do_check_eq("hard-eol", subject.code);
do_check_hard_eol(eh, start);
do_check_eq(Service.scheduler.eolInterval, Service.scheduler.syncInterval);
eh.clearServerAlerts();
server.stop(deferred.resolve);
};
let promiseObserved = promiseOneObserver("weave:eol");
Svc.Obs.add("weave:eol", obs);
try {
Service._fetchInfo();
Service.scheduler.adjustSyncInterval(); // As if we failed or succeeded in syncing.
} catch (ex) {
// Because fetchInfo will fail on a 513.
}
yield deferred.promise;
let { subject } = await promiseObserved;
do_check_eq("hard-eol", subject.code);
do_check_hard_eol(eh, start);
do_check_eq(Service.scheduler.eolInterval, Service.scheduler.syncInterval);
eh.clearServerAlerts();
await promiseStopServer(server);
});
add_identity_test(this, function* test_200_soft() {
add_identity_test(this, async function test_200_soft() {
let eh = Service.errorHandler;
let start = Date.now();
let server = sync_httpd_setup(handler200("soft-eol"));
yield setUp(server);
await setUp(server);
let deferred = Promise.defer();
let obs = function (subject, topic, data) {
Svc.Obs.remove("weave:eol", obs);
do_check_eq("soft-eol", subject.code);
do_check_soft_eol(eh, start);
do_check_eq(Service.scheduler.singleDeviceInterval, Service.scheduler.syncInterval);
eh.clearServerAlerts();
server.stop(deferred.resolve);
};
let promiseObserved = promiseOneObserver("weave:eol");
Svc.Obs.add("weave:eol", obs);
Service._fetchInfo();
Service.scheduler.adjustSyncInterval(); // As if we failed or succeeded in syncing.
yield deferred.promise;
let { subject } = await promiseObserved;
do_check_eq("soft-eol", subject.code);
do_check_soft_eol(eh, start);
do_check_eq(Service.scheduler.singleDeviceInterval, Service.scheduler.syncInterval);
eh.clearServerAlerts();
await promiseStopServer(server);
});

View File

@ -16,12 +16,6 @@ initTestLogging("Trace");
var engineManager = Service.engineManager;
engineManager.clear();
function promiseStopServer(server) {
let deferred = Promise.defer();
server.stop(deferred.resolve);
return deferred.promise;
}
function CatapultEngine() {
SyncEngine.call(this, "Catapult", Service);
}
@ -59,8 +53,8 @@ function sync_httpd_setup() {
return httpd_setup(handlers);
}
function* setUp(server) {
yield configureIdentity({username: "johndoe"});
async function setUp(server) {
await configureIdentity({username: "johndoe"});
Service.serverURL = server.baseURI + "/";
Service.clusterURL = server.baseURI + "/";
new FakeCryptoService();
@ -75,10 +69,10 @@ function generateAndUploadKeys(server) {
}
add_identity_test(this, function* test_backoff500() {
add_identity_test(this, async function test_backoff500() {
_("Test: HTTP 500 sets backoff status.");
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
let engine = engineManager.get("catapult");
engine.enabled = true;
@ -99,13 +93,13 @@ add_identity_test(this, function* test_backoff500() {
Status.resetBackoff();
Service.startOver();
}
yield promiseStopServer(server);
await promiseStopServer(server);
});
add_identity_test(this, function* test_backoff503() {
add_identity_test(this, async function test_backoff503() {
_("Test: HTTP 503 with Retry-After header leads to backoff notification and sets backoff status.");
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
const BACKOFF = 42;
let engine = engineManager.get("catapult");
@ -135,13 +129,13 @@ add_identity_test(this, function* test_backoff503() {
Status.resetSync();
Service.startOver();
}
yield promiseStopServer(server);
await promiseStopServer(server);
});
add_identity_test(this, function* test_overQuota() {
add_identity_test(this, async function test_overQuota() {
_("Test: HTTP 400 with body error code 14 means over quota.");
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
let engine = engineManager.get("catapult");
engine.enabled = true;
@ -164,67 +158,60 @@ add_identity_test(this, function* test_overQuota() {
Status.resetSync();
Service.startOver();
}
yield promiseStopServer(server);
await promiseStopServer(server);
});
add_identity_test(this, function* test_service_networkError() {
add_identity_test(this, async function test_service_networkError() {
_("Test: Connection refused error from Service.sync() leads to the right status code.");
let server = sync_httpd_setup();
yield setUp(server);
let deferred = Promise.defer();
server.stop(() => {
// Provoke connection refused.
Service.clusterURL = "http://localhost:12345/";
await setUp(server);
await promiseStopServer(server);
// Provoke connection refused.
Service.clusterURL = "http://localhost:12345/";
try {
do_check_eq(Status.sync, SYNC_SUCCEEDED);
try {
do_check_eq(Status.sync, SYNC_SUCCEEDED);
Service._loggedIn = true;
Service.sync();
Service._loggedIn = true;
Service.sync();
do_check_eq(Status.sync, LOGIN_FAILED_NETWORK_ERROR);
do_check_eq(Status.service, SYNC_FAILED);
} finally {
Status.resetSync();
Service.startOver();
}
deferred.resolve();
});
yield deferred.promise;
do_check_eq(Status.sync, LOGIN_FAILED_NETWORK_ERROR);
do_check_eq(Status.service, SYNC_FAILED);
} finally {
Status.resetSync();
Service.startOver();
}
});
add_identity_test(this, function* test_service_offline() {
add_identity_test(this, async function test_service_offline() {
_("Test: Wanting to sync in offline mode leads to the right status code but does not increment the ignorable error count.");
let server = sync_httpd_setup();
yield setUp(server);
let deferred = Promise.defer();
server.stop(() => {
Services.io.offline = true;
Services.prefs.setBoolPref("network.dns.offline-localhost", false);
await setUp(server);
try {
do_check_eq(Status.sync, SYNC_SUCCEEDED);
await promiseStopServer(server);
Services.io.offline = true;
Services.prefs.setBoolPref("network.dns.offline-localhost", false);
Service._loggedIn = true;
Service.sync();
try {
do_check_eq(Status.sync, SYNC_SUCCEEDED);
do_check_eq(Status.sync, LOGIN_FAILED_NETWORK_ERROR);
do_check_eq(Status.service, SYNC_FAILED);
} finally {
Status.resetSync();
Service.startOver();
}
Services.io.offline = false;
Services.prefs.clearUserPref("network.dns.offline-localhost");
deferred.resolve();
});
yield deferred.promise;
Service._loggedIn = true;
Service.sync();
do_check_eq(Status.sync, LOGIN_FAILED_NETWORK_ERROR);
do_check_eq(Status.service, SYNC_FAILED);
} finally {
Status.resetSync();
Service.startOver();
}
Services.io.offline = false;
Services.prefs.clearUserPref("network.dns.offline-localhost");
});
add_identity_test(this, function* test_engine_networkError() {
add_identity_test(this, async function test_engine_networkError() {
_("Test: Network related exceptions from engine.sync() lead to the right status code.");
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
let engine = engineManager.get("catapult");
engine.enabled = true;
@ -245,12 +232,12 @@ add_identity_test(this, function* test_engine_networkError() {
Status.resetSync();
Service.startOver();
}
yield promiseStopServer(server);
await promiseStopServer(server);
});
add_identity_test(this, function* test_resource_timeout() {
add_identity_test(this, async function test_resource_timeout() {
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
let engine = engineManager.get("catapult");
engine.enabled = true;
@ -272,7 +259,7 @@ add_identity_test(this, function* test_resource_timeout() {
Status.resetSync();
Service.startOver();
}
yield promiseStopServer(server);
await promiseStopServer(server);
});
function run_test() {

View File

@ -3,7 +3,6 @@ Services.prefs.setCharPref("identity.fxaccounts.auth.uri", "http://localhost");
// Test the FxAMigration module
Cu.import("resource://services-sync/FxaMigrator.jsm");
Cu.import("resource://gre/modules/Promise.jsm");
// Set our username pref early so sync initializes with the legacy provider.
Services.prefs.setCharPref("services.sync.username", "foo");
@ -24,24 +23,6 @@ Cu.import("resource://testing-common/services/sync/rotaryengine.js");
const FXA_USERNAME = "someone@somewhere";
// Utilities
function promiseOneObserver(topic) {
return new Promise((resolve, reject) => {
let observer = function(subject, topic, data) {
Services.obs.removeObserver(observer, topic);
resolve({ subject: subject, data: data });
}
Services.obs.addObserver(observer, topic, false);
});
}
function promiseStopServer(server) {
return new Promise((resolve, reject) => {
server.stop(resolve);
});
}
// Helpers
function configureLegacySync() {
let engine = new RotaryEngine(Service);
@ -80,7 +61,7 @@ function configureLegacySync() {
return [engine, server];
}
add_task(function *testMigrationUnlinks() {
add_task(async function testMigrationUnlinks() {
// when we do a .startOver we want the new provider.
let oldValue = Services.prefs.getBoolPref("services.sync-testing.startOverKeepIdentity");
@ -101,8 +82,8 @@ add_task(function *testMigrationUnlinks() {
Service.sync();
_("Finished sync");
yield promiseStartOver;
yield promiseMigration;
await promiseStartOver;
await promiseMigration;
// We should have seen the observer and Sync should no longer be configured.
Assert.ok(!Services.prefs.prefHasUserValue("services.sync.username"));
});

View File

@ -16,6 +16,7 @@ Cu.import("resource://services-sync/util.js");
Cu.import("resource://testing-common/services/sync/rotaryengine.js");
Cu.import("resource://services-sync/browserid_identity.js");
Cu.import("resource://testing-common/services/sync/utils.js");
Cu.import("resource://gre/modules/PromiseUtils.jsm");
Service.engineManager.clear();
@ -117,10 +118,10 @@ function getReassigned() {
* Runs `between` between the two. This can be used to undo deliberate failure
* setup, detach observers, etc.
*/
function* syncAndExpectNodeReassignment(server, firstNotification, between,
secondNotification, url) {
async function syncAndExpectNodeReassignment(server, firstNotification, between,
secondNotification, url) {
_("Starting syncAndExpectNodeReassignment\n");
let deferred = Promise.defer();
let deferred = PromiseUtils.defer();
function onwards() {
let numTokenRequestsBefore;
function onFirstSync() {
@ -168,13 +169,13 @@ function* syncAndExpectNodeReassignment(server, firstNotification, between,
_("Skipping preliminary validation check for a 401 as we aren't logged in");
Utils.nextTick(onwards);
}
yield deferred.promise;
await deferred.promise;
}
// Check that when we sync we don't request a new token by default - our
// test setup has configured the client with a valid token, and that token
// should be used to form the cluster URL.
add_task(function* test_single_token_fetch() {
add_task(async function test_single_token_fetch() {
_("Test a normal sync only fetches 1 token");
let numTokenFetches = 0;
@ -190,7 +191,7 @@ add_task(function* test_single_token_fetch() {
// it will crash.
Service.clusterURL = "http://example.com/";
let server = yield prepareServer(afterTokenFetch);
let server = await prepareServer(afterTokenFetch);
do_check_false(Service.isLoggedIn, "not already logged in");
Service.sync();
@ -200,12 +201,12 @@ add_task(function* test_single_token_fetch() {
// that clusterURL we expect.
let expectedClusterURL = server.baseURI + "1.1/johndoe/";
do_check_eq(Service.clusterURL, expectedClusterURL);
yield new Promise(resolve => server.stop(resolve));
await promiseStopServer(server);
});
add_task(function* test_momentary_401_engine() {
add_task(async function test_momentary_401_engine() {
_("Test a failure for engine URLs that's resolved by reassignment.");
let server = yield prepareServer();
let server = await prepareServer();
let john = server.user("johndoe");
_("Enabling the Rotary engine.");
@ -247,7 +248,7 @@ add_task(function* test_momentary_401_engine() {
Svc.Obs.add("weave:service:login:start", onLoginStart);
}
yield syncAndExpectNodeReassignment(server,
await syncAndExpectNodeReassignment(server,
"weave:service:sync:finish",
between,
"weave:service:sync:finish",
@ -255,9 +256,9 @@ add_task(function* test_momentary_401_engine() {
});
// This test ends up being a failing info fetch *after we're already logged in*.
add_task(function* test_momentary_401_info_collections_loggedin() {
add_task(async function test_momentary_401_info_collections_loggedin() {
_("Test a failure for info/collections after login that's resolved by reassignment.");
let server = yield prepareServer();
let server = await prepareServer();
_("First sync to prepare server contents.");
Service.sync();
@ -273,7 +274,7 @@ add_task(function* test_momentary_401_info_collections_loggedin() {
do_check_true(Service.isLoggedIn, "already logged in");
yield syncAndExpectNodeReassignment(server,
await syncAndExpectNodeReassignment(server,
"weave:service:sync:error",
undo,
"weave:service:sync:finish",
@ -283,7 +284,7 @@ add_task(function* test_momentary_401_info_collections_loggedin() {
// This test ends up being a failing info fetch *before we're logged in*.
// In this case we expect to recover during the login phase - so the first
// sync succeeds.
add_task(function* test_momentary_401_info_collections_loggedout() {
add_task(async function test_momentary_401_info_collections_loggedout() {
_("Test a failure for info/collections before login that's resolved by reassignment.");
let oldHandler;
@ -296,7 +297,7 @@ add_task(function* test_momentary_401_info_collections_loggedout() {
sawTokenFetch = true;
}
let server = yield prepareServer(afterTokenFetch);
let server = await prepareServer(afterTokenFetch);
// Return a 401 for the next /info request - it will be reset immediately
// after a new token is fetched.
@ -311,16 +312,14 @@ add_task(function* test_momentary_401_info_collections_loggedout() {
do_check_true(sawTokenFetch, "a new token was fetched by this test.")
// and we are done.
Service.startOver();
let deferred = Promise.defer();
server.stop(deferred.resolve);
yield deferred.promise;
await promiseStopServer(server);
});
// This test ends up being a failing meta/global fetch *after we're already logged in*.
add_task(function* test_momentary_401_storage_loggedin() {
add_task(async function test_momentary_401_storage_loggedin() {
_("Test a failure for any storage URL after login that's resolved by" +
"reassignment.");
let server = yield prepareServer();
let server = await prepareServer();
_("First sync to prepare server contents.");
Service.sync();
@ -336,7 +335,7 @@ add_task(function* test_momentary_401_storage_loggedin() {
do_check_true(Service.isLoggedIn, "already logged in");
yield syncAndExpectNodeReassignment(server,
await syncAndExpectNodeReassignment(server,
"weave:service:sync:error",
undo,
"weave:service:sync:finish",
@ -344,10 +343,10 @@ add_task(function* test_momentary_401_storage_loggedin() {
});
// This test ends up being a failing meta/global fetch *before we've logged in*.
add_task(function* test_momentary_401_storage_loggedout() {
add_task(async function test_momentary_401_storage_loggedout() {
_("Test a failure for any storage URL before login, not just engine parts. " +
"Resolved by reassignment.");
let server = yield prepareServer();
let server = await prepareServer();
// Return a 401 for all storage requests.
let oldHandler = server.toplevelHandlers.storage;
@ -360,7 +359,7 @@ add_task(function* test_momentary_401_storage_loggedout() {
do_check_false(Service.isLoggedIn, "already logged in");
yield syncAndExpectNodeReassignment(server,
await syncAndExpectNodeReassignment(server,
"weave:service:login:error",
undo,
"weave:service:sync:finish",

View File

@ -6,7 +6,7 @@ Cu.import("resource://services-sync/util.js");
Cu.import("resource://testing-common/services/sync/fxa_utils.js");
Cu.import("resource://testing-common/services/sync/utils.js");
add_task(function* test_findCluster() {
add_task(async function test_findCluster() {
_("Test FxA _findCluster()");
_("_findCluster() throws on 500 errors.");
@ -16,8 +16,8 @@ add_task(function* test_findCluster() {
body: "",
});
yield Service.identity.initializeWithCurrentIdentity();
yield Assert.rejects(Service.identity.whenReadyToAuthenticate.promise,
await Service.identity.initializeWithCurrentIdentity();
await Assert.rejects(Service.identity.whenReadyToAuthenticate.promise,
"should reject due to 500");
Assert.throws(function() {
@ -31,8 +31,8 @@ add_task(function* test_findCluster() {
body: "{}",
});
yield Service.identity.initializeWithCurrentIdentity();
yield Assert.rejects(Service.identity.whenReadyToAuthenticate.promise,
await Service.identity.initializeWithCurrentIdentity();
await Assert.rejects(Service.identity.whenReadyToAuthenticate.promise,
"should reject due to 401");
cluster = Service._clusterManager._findCluster();
@ -53,8 +53,8 @@ add_task(function* test_findCluster() {
})
});
yield Service.identity.initializeWithCurrentIdentity();
yield Service.identity.whenReadyToAuthenticate.promise;
await Service.identity.initializeWithCurrentIdentity();
await Service.identity.whenReadyToAuthenticate.promise;
cluster = Service._clusterManager._findCluster();
// The cluster manager ensures a trailing "/"
Assert.strictEqual(cluster, endpoint + "/");

View File

@ -11,12 +11,12 @@ function run_test() {
run_next_test();
}
add_task(function* test_startover() {
add_task(async function test_startover() {
let oldValue = Services.prefs.getBoolPref("services.sync-testing.startOverKeepIdentity", true);
Services.prefs.setBoolPref("services.sync-testing.startOverKeepIdentity", false);
ensureLegacyIdentityManager();
yield configureIdentity({username: "johndoe"});
await configureIdentity({username: "johndoe"});
// The boolean flag on the xpcom service should reflect a legacy provider.
let xps = Cc["@mozilla.org/weave/service;1"]
@ -38,14 +38,15 @@ add_task(function* test_startover() {
// remember some stuff so we can reset it after.
let oldIdentity = Service.identity;
let oldClusterManager = Service._clusterManager;
let deferred = Promise.defer();
Services.obs.addObserver(function observeStartOverFinished() {
Services.obs.removeObserver(observeStartOverFinished, "weave:service:start-over:finish");
deferred.resolve();
}, "weave:service:start-over:finish", false);
let promiseStartOver = new Promise(resolve => {
Services.obs.addObserver(function observeStartOverFinished() {
Services.obs.removeObserver(observeStartOverFinished, "weave:service:start-over:finish");
resolve();
}, "weave:service:start-over:finish", false);
});
Service.startOver();
yield deferred.promise; // wait for the observer to fire.
await promiseStartOver; // wait for the observer to fire.
// the xpcom service should indicate FxA is enabled.
do_check_true(xps.fxAccountsEnabled);

View File

@ -49,7 +49,7 @@ function shared_setup() {
return [engine, rotaryColl, clientsColl, keysWBO, global];
}
add_task(function *hmac_error_during_404() {
add_task(async function hmac_error_during_404() {
_("Attempt to replicate the HMAC error setup.");
let [engine, rotaryColl, clientsColl, keysWBO, global] = shared_setup();
@ -83,14 +83,14 @@ add_task(function *hmac_error_during_404() {
try {
_("Syncing.");
yield sync_and_validate_telem();
await sync_and_validate_telem();
_("Partially resetting client, as if after a restart, and forcing redownload.");
Service.collectionKeys.clear();
engine.lastSync = 0; // So that we redownload records.
key404Counter = 1;
_("---------------------------");
yield sync_and_validate_telem();
await sync_and_validate_telem();
_("---------------------------");
// Two rotary items, one client record... no errors.
@ -98,7 +98,7 @@ add_task(function *hmac_error_during_404() {
} finally {
Svc.Prefs.resetBranch("");
Service.recordManager.clearCache();
yield new Promise(resolve => server.stop(resolve));
await promiseStopServer(server);
}
});

View File

@ -18,12 +18,6 @@ var clientsEngine = Service.clientsEngine;
// the next sync.
clientsEngine._removeRemoteClient = id => {};
function promiseStopServer(server) {
let deferred = Promise.defer();
server.stop(deferred.resolve);
return deferred.promise;
}
function sync_httpd_setup() {
let global = new ServerWBO("global", {
syncID: Service.syncID,
@ -46,8 +40,8 @@ function sync_httpd_setup() {
});
}
function* setUp(server) {
yield configureIdentity({username: "johndoe"});
async function setUp(server) {
await configureIdentity({username: "johndoe"});
Service.serverURL = server.baseURI + "/";
Service.clusterURL = server.baseURI + "/";
generateNewKeys(Service.collectionKeys);
@ -65,7 +59,7 @@ function run_test() {
run_next_test();
}
add_identity_test(this, function* test_successful_sync_adjustSyncInterval() {
add_identity_test(this, async function test_successful_sync_adjustSyncInterval() {
_("Test successful sync calling adjustSyncInterval");
let syncSuccesses = 0;
function onSyncFinish() {
@ -75,7 +69,7 @@ add_identity_test(this, function* test_successful_sync_adjustSyncInterval() {
Svc.Obs.add("weave:service:sync:finish", onSyncFinish);
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
// Confirm defaults
do_check_false(scheduler.idle);
@ -161,10 +155,10 @@ add_identity_test(this, function* test_successful_sync_adjustSyncInterval() {
Svc.Obs.remove("weave:service:sync:finish", onSyncFinish);
Service.startOver();
yield promiseStopServer(server);
await promiseStopServer(server);
});
add_identity_test(this, function* test_unsuccessful_sync_adjustSyncInterval() {
add_identity_test(this, async function test_unsuccessful_sync_adjustSyncInterval() {
_("Test unsuccessful sync calling adjustSyncInterval");
let syncFailures = 0;
@ -179,7 +173,7 @@ add_identity_test(this, function* test_unsuccessful_sync_adjustSyncInterval() {
Svc.Prefs.set("firstSync", "notReady");
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
// Confirm defaults
do_check_false(scheduler.idle);
@ -266,12 +260,12 @@ add_identity_test(this, function* test_unsuccessful_sync_adjustSyncInterval() {
Service.startOver();
Svc.Obs.remove("weave:service:sync:error", onSyncError);
yield promiseStopServer(server);
await promiseStopServer(server);
});
add_identity_test(this, function* test_back_triggers_sync() {
add_identity_test(this, async function test_back_triggers_sync() {
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
// Single device: no sync triggered.
scheduler.idle = true;
@ -282,28 +276,25 @@ add_identity_test(this, function* test_back_triggers_sync() {
clientsEngine._store.create({id: "foo", cleartext: "bar"});
scheduler.updateClientMode();
let deferred = Promise.defer();
Svc.Obs.add("weave:service:sync:finish", function onSyncFinish() {
Svc.Obs.remove("weave:service:sync:finish", onSyncFinish);
Service.recordManager.clearCache();
Svc.Prefs.resetBranch("");
scheduler.setDefaults();
clientsEngine.resetClient();
Service.startOver();
server.stop(deferred.resolve);
});
let promiseDone = promiseOneObserver("weave:service:sync:finish");
scheduler.idle = true;
scheduler.observe(null, "active", Svc.Prefs.get("scheduler.idleTime"));
do_check_false(scheduler.idle);
yield deferred.promise;
await promiseDone;
Service.recordManager.clearCache();
Svc.Prefs.resetBranch("");
scheduler.setDefaults();
clientsEngine.resetClient();
Service.startOver();
await promiseStopServer(server);
});
add_identity_test(this, function* test_adjust_interval_on_sync_error() {
add_identity_test(this, async function test_adjust_interval_on_sync_error() {
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
let syncFailures = 0;
function onSyncError() {
@ -329,17 +320,17 @@ add_identity_test(this, function* test_adjust_interval_on_sync_error() {
Svc.Obs.remove("weave:service:sync:error", onSyncError);
Service.startOver();
yield promiseStopServer(server);
await promiseStopServer(server);
});
add_identity_test(this, function* test_bug671378_scenario() {
add_identity_test(this, async function test_bug671378_scenario() {
// Test scenario similar to bug 671378. This bug appeared when a score
// update occurred that wasn't large enough to trigger a sync so
// scheduleNextSync() was called without a time interval parameter,
// setting nextSync to a non-zero value and preventing the timer from
// being adjusted in the next call to scheduleNextSync().
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
let syncSuccesses = 0;
function onSyncFinish() {
@ -355,25 +346,26 @@ add_identity_test(this, function* test_bug671378_scenario() {
do_check_eq(scheduler.syncInterval, scheduler.singleDeviceInterval);
do_check_eq(scheduler.syncTimer.delay, scheduler.singleDeviceInterval);
let deferred = Promise.defer();
// Wrap scheduleNextSync so we are notified when it is finished.
scheduler._scheduleNextSync = scheduler.scheduleNextSync;
scheduler.scheduleNextSync = function() {
scheduler._scheduleNextSync();
let promiseDone = new Promise(resolve => {
// Wrap scheduleNextSync so we are notified when it is finished.
scheduler._scheduleNextSync = scheduler.scheduleNextSync;
scheduler.scheduleNextSync = function() {
scheduler._scheduleNextSync();
// Check on sync:finish scheduleNextSync sets the appropriate
// syncInterval and syncTimer values.
if (syncSuccesses == 2) {
do_check_neq(scheduler.nextSync, 0);
do_check_eq(scheduler.syncInterval, scheduler.activeInterval);
do_check_true(scheduler.syncTimer.delay <= scheduler.activeInterval);
// Check on sync:finish scheduleNextSync sets the appropriate
// syncInterval and syncTimer values.
if (syncSuccesses == 2) {
do_check_neq(scheduler.nextSync, 0);
do_check_eq(scheduler.syncInterval, scheduler.activeInterval);
do_check_true(scheduler.syncTimer.delay <= scheduler.activeInterval);
scheduler.scheduleNextSync = scheduler._scheduleNextSync;
Svc.Obs.remove("weave:service:sync:finish", onSyncFinish);
Service.startOver();
server.stop(deferred.resolve);
}
};
scheduler.scheduleNextSync = scheduler._scheduleNextSync;
Svc.Obs.remove("weave:service:sync:finish", onSyncFinish);
Service.startOver();
server.stop(resolve);
}
};
});
// Set nextSync != 0
// syncInterval still hasn't been set by call to updateClientMode.
@ -394,7 +386,7 @@ add_identity_test(this, function* test_bug671378_scenario() {
clientsEngine._store.create({id: "foo", cleartext: "bar"});
Service.sync();
yield deferred.promise;
await promiseDone;
});
add_test(function test_adjust_timer_larger_syncInterval() {

View File

@ -12,6 +12,7 @@ Cu.import("resource://services-sync/status.js");
Cu.import("resource://services-sync/util.js");
Cu.import("resource://testing-common/services/sync/rotaryengine.js");
Cu.import("resource://testing-common/services/sync/utils.js");
Cu.import("resource://gre/modules/PromiseUtils.jsm");
Service.engineManager.clear();
@ -76,7 +77,7 @@ function installNodeHandler(server, next) {
}
function prepareServer() {
let deferred = Promise.defer();
let deferred = PromiseUtils.defer();
configureIdentity({username: "johndoe"}).then(() => {
let server = new SyncServer();
server.registerUser("johndoe");
@ -107,9 +108,9 @@ function getReassigned() {
* Runs `between` between the two. This can be used to undo deliberate failure
* setup, detach observers, etc.
*/
function* syncAndExpectNodeReassignment(server, firstNotification, between,
async function syncAndExpectNodeReassignment(server, firstNotification, between,
secondNotification, url) {
let deferred = Promise.defer();
let deferred = PromiseUtils.defer();
function onwards() {
let nodeFetched = false;
function onFirstSync() {
@ -158,12 +159,12 @@ function* syncAndExpectNodeReassignment(server, firstNotification, between,
do_check_eq(request.response.status, 401);
Utils.nextTick(onwards);
});
yield deferred.promise;
await deferred.promise;
}
add_task(function* test_momentary_401_engine() {
add_task(async function test_momentary_401_engine() {
_("Test a failure for engine URLs that's resolved by reassignment.");
let server = yield prepareServer();
let server = await prepareServer();
let john = server.user("johndoe");
_("Enabling the Rotary engine.");
@ -205,7 +206,7 @@ add_task(function* test_momentary_401_engine() {
Svc.Obs.add("weave:service:login:start", onLoginStart);
}
yield syncAndExpectNodeReassignment(server,
await syncAndExpectNodeReassignment(server,
"weave:service:sync:finish",
between,
"weave:service:sync:finish",
@ -213,9 +214,9 @@ add_task(function* test_momentary_401_engine() {
});
// This test ends up being a failing fetch *after we're already logged in*.
add_task(function* test_momentary_401_info_collections() {
add_task(async function test_momentary_401_info_collections() {
_("Test a failure for info/collections that's resolved by reassignment.");
let server = yield prepareServer();
let server = await prepareServer();
_("First sync to prepare server contents.");
Service.sync();
@ -229,17 +230,17 @@ add_task(function* test_momentary_401_info_collections() {
server.toplevelHandlers.info = oldHandler;
}
yield syncAndExpectNodeReassignment(server,
await syncAndExpectNodeReassignment(server,
"weave:service:sync:error",
undo,
"weave:service:sync:finish",
Service.infoURL);
});
add_task(function* test_momentary_401_storage_loggedin() {
add_task(async function test_momentary_401_storage_loggedin() {
_("Test a failure for any storage URL, not just engine parts. " +
"Resolved by reassignment.");
let server = yield prepareServer();
let server = await prepareServer();
_("Performing initial sync to ensure we are logged in.")
Service.sync();
@ -254,17 +255,17 @@ add_task(function* test_momentary_401_storage_loggedin() {
}
do_check_true(Service.isLoggedIn, "already logged in");
yield syncAndExpectNodeReassignment(server,
await syncAndExpectNodeReassignment(server,
"weave:service:sync:error",
undo,
"weave:service:sync:finish",
Service.storageURL + "meta/global");
});
add_task(function* test_momentary_401_storage_loggedout() {
add_task(async function test_momentary_401_storage_loggedout() {
_("Test a failure for any storage URL, not just engine parts. " +
"Resolved by reassignment.");
let server = yield prepareServer();
let server = await prepareServer();
// Return a 401 for all storage requests.
let oldHandler = server.toplevelHandlers.storage;
@ -276,18 +277,18 @@ add_task(function* test_momentary_401_storage_loggedout() {
}
do_check_false(Service.isLoggedIn, "not already logged in");
yield syncAndExpectNodeReassignment(server,
await syncAndExpectNodeReassignment(server,
"weave:service:login:error",
undo,
"weave:service:sync:finish",
Service.storageURL + "meta/global");
});
add_task(function* test_loop_avoidance_storage() {
add_task(async function test_loop_avoidance_storage() {
_("Test that a repeated failure doesn't result in a sync loop " +
"if node reassignment cannot resolve the failure.");
let server = yield prepareServer();
let server = await prepareServer();
// Return a 401 for all storage requests.
let oldHandler = server.toplevelHandlers.storage;
@ -298,7 +299,7 @@ add_task(function* test_loop_avoidance_storage() {
let thirdNotification = "weave:service:sync:finish";
let nodeFetched = false;
let deferred = Promise.defer();
let deferred = PromiseUtils.defer();
// Track the time. We want to make sure the duration between the first and
// second sync is small, and then that the duration between second and third
@ -380,19 +381,19 @@ add_task(function* test_loop_avoidance_storage() {
now = Date.now();
Service.sync();
yield deferred.promise;
await deferred.promise;
});
add_task(function* test_loop_avoidance_engine() {
add_task(async function test_loop_avoidance_engine() {
_("Test that a repeated 401 in an engine doesn't result in a sync loop " +
"if node reassignment cannot resolve the failure.");
let server = yield prepareServer();
let server = await prepareServer();
let john = server.user("johndoe");
_("Enabling the Rotary engine.");
let engine = Service.engineManager.get("rotary");
engine.enabled = true;
let deferred = Promise.defer();
let deferred = PromiseUtils.defer();
// We need the server to be correctly set up prior to experimenting. Do this
// through a sync.
@ -519,5 +520,5 @@ add_task(function* test_loop_avoidance_engine() {
now = Date.now();
Service.sync();
yield deferred.promise;
await deferred.promise;
});

View File

@ -28,8 +28,8 @@ function run_test() {
run_next_test();
}
add_identity_test(this, function* test_resetLocalData() {
yield configureIdentity();
add_identity_test(this, async function test_resetLocalData() {
await configureIdentity();
Service.status.enforceBackoff = true;
Service.status.backoffInterval = 42;
Service.status.minimumNextSync = 23;

View File

@ -8,7 +8,7 @@ Svc.DefaultPrefs.set("registerEngines", "");
Cu.import("resource://services-sync/service.js");
// configure the identity we use for this test.
identityConfig = makeIdentityConfig({username: "johndoe"});
const identityConfig = makeIdentityConfig({username: "johndoe"});
function FakeCollection() {
this.deleted = false;
@ -31,13 +31,13 @@ FakeCollection.prototype = {
}
};
function* setUpTestFixtures(server) {
async function setUpTestFixtures(server) {
let cryptoService = new FakeCryptoService();
Service.serverURL = server.baseURI + "/";
Service.clusterURL = server.baseURI + "/";
yield configureIdentity(identityConfig);
await configureIdentity(identityConfig);
}
@ -46,13 +46,7 @@ function run_test() {
run_next_test();
}
function promiseStopServer(server) {
let deferred = Promise.defer();
server.stop(deferred.resolve);
return deferred.promise;
}
add_identity_test(this, function* test_wipeServer_list_success() {
add_identity_test(this, async function test_wipeServer_list_success() {
_("Service.wipeServer() deletes collections given as argument.");
let steam_coll = new FakeCollection();
@ -65,7 +59,7 @@ add_identity_test(this, function* test_wipeServer_list_success() {
});
try {
yield setUpTestFixtures(server);
await setUpTestFixtures(server);
new SyncTestingInfrastructure(server, "johndoe", "irrelevant", "irrelevant");
_("Confirm initial environment.");
@ -81,12 +75,12 @@ add_identity_test(this, function* test_wipeServer_list_success() {
do_check_true(diesel_coll.deleted);
} finally {
yield promiseStopServer(server);
await promiseStopServer(server);
Svc.Prefs.resetBranch("");
}
});
add_identity_test(this, function* test_wipeServer_list_503() {
add_identity_test(this, async function test_wipeServer_list_503() {
_("Service.wipeServer() deletes collections given as argument.");
let steam_coll = new FakeCollection();
@ -99,7 +93,7 @@ add_identity_test(this, function* test_wipeServer_list_503() {
});
try {
yield setUpTestFixtures(server);
await setUpTestFixtures(server);
new SyncTestingInfrastructure(server, "johndoe", "irrelevant", "irrelevant");
_("Confirm initial environment.");
@ -122,12 +116,12 @@ add_identity_test(this, function* test_wipeServer_list_503() {
do_check_false(diesel_coll.deleted);
} finally {
yield promiseStopServer(server);
await promiseStopServer(server);
Svc.Prefs.resetBranch("");
}
});
add_identity_test(this, function* test_wipeServer_all_success() {
add_identity_test(this, async function test_wipeServer_all_success() {
_("Service.wipeServer() deletes all the things.");
/**
@ -145,7 +139,7 @@ add_identity_test(this, function* test_wipeServer_all_success() {
let server = httpd_setup({
"/1.1/johndoe/storage": storageHandler
});
yield setUpTestFixtures(server);
await setUpTestFixtures(server);
_("Try deletion.");
new SyncTestingInfrastructure(server, "johndoe", "irrelevant", "irrelevant");
@ -153,11 +147,11 @@ add_identity_test(this, function* test_wipeServer_all_success() {
do_check_true(deleted);
do_check_eq(returnedTimestamp, serverTimestamp);
yield promiseStopServer(server);
await promiseStopServer(server);
Svc.Prefs.resetBranch("");
});
add_identity_test(this, function* test_wipeServer_all_404() {
add_identity_test(this, async function test_wipeServer_all_404() {
_("Service.wipeServer() accepts a 404.");
/**
@ -177,7 +171,7 @@ add_identity_test(this, function* test_wipeServer_all_404() {
let server = httpd_setup({
"/1.1/johndoe/storage": storageHandler
});
yield setUpTestFixtures(server);
await setUpTestFixtures(server);
_("Try deletion.");
new SyncTestingInfrastructure(server, "johndoe", "irrelevant", "irrelevant");
@ -185,11 +179,11 @@ add_identity_test(this, function* test_wipeServer_all_404() {
do_check_true(deleted);
do_check_eq(returnedTimestamp, serverTimestamp);
yield promiseStopServer(server);
await promiseStopServer(server);
Svc.Prefs.resetBranch("");
});
add_identity_test(this, function* test_wipeServer_all_503() {
add_identity_test(this, async function test_wipeServer_all_503() {
_("Service.wipeServer() throws if it encounters a non-200/404 response.");
/**
@ -204,7 +198,7 @@ add_identity_test(this, function* test_wipeServer_all_503() {
let server = httpd_setup({
"/1.1/johndoe/storage": storageHandler
});
yield setUpTestFixtures(server);
await setUpTestFixtures(server);
_("Try deletion.");
let error;
@ -217,14 +211,14 @@ add_identity_test(this, function* test_wipeServer_all_503() {
}
do_check_eq(error.status, 503);
yield promiseStopServer(server);
await promiseStopServer(server);
Svc.Prefs.resetBranch("");
});
add_identity_test(this, function* test_wipeServer_all_connectionRefused() {
add_identity_test(this, async function test_wipeServer_all_connectionRefused() {
_("Service.wipeServer() throws if it encounters a network problem.");
let server = httpd_setup({});
yield setUpTestFixtures(server);
await setUpTestFixtures(server);
Service.serverURL = "http://localhost:4352/";
Service.clusterURL = "http://localhost:4352/";
@ -238,5 +232,5 @@ add_identity_test(this, function* test_wipeServer_all_connectionRefused() {
}
Svc.Prefs.resetBranch("");
yield promiseStopServer(server);
await promiseStopServer(server);
});

View File

@ -81,16 +81,16 @@ function configureClients(clients, clientSettings = {}) {
}
// The tests.
add_task(function* test_noClients() {
add_task(async function test_noClients() {
// no clients, can't be tabs.
yield configureClients({});
await configureClients({});
let tabs = yield SyncedTabs.getTabClients();
let tabs = await SyncedTabs.getTabClients();
equal(Object.keys(tabs).length, 0);
});
add_task(function* test_clientWithTabs() {
yield configureClients({
add_task(async function test_clientWithTabs() {
await configureClients({
guid_desktop: {
clientName: "My Desktop",
tabs: [
@ -105,7 +105,7 @@ add_task(function* test_clientWithTabs() {
}
});
let clients = yield SyncedTabs.getTabClients();
let clients = await SyncedTabs.getTabClients();
equal(clients.length, 2);
clients.sort((a, b) => { return a.name.localeCompare(b.name);});
equal(clients[0].tabs.length, 1);
@ -115,8 +115,8 @@ add_task(function* test_clientWithTabs() {
equal(clients[1].tabs.length, 0);
});
add_task(function* test_staleClientWithTabs() {
yield configureClients({
add_task(async function test_staleClientWithTabs() {
await configureClients({
guid_desktop: {
clientName: "My Desktop",
tabs: [
@ -156,7 +156,7 @@ add_task(function* test_staleClientWithTabs() {
// of the possibly stale tabs collection.
guid_stale_name_desktop: "My Laptop",
});
let clients = yield SyncedTabs.getTabClients();
let clients = await SyncedTabs.getTabClients();
clients.sort((a, b) => { return a.name.localeCompare(b.name);});
equal(clients.length, 3);
equal(clients[0].name, "My Desktop");
@ -169,9 +169,9 @@ add_task(function* test_staleClientWithTabs() {
equal(clients[2].tabs.length, 0);
});
add_task(function* test_clientWithTabsIconsDisabled() {
add_task(async function test_clientWithTabsIconsDisabled() {
Services.prefs.setBoolPref("services.sync.syncedTabs.showRemoteIcons", false);
yield configureClients({
await configureClients({
guid_desktop: {
clientName: "My Desktop",
tabs: [
@ -182,7 +182,7 @@ add_task(function* test_clientWithTabsIconsDisabled() {
},
});
let clients = yield SyncedTabs.getTabClients();
let clients = await SyncedTabs.getTabClients();
equal(clients.length, 1);
clients.sort((a, b) => { return a.name.localeCompare(b.name);});
equal(clients[0].tabs.length, 1);
@ -192,9 +192,9 @@ add_task(function* test_clientWithTabsIconsDisabled() {
Services.prefs.clearUserPref("services.sync.syncedTabs.showRemoteIcons");
});
add_task(function* test_filter() {
add_task(async function test_filter() {
// Nothing matches.
yield configureClients({
await configureClients({
guid_desktop: {
clientName: "My Desktop",
tabs: [
@ -209,12 +209,12 @@ add_task(function* test_filter() {
},
});
let clients = yield SyncedTabs.getTabClients("foo");
let clients = await SyncedTabs.getTabClients("foo");
equal(clients.length, 1);
equal(clients[0].tabs.length, 1);
equal(clients[0].tabs[0].url, "http://foo.com/");
// check it matches the title.
clients = yield SyncedTabs.getTabClients("test");
clients = await SyncedTabs.getTabClients("test");
equal(clients.length, 1);
equal(clients[0].tabs.length, 1);
equal(clients[0].tabs[0].url, "http://foo.com/");

View File

@ -26,9 +26,9 @@ function cleanAndGo(server) {
server.stop(run_next_test);
}
function promiseClean(server) {
async function promiseClean(server) {
clean();
return new Promise(resolve => server.stop(resolve));
await promiseStopServer(server);
}
function configureService(server, username, password) {
@ -676,7 +676,7 @@ add_test(function test_processIncoming_mobile_batchSize() {
});
add_task(function *test_processIncoming_store_toFetch() {
add_task(async function test_processIncoming_store_toFetch() {
_("If processIncoming fails in the middle of a batch on mobile, state is saved in toFetch and lastSync.");
Service.identity.username = "foo";
Svc.Prefs.set("client.type", "mobile");
@ -723,7 +723,7 @@ add_task(function *test_processIncoming_store_toFetch() {
let error;
try {
yield sync_engine_and_validate_telem(engine, true);
await sync_engine_and_validate_telem(engine, true);
} catch (ex) {
error = ex;
}
@ -738,7 +738,7 @@ add_task(function *test_processIncoming_store_toFetch() {
do_check_eq(engine.lastSync, collection.wbo("record-no-99").modified);
} finally {
yield promiseClean(server);
await promiseClean(server);
}
});
@ -1229,7 +1229,7 @@ add_test(function test_processIncoming_failed_records() {
});
add_task(function *test_processIncoming_decrypt_failed() {
add_task(async function test_processIncoming_decrypt_failed() {
_("Ensure that records failing to decrypt are either replaced or refetched.");
Service.identity.username = "foo";
@ -1288,7 +1288,7 @@ add_task(function *test_processIncoming_decrypt_failed() {
});
engine.lastSync = collection.wbo("nojson").modified - 1;
let ping = yield sync_engine_and_validate_telem(engine, true);
let ping = await sync_engine_and_validate_telem(engine, true);
do_check_eq(ping.engines[0].incoming.applied, 2);
do_check_eq(ping.engines[0].incoming.failed, 4);
do_check_eq(ping.engines[0].incoming.newFailed, 4);
@ -1305,7 +1305,7 @@ add_task(function *test_processIncoming_decrypt_failed() {
do_check_eq(observerSubject.failed, 4);
} finally {
yield promiseClean(server);
await promiseClean(server);
}
});
@ -1416,7 +1416,7 @@ add_test(function test_uploadOutgoing_huge() {
});
add_task(function *test_uploadOutgoing_failed() {
add_task(async function test_uploadOutgoing_failed() {
_("SyncEngine._uploadOutgoing doesn't clear the tracker of objects that failed to upload.");
Service.identity.username = "foo";
@ -1459,7 +1459,7 @@ add_task(function *test_uploadOutgoing_failed() {
do_check_eq(engine._tracker.changedIDs['peppercorn'], PEPPERCORN_CHANGED);
engine.enabled = true;
yield sync_engine_and_validate_telem(engine, true);
await sync_engine_and_validate_telem(engine, true);
// Local timestamp has been set.
do_check_true(engine.lastSyncLocal > 0);
@ -1474,7 +1474,7 @@ add_task(function *test_uploadOutgoing_failed() {
do_check_eq(engine._tracker.changedIDs['peppercorn'], PEPPERCORN_CHANGED);
} finally {
yield promiseClean(server);
await promiseClean(server);
}
});
@ -1714,7 +1714,7 @@ add_test(function test_syncFinish_deleteLotsInBatches() {
});
add_task(function *test_sync_partialUpload() {
add_task(async function test_sync_partialUpload() {
_("SyncEngine.sync() keeps changedIDs that couldn't be uploaded.");
Service.identity.username = "foo";
@ -1762,7 +1762,7 @@ add_task(function *test_sync_partialUpload() {
engine.enabled = true;
let error;
try {
yield sync_engine_and_validate_telem(engine, true);
await sync_engine_and_validate_telem(engine, true);
} catch (ex) {
error = ex;
}
@ -1785,7 +1785,7 @@ add_task(function *test_sync_partialUpload() {
}
} finally {
yield promiseClean(server);
await promiseClean(server);
}
});

View File

@ -57,32 +57,25 @@ function sync_httpd_setup() {
});
}
function setUp(server) {
let deferred = Promise.defer();
configureIdentity({username: "johndoe"}).then(() => {
Service.clusterURL = server.baseURI + "/";
async function setUp(server) {
await configureIdentity({username: "johndoe"});
generateNewKeys(Service.collectionKeys);
let serverKeys = Service.collectionKeys.asWBO("crypto", "keys");
serverKeys.encrypt(Service.identity.syncKeyBundle);
let result = serverKeys.upload(Service.resource(Service.cryptoKeysURL)).success;
deferred.resolve(result);
});
return deferred.promise;
Service.clusterURL = server.baseURI + "/";
generateNewKeys(Service.collectionKeys);
let serverKeys = Service.collectionKeys.asWBO("crypto", "keys");
serverKeys.encrypt(Service.identity.syncKeyBundle);
let result = serverKeys.upload(Service.resource(Service.cryptoKeysURL)).success;
return result;
}
function cleanUpAndGo(server) {
let deferred = Promise.defer();
Utils.nextTick(function () {
clientsEngine._store.wipe();
Service.startOver();
if (server) {
server.stop(deferred.resolve);
} else {
deferred.resolve();
}
});
return deferred.promise;
async function cleanUpAndGo(server) {
await promiseNextTick();
clientsEngine._store.wipe();
Service.startOver();
if (server) {
await promiseStopServer(server);
}
}
function run_test() {
@ -174,7 +167,7 @@ add_test(function test_prefAttributes() {
run_next_test();
});
add_identity_test(this, function* test_updateClientMode() {
add_identity_test(this, async function test_updateClientMode() {
_("Test updateClientMode adjusts scheduling attributes based on # of clients appropriately");
do_check_eq(scheduler.syncThreshold, SINGLE_USER_THRESHOLD);
do_check_eq(scheduler.syncInterval, scheduler.singleDeviceInterval);
@ -201,10 +194,10 @@ add_identity_test(this, function* test_updateClientMode() {
do_check_false(scheduler.numClients > 1);
do_check_false(scheduler.idle);
yield cleanUpAndGo();
await cleanUpAndGo();
});
add_identity_test(this, function* test_masterpassword_locked_retry_interval() {
add_identity_test(this, async function test_masterpassword_locked_retry_interval() {
_("Test Status.login = MASTER_PASSWORD_LOCKED results in reschedule at MASTER_PASSWORD interval");
let loginFailed = false;
Svc.Obs.add("weave:service:login:error", function onLoginError() {
@ -227,7 +220,7 @@ add_identity_test(this, function* test_masterpassword_locked_retry_interval() {
};
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
Service.sync();
@ -238,10 +231,10 @@ add_identity_test(this, function* test_masterpassword_locked_retry_interval() {
Service.verifyLogin = oldVerifyLogin;
SyncScheduler.prototype.scheduleAtInterval = oldScheduleAtInterval;
yield cleanUpAndGo(server);
await cleanUpAndGo(server);
});
add_identity_test(this, function* test_calculateBackoff() {
add_identity_test(this, async function test_calculateBackoff() {
do_check_eq(Status.backoffInterval, 0);
// Test no interval larger than the maximum backoff is used if
@ -260,25 +253,22 @@ add_identity_test(this, function* test_calculateBackoff() {
do_check_eq(backoffInterval, MAXIMUM_BACKOFF_INTERVAL + 10);
yield cleanUpAndGo();
await cleanUpAndGo();
});
add_identity_test(this, function* test_scheduleNextSync_nowOrPast() {
let deferred = Promise.defer();
Svc.Obs.add("weave:service:sync:finish", function onSyncFinish() {
Svc.Obs.remove("weave:service:sync:finish", onSyncFinish);
cleanUpAndGo(server).then(deferred.resolve);
});
add_identity_test(this, async function test_scheduleNextSync_nowOrPast() {
let promiseObserved = promiseOneObserver("weave:service:sync:finish");
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
// We're late for a sync...
scheduler.scheduleNextSync(-1);
yield deferred.promise;
await promiseObserved;
await cleanUpAndGo(server);
});
add_identity_test(this, function* test_scheduleNextSync_future_noBackoff() {
add_identity_test(this, async function test_scheduleNextSync_future_noBackoff() {
_("scheduleNextSync() uses the current syncInterval if no interval is provided.");
// Test backoffInterval is 0 as expected.
do_check_eq(Status.backoffInterval, 0);
@ -324,10 +314,10 @@ add_identity_test(this, function* test_scheduleNextSync_future_noBackoff() {
do_check_true(scheduler.nextSync <= Date.now() + 1);
do_check_eq(scheduler.syncTimer.delay, 1);
yield cleanUpAndGo();
await cleanUpAndGo();
});
add_identity_test(this, function* test_scheduleNextSync_future_backoff() {
add_identity_test(this, async function test_scheduleNextSync_future_backoff() {
_("scheduleNextSync() will honour backoff in all scheduling requests.");
// Let's take a backoff interval that's bigger than the default sync interval.
const BACKOFF = 7337;
@ -374,12 +364,12 @@ add_identity_test(this, function* test_scheduleNextSync_future_backoff() {
do_check_true(scheduler.nextSync <= Date.now() + Status.backoffInterval);
do_check_eq(scheduler.syncTimer.delay, Status.backoffInterval);
yield cleanUpAndGo();
await cleanUpAndGo();
});
add_identity_test(this, function* test_handleSyncError() {
add_identity_test(this, async function test_handleSyncError() {
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
// Force sync to fail.
Svc.Prefs.set("firstSync", "notReady");
@ -433,19 +423,16 @@ add_identity_test(this, function* test_handleSyncError() {
scheduler.syncTimer.clear();
_("Arrange for a successful sync to reset the scheduler error count");
let deferred = Promise.defer();
Svc.Obs.add("weave:service:sync:finish", function onSyncFinish() {
Svc.Obs.remove("weave:service:sync:finish", onSyncFinish);
cleanUpAndGo(server).then(deferred.resolve);
});
let promiseObserved = promiseOneObserver("weave:service:sync:finish");
Svc.Prefs.set("firstSync", "wipeRemote");
scheduler.scheduleNextSync(-1);
yield deferred.promise;
await promiseObserved;
await cleanUpAndGo(server);
});
add_identity_test(this, function* test_client_sync_finish_updateClientMode() {
add_identity_test(this, async function test_client_sync_finish_updateClientMode() {
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
// Confirm defaults.
do_check_eq(scheduler.syncThreshold, SINGLE_USER_THRESHOLD);
@ -474,27 +461,22 @@ add_identity_test(this, function* test_client_sync_finish_updateClientMode() {
do_check_false(scheduler.numClients > 1);
do_check_false(scheduler.idle);
yield cleanUpAndGo(server);
await cleanUpAndGo(server);
});
add_identity_test(this, function* test_autoconnect_nextSync_past() {
let deferred = Promise.defer();
add_identity_test(this, async function test_autoconnect_nextSync_past() {
let promiseObserved = promiseOneObserver("weave:service:sync:finish");
// nextSync will be 0 by default, so it's way in the past.
Svc.Obs.add("weave:service:sync:finish", function onSyncFinish() {
Svc.Obs.remove("weave:service:sync:finish", onSyncFinish);
cleanUpAndGo(server).then(deferred.resolve);
});
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
scheduler.delayedAutoConnect(0);
yield deferred.promise;
await promiseObserved;
await cleanUpAndGo(server);
});
add_identity_test(this, function* test_autoconnect_nextSync_future() {
let deferred = Promise.defer();
add_identity_test(this, async function test_autoconnect_nextSync_future() {
let previousSync = Date.now() + scheduler.syncInterval / 2;
scheduler.nextSync = previousSync;
// nextSync rounds to the nearest second.
@ -507,24 +489,22 @@ add_identity_test(this, function* test_autoconnect_nextSync_future() {
}
Svc.Obs.add("weave:service:login:start", onLoginStart);
waitForZeroTimer(function () {
do_check_eq(scheduler.nextSync, expectedSync);
do_check_true(scheduler.syncTimer.delay >= expectedInterval);
Svc.Obs.remove("weave:service:login:start", onLoginStart);
cleanUpAndGo().then(deferred.resolve);
});
yield configureIdentity({username: "johndoe"});
await configureIdentity({username: "johndoe"});
scheduler.delayedAutoConnect(0);
yield deferred.promise;
await promiseZeroTimer();
do_check_eq(scheduler.nextSync, expectedSync);
do_check_true(scheduler.syncTimer.delay >= expectedInterval);
Svc.Obs.remove("weave:service:login:start", onLoginStart);
await cleanUpAndGo();
});
// XXX - this test can't be run with the browserid identity as it relies
// on the syncKey getter behaving in a certain way...
add_task(function* test_autoconnect_mp_locked() {
add_task(async function test_autoconnect_mp_locked() {
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
// Pretend user did not unlock master password.
let origLocked = Utils.mpLocked;
@ -538,30 +518,28 @@ add_task(function* test_autoconnect_mp_locked() {
throw "User canceled Master Password entry";
});
let deferred = Promise.defer();
// A locked master password will still trigger a sync, but then we'll hit
// MASTER_PASSWORD_LOCKED and hence MASTER_PASSWORD_LOCKED_RETRY_INTERVAL.
Svc.Obs.add("weave:service:login:error", function onLoginError() {
Svc.Obs.remove("weave:service:login:error", onLoginError);
Utils.nextTick(function aLittleBitAfterLoginError() {
do_check_eq(Status.login, MASTER_PASSWORD_LOCKED);
Utils.mpLocked = origLocked;
delete Service.identity.syncKey;
Service.identity.__defineGetter__("syncKey", origGetter);
Service.identity.__defineSetter__("syncKey", origSetter);
cleanUpAndGo(server).then(deferred.resolve);
});
});
let promiseObserved = promiseOneObserver("weave:service:login:error");
scheduler.delayedAutoConnect(0);
yield deferred.promise;
await promiseObserved;
await promiseNextTick();
do_check_eq(Status.login, MASTER_PASSWORD_LOCKED);
Utils.mpLocked = origLocked;
delete Service.identity.syncKey;
Service.identity.__defineGetter__("syncKey", origGetter);
Service.identity.__defineSetter__("syncKey", origSetter);
await cleanUpAndGo(server);
});
add_identity_test(this, function* test_no_autoconnect_during_wizard() {
add_identity_test(this, async function test_no_autoconnect_during_wizard() {
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
// Simulate the Sync setup wizard.
Svc.Prefs.set("firstSync", "notReady");
@ -572,17 +550,13 @@ add_identity_test(this, function* test_no_autoconnect_during_wizard() {
}
Svc.Obs.add("weave:service:login:start", onLoginStart);
let deferred = Promise.defer();
waitForZeroTimer(function () {
Svc.Obs.remove("weave:service:login:start", onLoginStart);
cleanUpAndGo(server).then(deferred.resolve);
});
scheduler.delayedAutoConnect(0);
yield deferred.promise;
await promiseZeroTimer();
Svc.Obs.remove("weave:service:login:start", onLoginStart);
await cleanUpAndGo(server);
});
add_identity_test(this, function* test_no_autoconnect_status_not_ok() {
add_identity_test(this, async function test_no_autoconnect_status_not_ok() {
let server = sync_httpd_setup();
// Ensure we don't actually try to sync (or log in for that matter).
@ -591,41 +565,34 @@ add_identity_test(this, function* test_no_autoconnect_status_not_ok() {
}
Svc.Obs.add("weave:service:login:start", onLoginStart);
let deferred = Promise.defer();
waitForZeroTimer(function () {
Svc.Obs.remove("weave:service:login:start", onLoginStart);
do_check_eq(Status.service, CLIENT_NOT_CONFIGURED);
do_check_eq(Status.login, LOGIN_FAILED_NO_USERNAME);
cleanUpAndGo(server).then(deferred.resolve);
});
scheduler.delayedAutoConnect(0);
yield deferred.promise;
await promiseZeroTimer();
Svc.Obs.remove("weave:service:login:start", onLoginStart);
do_check_eq(Status.service, CLIENT_NOT_CONFIGURED);
do_check_eq(Status.login, LOGIN_FAILED_NO_USERNAME);
await cleanUpAndGo(server);
});
add_identity_test(this, function* test_autoconnectDelay_pref() {
let deferred = Promise.defer();
Svc.Obs.add("weave:service:sync:finish", function onSyncFinish() {
Svc.Obs.remove("weave:service:sync:finish", onSyncFinish);
cleanUpAndGo(server).then(deferred.resolve);
});
add_identity_test(this, async function test_autoconnectDelay_pref() {
let promiseObserved = promiseOneObserver("weave:service:sync:finish");
Svc.Prefs.set("autoconnectDelay", 1);
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
Svc.Obs.notify("weave:service:ready");
// autoconnectDelay pref is multiplied by 1000.
do_check_eq(scheduler._autoTimer.delay, 1000);
do_check_eq(Status.service, STATUS_OK);
yield deferred.promise;
await promiseObserved;
await cleanUpAndGo(server);
});
add_identity_test(this, function* test_idle_adjustSyncInterval() {
add_identity_test(this, async function test_idle_adjustSyncInterval() {
// Confirm defaults.
do_check_eq(scheduler.idle, false);
@ -642,10 +609,10 @@ add_identity_test(this, function* test_idle_adjustSyncInterval() {
do_check_eq(scheduler.idle, true);
do_check_eq(scheduler.syncInterval, scheduler.idleInterval);
yield cleanUpAndGo();
await cleanUpAndGo();
});
add_identity_test(this, function* test_back_triggersSync() {
add_identity_test(this, async function test_back_triggersSync() {
// Confirm defaults.
do_check_false(scheduler.idle);
do_check_eq(Status.backoffInterval, 0);
@ -655,20 +622,17 @@ add_identity_test(this, function* test_back_triggersSync() {
scheduler.observe(null, "idle", Svc.Prefs.get("scheduler.idleTime"));
do_check_true(scheduler.idle);
let deferred = Promise.defer();
// We don't actually expect the sync (or the login, for that matter) to
// succeed. We just want to ensure that it was attempted.
Svc.Obs.add("weave:service:login:error", function onLoginError() {
Svc.Obs.remove("weave:service:login:error", onLoginError);
cleanUpAndGo().then(deferred.resolve);
});
let promiseObserved = promiseOneObserver("weave:service:login:error");
// Send an 'active' event to trigger sync soonish.
scheduler.observe(null, "active", Svc.Prefs.get("scheduler.idleTime"));
yield deferred.promise;
await promiseObserved;
await cleanUpAndGo();
});
add_identity_test(this, function* test_active_triggersSync_observesBackoff() {
add_identity_test(this, async function test_active_triggersSync_observesBackoff() {
// Confirm defaults.
do_check_false(scheduler.idle);
@ -684,22 +648,20 @@ add_identity_test(this, function* test_active_triggersSync_observesBackoff() {
}
Svc.Obs.add("weave:service:login:start", onLoginStart);
let deferred = Promise.defer();
timer = Utils.namedTimer(function () {
Svc.Obs.remove("weave:service:login:start", onLoginStart);
do_check_true(scheduler.nextSync <= Date.now() + Status.backoffInterval);
do_check_eq(scheduler.syncTimer.delay, Status.backoffInterval);
cleanUpAndGo().then(deferred.resolve);
}, IDLE_OBSERVER_BACK_DELAY * 1.5, {}, "timer");
let promiseTimer = promiseNamedTimer(IDLE_OBSERVER_BACK_DELAY * 1.5, {}, "timer");
// Send an 'active' event to try to trigger sync soonish.
scheduler.observe(null, "active", Svc.Prefs.get("scheduler.idleTime"));
yield deferred.promise;
await promiseTimer;
Svc.Obs.remove("weave:service:login:start", onLoginStart);
do_check_true(scheduler.nextSync <= Date.now() + Status.backoffInterval);
do_check_eq(scheduler.syncTimer.delay, Status.backoffInterval);
await cleanUpAndGo();
});
add_identity_test(this, function* test_back_debouncing() {
add_identity_test(this, async function test_back_debouncing() {
_("Ensure spurious back-then-idle events, as observed on OS X, don't trigger a sync.");
// Confirm defaults.
@ -719,19 +681,16 @@ add_identity_test(this, function* test_back_debouncing() {
scheduler.observe(null, "active", Svc.Prefs.get("scheduler.idleTime"));
scheduler.observe(null, "idle", Svc.Prefs.get("scheduler.idleTime"));
let deferred = Promise.defer();
timer = Utils.namedTimer(function () {
Svc.Obs.remove("weave:service:login:start", onLoginStart);
cleanUpAndGo().then(deferred.resolve);
}, IDLE_OBSERVER_BACK_DELAY * 1.5, {}, "timer");
yield deferred.promise;
await promiseNamedTimer(IDLE_OBSERVER_BACK_DELAY * 1.5, {}, "timer");
Svc.Obs.remove("weave:service:login:start", onLoginStart);
await cleanUpAndGo();
});
add_identity_test(this, function* test_no_sync_node() {
add_identity_test(this, async function test_no_sync_node() {
// Test when Status.sync == NO_SYNC_NODE_FOUND
// it is not overwritten on sync:finish
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
Service.serverURL = server.baseURI + "/";
@ -739,10 +698,10 @@ add_identity_test(this, function* test_no_sync_node() {
do_check_eq(Status.sync, NO_SYNC_NODE_FOUND);
do_check_eq(scheduler.syncTimer.delay, NO_SYNC_NODE_INTERVAL);
yield cleanUpAndGo(server);
await cleanUpAndGo(server);
});
add_identity_test(this, function* test_sync_failed_partial_500s() {
add_identity_test(this, async function test_sync_failed_partial_500s() {
_("Test a 5xx status calls handleSyncError.");
scheduler._syncErrors = MAX_ERROR_COUNT_BEFORE_BACKOFF;
let server = sync_httpd_setup();
@ -753,7 +712,7 @@ add_identity_test(this, function* test_sync_failed_partial_500s() {
do_check_eq(Status.sync, SYNC_SUCCEEDED);
do_check_true(yield setUp(server));
do_check_true(await setUp(server));
Service.sync();
@ -766,10 +725,10 @@ add_identity_test(this, function* test_sync_failed_partial_500s() {
do_check_true(scheduler.nextSync <= (Date.now() + maxInterval));
do_check_true(scheduler.syncTimer.delay <= maxInterval);
yield cleanUpAndGo(server);
await cleanUpAndGo(server);
});
add_identity_test(this, function* test_sync_failed_partial_400s() {
add_identity_test(this, async function test_sync_failed_partial_400s() {
_("Test a non-5xx status doesn't call handleSyncError.");
scheduler._syncErrors = MAX_ERROR_COUNT_BEFORE_BACKOFF;
let server = sync_httpd_setup();
@ -783,7 +742,7 @@ add_identity_test(this, function* test_sync_failed_partial_400s() {
do_check_eq(Status.sync, SYNC_SUCCEEDED);
do_check_true(yield setUp(server));
do_check_true(await setUp(server));
Service.sync();
@ -796,12 +755,12 @@ add_identity_test(this, function* test_sync_failed_partial_400s() {
do_check_true(scheduler.nextSync <= (Date.now() + scheduler.activeInterval));
do_check_true(scheduler.syncTimer.delay <= scheduler.activeInterval);
yield cleanUpAndGo(server);
await cleanUpAndGo(server);
});
add_identity_test(this, function* test_sync_X_Weave_Backoff() {
add_identity_test(this, async function test_sync_X_Weave_Backoff() {
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
// Use an odd value on purpose so that it doesn't happen to coincide with one
// of the sync intervals.
@ -851,12 +810,12 @@ add_identity_test(this, function* test_sync_X_Weave_Backoff() {
do_check_true(scheduler.nextSync >= Date.now() + minimumExpectedDelay);
do_check_true(scheduler.syncTimer.delay >= minimumExpectedDelay);
yield cleanUpAndGo(server);
await cleanUpAndGo(server);
});
add_identity_test(this, function* test_sync_503_Retry_After() {
add_identity_test(this, async function test_sync_503_Retry_After() {
let server = sync_httpd_setup();
yield setUp(server);
await setUp(server);
// Use an odd value on purpose so that it doesn't happen to coincide with one
// of the sync intervals.
@ -910,33 +869,18 @@ add_identity_test(this, function* test_sync_503_Retry_After() {
do_check_true(scheduler.nextSync >= Date.now() + minimumExpectedDelay);
do_check_true(scheduler.syncTimer.delay >= minimumExpectedDelay);
yield cleanUpAndGo(server);
await cleanUpAndGo(server);
});
add_identity_test(this, function* test_loginError_recoverable_reschedules() {
add_identity_test(this, async function test_loginError_recoverable_reschedules() {
_("Verify that a recoverable login error schedules a new sync.");
yield configureIdentity({username: "johndoe"});
await configureIdentity({username: "johndoe"});
Service.serverURL = "http://localhost:1234/";
Service.clusterURL = Service.serverURL;
Service.persistLogin();
Status.resetSync(); // reset Status.login
let deferred = Promise.defer();
Svc.Obs.add("weave:service:login:error", function onLoginError() {
Svc.Obs.remove("weave:service:login:error", onLoginError);
Utils.nextTick(function aLittleBitAfterLoginError() {
do_check_eq(Status.login, LOGIN_FAILED_NETWORK_ERROR);
let expectedNextSync = Date.now() + scheduler.syncInterval;
do_check_true(scheduler.nextSync > Date.now());
do_check_true(scheduler.nextSync <= expectedNextSync);
do_check_true(scheduler.syncTimer.delay > 0);
do_check_true(scheduler.syncTimer.delay <= scheduler.syncInterval);
Svc.Obs.remove("weave:service:sync:start", onSyncStart);
cleanUpAndGo().then(deferred.resolve);
});
});
let promiseObserved = promiseOneObserver("weave:service:login:error");
// Let's set it up so that a sync is overdue, both in terms of previously
// scheduled syncs and the global score. We still do not expect an immediate
@ -954,12 +898,24 @@ add_identity_test(this, function* test_loginError_recoverable_reschedules() {
do_check_eq(Status.login, LOGIN_SUCCEEDED);
scheduler.scheduleNextSync(0);
yield deferred.promise;
await promiseObserved;
await promiseNextTick();
do_check_eq(Status.login, LOGIN_FAILED_NETWORK_ERROR);
let expectedNextSync = Date.now() + scheduler.syncInterval;
do_check_true(scheduler.nextSync > Date.now());
do_check_true(scheduler.nextSync <= expectedNextSync);
do_check_true(scheduler.syncTimer.delay > 0);
do_check_true(scheduler.syncTimer.delay <= scheduler.syncInterval);
Svc.Obs.remove("weave:service:sync:start", onSyncStart);
await cleanUpAndGo()
});
add_identity_test(this, function* test_loginError_fatal_clearsTriggers() {
add_identity_test(this, async function test_loginError_fatal_clearsTriggers() {
_("Verify that a fatal login error clears sync triggers.");
yield configureIdentity({username: "johndoe"});
await configureIdentity({username: "johndoe"});
let server = httpd_setup({
"/1.1/johndoe/info/collections": httpd_handler(401, "Unauthorized")
@ -970,29 +926,7 @@ add_identity_test(this, function* test_loginError_fatal_clearsTriggers() {
Service.persistLogin();
Status.resetSync(); // reset Status.login
let deferred = Promise.defer();
Svc.Obs.add("weave:service:login:error", function onLoginError() {
Svc.Obs.remove("weave:service:login:error", onLoginError);
Utils.nextTick(function aLittleBitAfterLoginError() {
if (isConfiguredWithLegacyIdentity()) {
// for the "legacy" identity, a 401 on info/collections means the
// password is wrong, so we enter a "login rejected" state.
do_check_eq(Status.login, LOGIN_FAILED_LOGIN_REJECTED);
do_check_eq(scheduler.nextSync, 0);
do_check_eq(scheduler.syncTimer, null);
} else {
// For the FxA identity, a 401 on info/collections means a transient
// error, probably due to an inability to fetch a token.
do_check_eq(Status.login, LOGIN_FAILED_NETWORK_ERROR);
// syncs should still be scheduled.
do_check_true(scheduler.nextSync > Date.now());
do_check_true(scheduler.syncTimer.delay > 0);
}
cleanUpAndGo(server).then(deferred.resolve);
});
});
let promiseObserved = promiseOneObserver("weave:service:login:error");
// Sanity check.
do_check_eq(scheduler.nextSync, 0);
@ -1001,10 +935,28 @@ add_identity_test(this, function* test_loginError_fatal_clearsTriggers() {
do_check_eq(Status.login, LOGIN_SUCCEEDED);
scheduler.scheduleNextSync(0);
yield deferred.promise;
await promiseObserved;
await promiseNextTick();
if (isConfiguredWithLegacyIdentity()) {
// for the "legacy" identity, a 401 on info/collections means the
// password is wrong, so we enter a "login rejected" state.
do_check_eq(Status.login, LOGIN_FAILED_LOGIN_REJECTED);
do_check_eq(scheduler.nextSync, 0);
do_check_eq(scheduler.syncTimer, null);
} else {
// For the FxA identity, a 401 on info/collections means a transient
// error, probably due to an inability to fetch a token.
do_check_eq(Status.login, LOGIN_FAILED_NETWORK_ERROR);
// syncs should still be scheduled.
do_check_true(scheduler.nextSync > Date.now());
do_check_true(scheduler.syncTimer.delay > 0);
}
await cleanUpAndGo(server);
});
add_identity_test(this, function* test_proper_interval_on_only_failing() {
add_identity_test(this, async function test_proper_interval_on_only_failing() {
_("Ensure proper behavior when only failed records are applied.");
// If an engine reports that no records succeeded, we shouldn't decrease the
@ -1021,13 +973,8 @@ add_identity_test(this, function* test_proper_interval_on_only_failing() {
reconciled: 0
});
let deferred = Promise.defer();
Utils.nextTick(function() {
scheduler.adjustSyncInterval();
do_check_false(scheduler.hasIncomingItems);
do_check_eq(scheduler.syncInterval, scheduler.singleDeviceInterval);
deferred.resolve();
});
yield deferred.promise;
await promiseNextTick();
scheduler.adjustSyncInterval();
do_check_false(scheduler.hasIncomingItems);
do_check_eq(scheduler.syncInterval, scheduler.singleDeviceInterval);
});

View File

@ -58,21 +58,21 @@ function BogusEngine(service) {
BogusEngine.prototype = Object.create(SteamEngine.prototype);
function cleanAndGo(server) {
async function cleanAndGo(server) {
Svc.Prefs.resetBranch("");
Svc.Prefs.set("log.logger.engine.rotary", "Trace");
Service.recordManager.clearCache();
return new Promise(resolve => server.stop(resolve));
await promiseStopServer(server);
}
// Avoid addon manager complaining about not being initialized
Service.engineManager.unregister("addons");
add_identity_test(this, function *test_basic() {
add_identity_test(this, async function test_basic() {
let helper = track_collections_helper();
let upd = helper.with_updated_collection;
yield configureIdentity({ username: "johndoe" });
await configureIdentity({ username: "johndoe" });
let handlers = {
"/1.1/johndoe/info/collections": helper.handler,
"/1.1/johndoe/storage/crypto/keys": upd("crypto", new ServerWBO("keys").handler()),
@ -88,12 +88,12 @@ add_identity_test(this, function *test_basic() {
let server = httpd_setup(handlers);
Service.serverURL = server.baseURI;
yield sync_and_validate_telem(true);
await sync_and_validate_telem(true);
yield new Promise(resolve => server.stop(resolve));
await promiseStopServer(server);
});
add_task(function* test_processIncoming_error() {
add_task(async function test_processIncoming_error() {
let engine = new BookmarksEngine(Service);
let store = engine._store;
let server = serverForUsers({"foo": "password"}, {
@ -118,7 +118,7 @@ add_task(function* test_processIncoming_error() {
let error, ping;
try {
yield sync_engine_and_validate_telem(engine, true, errPing => ping = errPing);
await sync_engine_and_validate_telem(engine, true, errPing => ping = errPing);
} catch(ex) {
error = ex;
}
@ -139,11 +139,11 @@ add_task(function* test_processIncoming_error() {
} finally {
store.wipe();
yield cleanAndGo(server);
await cleanAndGo(server);
}
});
add_task(function *test_uploading() {
add_task(async function test_uploading() {
let engine = new BookmarksEngine(Service);
let store = engine._store;
let server = serverForUsers({"foo": "password"}, {
@ -165,7 +165,7 @@ add_task(function *test_uploading() {
let collection = server.user("foo").collection("bookmarks");
try {
let ping = yield sync_engine_and_validate_telem(engine, false);
let ping = await sync_engine_and_validate_telem(engine, false);
ok(!!ping);
equal(ping.engines.length, 1);
equal(ping.engines[0].name, "bookmarks");
@ -178,7 +178,7 @@ add_task(function *test_uploading() {
store.wipe();
engine.resetClient();
ping = yield sync_engine_and_validate_telem(engine, false);
ping = await sync_engine_and_validate_telem(engine, false);
equal(ping.engines.length, 1);
equal(ping.engines[0].name, "bookmarks");
equal(ping.engines[0].outgoing.length, 1);
@ -187,11 +187,11 @@ add_task(function *test_uploading() {
} finally {
// Clean up.
store.wipe();
yield cleanAndGo(server);
await cleanAndGo(server);
}
});
add_task(function *test_upload_failed() {
add_task(async function test_upload_failed() {
Service.identity.username = "foo";
let collection = new ServerCollection();
collection._wbos.flying = new ServerWBO('flying');
@ -222,7 +222,7 @@ add_task(function *test_upload_failed() {
try {
engine.enabled = true;
let ping = yield sync_engine_and_validate_telem(engine, true);
let ping = await sync_engine_and_validate_telem(engine, true);
ok(!!ping);
equal(ping.engines.length, 1);
equal(ping.engines[0].incoming, null);
@ -230,18 +230,18 @@ add_task(function *test_upload_failed() {
engine.lastSync = 123;
engine.lastSyncLocal = 456;
ping = yield sync_engine_and_validate_telem(engine, true);
ping = await sync_engine_and_validate_telem(engine, true);
ok(!!ping);
equal(ping.engines.length, 1);
equal(ping.engines[0].incoming.reconciled, 1);
deepEqual(ping.engines[0].outgoing, [{ sent: 2, failed: 2 }]);
} finally {
yield cleanAndGo(server);
await cleanAndGo(server);
}
});
add_task(function *test_sync_partialUpload() {
add_task(async function test_sync_partialUpload() {
Service.identity.username = "foo";
let collection = new ServerCollection();
@ -274,7 +274,7 @@ add_task(function *test_sync_partialUpload() {
try {
engine.enabled = true;
let ping = yield sync_engine_and_validate_telem(engine, true);
let ping = await sync_engine_and_validate_telem(engine, true);
ok(!!ping);
ok(!ping.failureReason);
@ -296,7 +296,7 @@ add_task(function *test_sync_partialUpload() {
try {
// should throw
yield sync_engine_and_validate_telem(engine, true, errPing => ping = errPing);
await sync_engine_and_validate_telem(engine, true, errPing => ping = errPing);
} catch (e) {}
// It would be nice if we had a more descriptive error for this...
let uploadFailureError = {
@ -317,11 +317,11 @@ add_task(function *test_sync_partialUpload() {
deepEqual(ping.engines[0].failureReason, uploadFailureError);
} finally {
yield cleanAndGo(server);
await cleanAndGo(server);
}
});
add_task(function* test_generic_engine_fail() {
add_task(async function test_generic_engine_fail() {
Service.engineManager.register(SteamEngine);
let engine = Service.engineManager.get("steam");
engine.enabled = true;
@ -336,7 +336,7 @@ add_task(function* test_generic_engine_fail() {
engine._errToThrow = e;
try {
let ping = yield sync_and_validate_telem(true);
let ping = await sync_and_validate_telem(true);
equal(ping.status.service, SYNC_FAILED_PARTIAL);
deepEqual(ping.engines.find(e => e.name === "steam").failureReason, {
name: "unexpectederror",
@ -344,11 +344,11 @@ add_task(function* test_generic_engine_fail() {
});
} finally {
Service.engineManager.unregister(engine);
yield cleanAndGo(server);
await cleanAndGo(server);
}
});
add_task(function* test_engine_fail_ioerror() {
add_task(async function test_engine_fail_ioerror() {
Service.engineManager.register(SteamEngine);
let engine = Service.engineManager.get("steam");
engine.enabled = true;
@ -364,14 +364,14 @@ add_task(function* test_engine_fail_ioerror() {
// (Note that fakeservices.js has replaced Utils.jsonMove etc, but for
// this test we need the real one so we get real exceptions from the
// filesystem.)
yield Utils._real_jsonMove("file-does-not-exist", "anything", {});
await Utils._real_jsonMove("file-does-not-exist", "anything", {});
} catch (ex) {
engine._errToThrow = ex;
}
ok(engine._errToThrow, "expecting exception");
try {
let ping = yield sync_and_validate_telem(true);
let ping = await sync_and_validate_telem(true);
equal(ping.status.service, SYNC_FAILED_PARTIAL);
let failureReason = ping.engines.find(e => e.name === "steam").failureReason;
equal(failureReason.name, "unexpectederror");
@ -380,11 +380,11 @@ add_task(function* test_engine_fail_ioerror() {
ok(failureReason.error.includes("[profileDir]"), failureReason.error);
} finally {
Service.engineManager.unregister(engine);
yield cleanAndGo(server);
await cleanAndGo(server);
}
});
add_task(function* test_initial_sync_engines() {
add_task(async function test_initial_sync_engines() {
Service.engineManager.register(SteamEngine);
let engine = Service.engineManager.get("steam");
engine.enabled = true;
@ -400,7 +400,7 @@ add_task(function* test_initial_sync_engines() {
let server = serverForUsers({"foo": "password"}, conf);
new SyncTestingInfrastructure(server.server);
try {
let ping = yield wait_for_ping(() => Service.sync(), true);
let ping = await wait_for_ping(() => Service.sync(), true);
equal(ping.engines.find(e => e.name === "clients").outgoing[0].sent, 1);
equal(ping.engines.find(e => e.name === "tabs").outgoing[0].sent, 1);
@ -417,11 +417,11 @@ add_task(function* test_initial_sync_engines() {
equal(e.outgoing[0].failed, undefined);
}
} finally {
yield cleanAndGo(server);
await cleanAndGo(server);
}
});
add_task(function* test_nserror() {
add_task(async function test_nserror() {
Service.engineManager.register(SteamEngine);
let engine = Service.engineManager.get("steam");
engine.enabled = true;
@ -434,7 +434,7 @@ add_task(function* test_nserror() {
new SyncTestingInfrastructure(server.server);
engine._errToThrow = Components.Exception("NS_ERROR_UNKNOWN_HOST", Cr.NS_ERROR_UNKNOWN_HOST);
try {
let ping = yield sync_and_validate_telem(true);
let ping = await sync_and_validate_telem(true);
deepEqual(ping.status, {
service: SYNC_FAILED_PARTIAL,
sync: LOGIN_FAILED_NETWORK_ERROR
@ -446,11 +446,11 @@ add_task(function* test_nserror() {
});
} finally {
Service.engineManager.unregister(engine);
yield cleanAndGo(server);
await cleanAndGo(server);
}
});
add_identity_test(this, function *test_discarding() {
add_identity_test(this, async function test_discarding() {
let helper = track_collections_helper();
let upd = helper.with_updated_collection;
let telem = get_sync_test_telemetry();
@ -461,7 +461,7 @@ add_identity_test(this, function *test_discarding() {
let server;
try {
yield configureIdentity({ username: "johndoe" });
await configureIdentity({ username: "johndoe" });
let handlers = {
"/1.1/johndoe/info/collections": helper.handler,
"/1.1/johndoe/storage/crypto/keys": upd("crypto", new ServerWBO("keys").handler()),
@ -483,7 +483,7 @@ add_identity_test(this, function *test_discarding() {
}
telem.submit = oldSubmit;
telem.submissionInterval = -1;
let ping = yield sync_and_validate_telem(true, true); // with this we've synced 6 times
let ping = await sync_and_validate_telem(true, true); // with this we've synced 6 times
equal(ping.syncs.length, 2);
equal(ping.discarded, 4);
} finally {
@ -491,12 +491,12 @@ add_identity_test(this, function *test_discarding() {
telem.submissionInterval = -1;
telem.submit = oldSubmit;
if (server) {
yield new Promise(resolve => server.stop(resolve));
await promiseStopServer(server);
}
}
})
add_task(function* test_no_foreign_engines_in_error_ping() {
add_task(async function test_no_foreign_engines_in_error_ping() {
Service.engineManager.register(BogusEngine);
let engine = Service.engineManager.get("bogus");
engine.enabled = true;
@ -508,16 +508,16 @@ add_task(function* test_no_foreign_engines_in_error_ping() {
engine._errToThrow = new Error("Oh no!");
new SyncTestingInfrastructure(server.server);
try {
let ping = yield sync_and_validate_telem(true);
let ping = await sync_and_validate_telem(true);
equal(ping.status.service, SYNC_FAILED_PARTIAL);
ok(ping.engines.every(e => e.name !== "bogus"));
} finally {
Service.engineManager.unregister(engine);
yield cleanAndGo(server);
await cleanAndGo(server);
}
});
add_task(function* test_sql_error() {
add_task(async function test_sql_error() {
Service.engineManager.register(SteamEngine);
let engine = Service.engineManager.get("steam");
engine.enabled = true;
@ -534,16 +534,16 @@ add_task(function* test_sql_error() {
Async.querySpinningly(db.createAsyncStatement("select bar from foo"));
};
try {
let ping = yield sync_and_validate_telem(true);
let ping = await sync_and_validate_telem(true);
let enginePing = ping.engines.find(e => e.name === "steam");
deepEqual(enginePing.failureReason, { name: "sqlerror", code: 1 });
} finally {
Service.engineManager.unregister(engine);
yield cleanAndGo(server);
await cleanAndGo(server);
}
});
add_task(function* test_no_foreign_engines_in_success_ping() {
add_task(async function test_no_foreign_engines_in_success_ping() {
Service.engineManager.register(BogusEngine);
let engine = Service.engineManager.get("bogus");
engine.enabled = true;
@ -555,10 +555,10 @@ add_task(function* test_no_foreign_engines_in_success_ping() {
new SyncTestingInfrastructure(server.server);
try {
let ping = yield sync_and_validate_telem();
let ping = await sync_and_validate_telem();
ok(ping.engines.every(e => e.name !== "bogus"));
} finally {
Service.engineManager.unregister(engine);
yield cleanAndGo(server);
await cleanAndGo(server);
}
});

View File

@ -109,6 +109,6 @@ add_test(function test_load_logging() {
}));
});
add_task(function* test_undefined_callback() {
yield Utils.jsonSave("foo", {}, ["v1", "v2"]);
add_task(async function test_undefined_callback() {
await Utils.jsonSave("foo", {}, ["v1", "v2"]);
});