gecko-dev/testing/modules/TestUtils.jsm

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

207 строки
6.8 KiB
JavaScript
Исходник Обычный вид История

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
* Contains a limited number of testing functions that are commonly used in a
* wide variety of situations, for example waiting for an event loop tick or an
* observer notification.
*
* More complex functions are likely to belong to a separate test-only module.
* Examples include Assert.jsm for generic assertions, FileTestUtils.jsm to work
* with local files and their contents, and BrowserTestUtils.jsm to work with
* browser windows and tabs.
*
* Individual components also offer testing functions to other components, for
* example LoginTestUtils.jsm.
*/
"use strict";
var EXPORTED_SYMBOLS = ["TestUtils"];
Bug 1514594: Part 3 - Change ChromeUtils.import API. *** Bug 1514594: Part 3a - Change ChromeUtils.import to return an exports object; not pollute global. r=mccr8 This changes the behavior of ChromeUtils.import() to return an exports object, rather than a module global, in all cases except when `null` is passed as a second argument, and changes the default behavior not to pollute the global scope with the module's exports. Thus, the following code written for the old model: ChromeUtils.import("resource://gre/modules/Services.jsm"); is approximately the same as the following, in the new model: var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); Since the two behaviors are mutually incompatible, this patch will land with a scripted rewrite to update all existing callers to use the new model rather than the old. *** Bug 1514594: Part 3b - Mass rewrite all JS code to use the new ChromeUtils.import API. rs=Gijs This was done using the followng script: https://bitbucket.org/kmaglione/m-c-rewrites/src/tip/processors/cu-import-exports.jsm *** Bug 1514594: Part 3c - Update ESLint plugin for ChromeUtils.import API changes. r=Standard8 Differential Revision: https://phabricator.services.mozilla.com/D16747 *** Bug 1514594: Part 3d - Remove/fix hundreds of duplicate imports from sync tests. r=Gijs Differential Revision: https://phabricator.services.mozilla.com/D16748 *** Bug 1514594: Part 3e - Remove no-op ChromeUtils.import() calls. r=Gijs Differential Revision: https://phabricator.services.mozilla.com/D16749 *** Bug 1514594: Part 3f.1 - Cleanup various test corner cases after mass rewrite. r=Gijs *** Bug 1514594: Part 3f.2 - Cleanup various non-test corner cases after mass rewrite. r=Gijs Differential Revision: https://phabricator.services.mozilla.com/D16750 --HG-- extra : rebase_source : 359574ee3064c90f33bf36c2ebe3159a24cc8895 extra : histedit_source : b93c8f42808b1599f9122d7842d2c0b3e656a594%2C64a3a4e3359dc889e2ab2b49461bab9e27fc10a7
2019-01-17 21:18:31 +03:00
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { clearInterval, setInterval } = ChromeUtils.import(
"resource://gre/modules/Timer.jsm"
);
var TestUtils = {
executeSoon(callbackFn) {
Services.tm.dispatchToMainThread(callbackFn);
},
waitForTick() {
return new Promise(resolve => this.executeSoon(resolve));
},
/**
* Waits for the specified topic to be observed.
*
* @param {string} topic
* The topic to observe.
* @param {function} checkFn [optional]
* Called with (subject, data) as arguments, should return true if the
* notification is the expected one, or false if it should be ignored
* and listening should continue. If not specified, the first
* notification for the specified topic resolves the returned promise.
*
* @note Because this function is intended for testing, any error in checkFn
* will cause the returned promise to be rejected instead of waiting for
* the next notification, since this is probably a bug in the test.
*
* @return {Promise}
* @resolves The array [subject, data] from the observed notification.
*/
topicObserved(topic, checkFn) {
return new Promise((resolve, reject) => {
Services.obs.addObserver(function observer(subject, topic, data) {
try {
if (checkFn && !checkFn(subject, data)) {
return;
}
Services.obs.removeObserver(observer, topic);
resolve([subject, data]);
} catch (ex) {
Services.obs.removeObserver(observer, topic);
reject(ex);
}
}, topic);
});
},
/**
* Waits for the specified preference to be change.
*
* @param {string} prefName
* The pref to observe.
* @param {function} checkFn [optional]
* Called with the new preference value as argument, should return true if the
* notification is the expected one, or false if it should be ignored
* and listening should continue. If not specified, the first
* notification for the specified topic resolves the returned promise.
*
* @note Because this function is intended for testing, any error in checkFn
* will cause the returned promise to be rejected instead of waiting for
* the next notification, since this is probably a bug in the test.
*
* @return {Promise}
* @resolves The value of the preference.
*/
waitForPrefChange(prefName, checkFn) {
return new Promise((resolve, reject) => {
Services.prefs.addObserver(prefName, function observer(
subject,
topic,
data
) {
try {
let prefValue = null;
switch (Services.prefs.getPrefType(prefName)) {
case Services.prefs.PREF_STRING:
prefValue = Services.prefs.getStringPref(prefName);
break;
case Services.prefs.PREF_INT:
prefValue = Services.prefs.getIntPref(prefName);
break;
case Services.prefs.PREF_BOOL:
prefValue = Services.prefs.getBoolPref(prefName);
break;
}
if (checkFn && !checkFn(prefValue)) {
return;
}
Services.prefs.removeObserver(prefName, observer);
resolve(prefValue);
} catch (ex) {
Services.prefs.removeObserver(prefName, observer);
reject(ex);
}
});
});
},
/**
* Takes a screenshot of an area and returns it as a data URL.
*
* @param eltOrRect
* The DOM node or rect ({left, top, width, height}) to screenshot.
* @param win
* The current window.
*/
screenshotArea(eltOrRect, win) {
if (Element.isInstance(eltOrRect)) {
eltOrRect = eltOrRect.getBoundingClientRect();
}
let { left, top, width, height } = eltOrRect;
let canvas = win.document.createElementNS(
"http://www.w3.org/1999/xhtml",
"canvas"
);
let ctx = canvas.getContext("2d");
let ratio = win.devicePixelRatio;
canvas.width = width * ratio;
canvas.height = height * ratio;
ctx.scale(ratio, ratio);
ctx.drawWindow(win, left, top, width, height, "#fff");
return canvas.toDataURL();
},
/**
* Will poll a condition function until it returns true.
*
* @param condition
* A condition function that must return true or false. If the
* condition ever throws, this is also treated as a false. The
* function can be a generator.
* @param interval
* The time interval to poll the condition function. Defaults
* to 100ms.
* @param attempts
* The number of times to poll before giving up and rejecting
* if the condition has not yet returned true. Defaults to 50
* (~5 seconds for 100ms intervals)
* @return Promise
* Resolves with the return value of the condition function.
* Rejects if timeout is exceeded or condition ever throws.
*/
waitForCondition(condition, msg, interval = 100, maxTries = 50) {
return new Promise((resolve, reject) => {
let tries = 0;
let intervalID = setInterval(async function() {
if (tries >= maxTries) {
clearInterval(intervalID);
msg += ` - timed out after ${maxTries} tries.`;
reject(msg);
return;
}
let conditionPassed = false;
try {
conditionPassed = await condition();
} catch (e) {
msg += ` - threw exception: ${e}`;
clearInterval(intervalID);
reject(msg);
return;
}
if (conditionPassed) {
clearInterval(intervalID);
resolve(conditionPassed);
}
tries++;
}, interval);
});
},
Bug 1368209 - Refactor `Engine::_processIncoming` into three stages. r=eoger,tcsc * In the first stage, we fetch changed records, newest first, up to the download limit. We keep track of the oldest record modified time we see. * Once we've fetched all records, we reconcile, noting records that fail to decrypt or reconcile for the next sync. We then ask the store to apply all remaining records. Previously, `applyIncomingBatchSize` specified how many records to apply at a time. I removed this because it added an extra layer of indirection that's no longer necessary, now that download batching buffers all records in memory, and all stores are async. * In the second stage, we fetch IDs for all remaining records changed between the last sync and the oldest modified time we saw in the first stage. We *don't* set the download limit here, to ensure we add *all* changed records to our backlog, and we use the `"oldest"` sort order instead of `"index"`. * In the third stage, we backfill as before. We don't want large deltas to delay other engines from syncing, so we still only take IDs up to the download limit from the backlog, and include failed IDs from the previous sync. On subsequent syncs, we'll keep fetching from the backlog until it's empty. Other changes to note in this patch: * `Collection::_rebuildURL` now allows callers to specify both `older` and `newer`. According to :rfkelly, this is explicitly and intentionally supported. * Tests that exercise `applyIncomingBatchSize` are gone, since that's no longer a thing. * The test server now shuffles records if the sort order is unspecified. MozReview-Commit-ID: 4EXvNOa8mIo --HG-- extra : rebase_source : f382f0a883c5aa1f6a4466fefe22ad1a88ab6d20
2017-11-01 21:09:57 +03:00
shuffle(array) {
let results = [];
for (let i = 0; i < array.length; ++i) {
let randomIndex = Math.floor(Math.random() * (i + 1));
results[i] = results[randomIndex];
results[randomIndex] = array[i];
}
return results;
},
};