Bug 672090 - Remove toolkit/content/tests/browser/common/_loadAll.js, testRunner.js, toolkitFunctions.js. r=gavin

--HG--
rename : toolkit/content/tests/browser/common/mockTransferForContinuing.js => toolkit/content/tests/browser/common/mockTransfer.js
This commit is contained in:
Dão Gottwald 2011-07-20 10:37:53 +02:00
parent 390526b794
commit 5a9f25b436
9 changed files with 220 additions and 609 deletions

View File

@ -6,105 +6,83 @@
* <https://bugzilla.mozilla.org/show_bug.cgi?id=564387>
*/
function test() {
waitForExplicitFinish();
// --- Testing support library ---
gBrowser.loadURI("http://mochi.test:8888/browser/browser/base/content/test/bug564387.html");
// Import the toolkit test support library in the scope of the current test.
// This operation also defines the common constants Cc, Ci, Cu, Cr and Cm.
Components.classes["@mozilla.org/moz/jssubscript-loader;1"].
getService(Components.interfaces.mozIJSSubScriptLoader).loadSubScript(
"chrome://mochitests/content/browser/toolkit/content/tests/browser/common/_loadAll.js",
this);
registerCleanupFunction(function () {
gBrowser.addTab();
gBrowser.removeCurrentTab();
});
// --- Test implementation ---
gBrowser.addEventListener("pageshow", function pageShown(event) {
if (event.target.location == "about:blank")
return;
gBrowser.removeEventListener("pageshow", pageShown);
const kBaseUrl =
"http://mochi.test:8888/browser/browser/base/content/test/";
document.addEventListener("popupshown", contextMenuOpened);
function pageShown(event) {
if (event.target.location != "about:blank")
testRunner.continueTest();
}
function saveVideoAs_TestGenerator() {
// Load Test page
gBrowser.addEventListener("pageshow", pageShown, false);
gBrowser.loadURI(kBaseUrl + "bug564387.html");
yield;
gBrowser.removeEventListener("pageshow", pageShown, false);
// Ensure that the window is focused.
SimpleTest.waitForFocus(testRunner.continueTest);
yield;
try {
// get the video element
var video1 = gBrowser.contentDocument.getElementById("video1");
// Synthesize the right click on the context menu, and
// wait for it to be shown
document.addEventListener("popupshown", testRunner.continueTest, false);
EventUtils.synthesizeMouseAtCenter(video1,
{ type: "contextmenu", button: 2 },
gBrowser.contentWindow);
yield;
});
function contextMenuOpened(event) {
event.currentTarget.removeEventListener("popupshown", contextMenuOpened);
// Create the folder the video will be saved into.
var destDir = createTemporarySaveDirectory();
try {
// Call the appropriate save function defined in contentAreaUtils.js.
mockFilePickerSettings.destDir = destDir;
mockFilePickerSettings.filterIndex = 1; // kSaveAsType_URL
// register mock file picker object
mockFilePickerRegisterer.register();
try {
// register mock download progress listener
mockTransferForContinuingRegisterer.register();
try {
mockTransferCallback = onTransferComplete;
mockTransferRegisterer.register();
registerCleanupFunction(function () {
mockTransferRegisterer.unregister();
mockFilePickerRegisterer.unregister();
destDir.remove(true);
});
// Select "Save Video As" option from context menu
var saveVideoCommand = document.getElementById("context-savevideo");
saveVideoCommand.doCommand();
// Unregister the popupshown listener
document.removeEventListener("popupshown",
testRunner.continueTest, false);
// Close the context menu
document.getElementById("placesContext").hidePopup();
event.target.hidePopup();
}
// Wait for the download to finish, and exit if it wasn't successful.
var downloadSuccess = yield;
if (!downloadSuccess)
throw "Unexpected failure in downloading Video file!";
}
finally {
// unregister download progress listener
mockTransferForContinuingRegisterer.unregister();
}
}
finally {
// unregister mock file picker object
mockFilePickerRegisterer.unregister();
}
function onTransferComplete(downloadSuccess) {
ok(downloadSuccess, "Video file should have been downloaded successfully");
// Read the name of the saved file.
var fileName = mockFilePickerResults.selectedFile.leafName;
is(fileName, "Bug564387-expectedName.ogv",
"Video File Name is correctly retrieved from Content-Disposition http header");
}
finally {
// Clean up the saved file.
destDir.remove(true);
}
}
finally {
// Replace the current tab with a clean one.
gBrowser.addTab().linkedBrowser.stop();
gBrowser.removeCurrentTab();
}
}
"Video file name is correctly retrieved from Content-Disposition http header");
// --- Run the test ---
testRunner.runTest(saveVideoAs_TestGenerator);
finish();
}
}
Cc["@mozilla.org/moz/jssubscript-loader;1"]
.getService(Ci.mozIJSSubScriptLoader)
.loadSubScript("chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockTransfer.js",
this);
Cc["@mozilla.org/moz/jssubscript-loader;1"]
.getService(Ci.mozIJSSubScriptLoader)
.loadSubScript("chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockFilePicker.js",
this);
function createTemporarySaveDirectory() {
var saveDir = Cc["@mozilla.org/file/directory_service;1"]
.getService(Ci.nsIProperties)
.get("TmpD", Ci.nsIFile);
saveDir.append("testsavedir");
if (!saveDir.exists())
saveDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0755);
return saveDir;
}

View File

@ -44,76 +44,61 @@
* page is no longer in the cache.
*/
function test() {
waitForExplicitFinish();
// --- Testing support library ---
gBrowser.loadURI("http://mochi.test:8888/browser/toolkit/content/tests/browser/data/post_form_outer.sjs");
// Import the toolkit test support library in the scope of the current test.
// This operation also defines the common constants Cc, Ci, Cu, Cr and Cm.
Components.classes["@mozilla.org/moz/jssubscript-loader;1"].
getService(Components.interfaces.mozIJSSubScriptLoader).loadSubScript(
"chrome://mochitests/content/browser/toolkit/content/tests/browser/common/_loadAll.js",
this);
registerCleanupFunction(function () {
gBrowser.addTab();
gBrowser.removeCurrentTab();
});
// --- Test implementation ---
gBrowser.addEventListener("pageshow", function pageShown(event) {
if (event.target.location == "about:blank")
return;
gBrowser.removeEventListener("pageshow", pageShown);
const kBaseUrl =
"http://mochi.test:8888/browser/toolkit/content/tests/browser/data/";
function pageShown(event)
{
if (event.target.location != "about:blank")
testRunner.continueTest();
}
function FramePostData_TestGenerator() {
// Display the outer page, and wait for it to be loaded. Loading the URI
// doesn't generally raise any exception, but if an error page is
// displayed, an exception will occur later during the test.
gBrowser.addEventListener("pageshow", pageShown, false);
gBrowser.loadURI(kBaseUrl + "post_form_outer.sjs");
yield;
gBrowser.removeEventListener("pageshow", pageShown, false);
try {
// Submit the form in the outer page, then wait for both the outer
// document and the inner frame to be loaded again.
gBrowser.addEventListener("DOMContentLoaded",
testRunner.continueAfterTwoEvents, false);
try {
gBrowser.addEventListener("DOMContentLoaded", handleOuterSubmit);
gBrowser.contentDocument.getElementById("postForm").submit();
yield;
}
finally {
// Remove the event listener, even if an exception occurred for any
// reason (for example, the requested element does not exist).
gBrowser.removeEventListener("DOMContentLoaded",
testRunner.continueAfterTwoEvents, false);
}
});
// Save a reference to the inner frame in the reloaded page for later.
var innerFrame = gBrowser.contentDocument.getElementById("innerFrame");
var framesLoaded = 0;
var innerFrame;
function handleOuterSubmit() {
if (++framesLoaded < 2)
return;
gBrowser.removeEventListener("DOMContentLoaded", handleOuterSubmit);
innerFrame = gBrowser.contentDocument.getElementById("innerFrame");
// Submit the form in the inner page.
gBrowser.addEventListener("DOMContentLoaded",
testRunner.continueTest, false);
try {
gBrowser.addEventListener("DOMContentLoaded", handleInnerSubmit);
innerFrame.contentDocument.getElementById("postForm").submit();
yield;
}
finally {
// Remove the event listener, even if an exception occurred for any
// reason (for example, the requested element does not exist).
gBrowser.removeEventListener("DOMContentLoaded",
testRunner.continueTest, false);
}
function handleInnerSubmit() {
gBrowser.removeEventListener("DOMContentLoaded", handleInnerSubmit);
// Create the folder the page will be saved into.
var destDir = createTemporarySaveDirectory();
try {
// Call the appropriate save function defined in contentAreaUtils.js.
mockFilePickerSettings.destDir = destDir;
mockFilePickerSettings.filterIndex = 1; // kSaveAsType_URL
callSaveWithMockObjects(function() {
mockFilePickerRegisterer.register();
mockTransferCallback = onTransferComplete;
mockTransferRegisterer.register();
registerCleanupFunction(function () {
mockTransferRegisterer.unregister();
mockFilePickerRegisterer.unregister();
destDir.remove(true);
});
var docToSave = innerFrame.contentDocument;
// We call internalSave instead of saveDocument to bypass the history
// cache.
@ -121,37 +106,76 @@ function test() {
docToSave.contentType, false, null, null,
docToSave.referrer ? makeURI(docToSave.referrer) : null,
false, null);
});
}
// Wait for the download to finish, and exit if it wasn't successful.
var downloadSuccess = yield;
if (!downloadSuccess)
throw "Unexpected failure, the inner frame couldn't be saved!";
function onTransferComplete(downloadSuccess) {
ok(downloadSuccess, "The inner frame should have been downloaded successfully");
// Read the entire saved file.
var fileContents = readShortFile(mockFilePickerResults.selectedFile);
// Check if outer POST data is found (bug 471962).
ok(fileContents.indexOf("inputfield=outer") === -1,
is(fileContents.indexOf("inputfield=outer"), -1,
"The saved inner frame does not contain outer POST data");
// Check if inner POST data is found (bug 485196).
ok(fileContents.indexOf("inputfield=inner") > -1,
isnot(fileContents.indexOf("inputfield=inner"), -1,
"The saved inner frame was generated using the correct POST data");
}
finally {
// Clean up the saved file.
destDir.remove(true);
}
}
finally {
// Replace the current tab with a clean one.
gBrowser.addTab().linkedBrowser.stop();
gBrowser.removeCurrentTab();
}
}
// --- Run the test ---
testRunner.runTest(FramePostData_TestGenerator);
finish();
}
}
Cc["@mozilla.org/moz/jssubscript-loader;1"]
.getService(Ci.mozIJSSubScriptLoader)
.loadSubScript("chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockTransfer.js",
this);
Cc["@mozilla.org/moz/jssubscript-loader;1"]
.getService(Ci.mozIJSSubScriptLoader)
.loadSubScript("chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockFilePicker.js",
this);
function createTemporarySaveDirectory() {
var saveDir = Cc["@mozilla.org/file/directory_service;1"]
.getService(Ci.nsIProperties)
.get("TmpD", Ci.nsIFile);
saveDir.append("testsavedir");
if (!saveDir.exists())
saveDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0755);
return saveDir;
}
/**
* Reads the contents of the provided short file (up to 1 MiB).
*
* @param aFile
* nsIFile object pointing to the file to be read.
*
* @return
* String containing the raw octets read from the file.
*/
function readShortFile(aFile) {
var inputStream = Cc["@mozilla.org/network/file-input-stream;1"]
.createInstance(Ci.nsIFileInputStream);
inputStream.init(aFile, -1, 0, 0);
try {
var scrInputStream = Cc["@mozilla.org/scriptableinputstream;1"]
.createInstance(Ci.nsIScriptableInputStream);
scrInputStream.init(inputStream);
try {
// Assume that the file is much shorter than 1 MiB.
return scrInputStream.read(1048576);
}
finally {
// Close the scriptable stream after reading, even if the operation
// failed.
scrInputStream.close();
}
}
finally {
// Close the stream after reading, if it is still open, even if the read
// operation failed.
inputStream.close();
}
}

View File

@ -44,14 +44,10 @@ relativesrcdir = toolkit/content/tests/browser/common
include $(DEPTH)/config/autoconf.mk
include $(topsrcdir)/config/rules.mk
# If you add files here, add them to "_loadAll.js" too.
_COMMON_FILES = \
_loadAll.js \
mockFilePicker.js \
mockObjects.js \
mockTransferForContinuing.js \
testRunner.js \
toolkitFunctions.js \
mockTransfer.js \
$(NULL)
libs:: $(_COMMON_FILES)

View File

@ -1,71 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla XUL Toolkit Testing Code.
*
* The Initial Developer of the Original Code is
* Paolo Amadini <http://www.amadzone.org/>.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* This file loads the entire library of testing objects and functions.
*/
// Define the shortcuts required by the included files.
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
const Cr = Components.results;
const Cm = Components.manager;
// Execute the following code while keeping the current scope clean.
void(function (scriptScope) {
const kBaseUrl = "chrome://mochitests/content/browser/toolkit/content/tests/browser/common/";
// If you add files here, add them to "Makefile.in" too.
var scriptNames = [
"mockObjects.js",
"testRunner.js",
// To be included after the files above.
"mockFilePicker.js",
"mockTransferForContinuing.js",
"toolkitFunctions.js",
];
// Include all the required scripts.
var scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
getService(Ci.mozIJSSubScriptLoader);
for (let [, scriptName] in Iterator(scriptNames)) {
// Ensure that the subscript is loaded in the scope where this script is
// being executed, which is not necessarily the global scope.
scriptLoader.loadSubScript(kBaseUrl + scriptName, scriptScope);
}
}(this));

View File

@ -34,7 +34,10 @@
*
* ***** END LICENSE BLOCK ***** */
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cc["@mozilla.org/moz/jssubscript-loader;1"]
.getService(Ci.mozIJSSubScriptLoader)
.loadSubScript("chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockObjects.js",
this);
var mockFilePickerSettings = {
/**
@ -71,9 +74,9 @@ var mockFilePickerResults = {
function MockFilePicker() { };
MockFilePicker.prototype = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsIFilePicker]),
init: function(aParent, aTitle, aMode) { },
appendFilters: function(aFilterMask) { },
appendFilter: function(aTitle, aFilter) { },
init: function () {},
appendFilters: function () {},
appendFilter: function () {},
defaultString: "",
defaultExtension: "",
filterIndex: 0,

View File

@ -51,30 +51,7 @@
* Components.interfaces.nsIFilePicker).
*/
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
if (Cc === undefined) {
var Cc = Components.classes;
}
if (Ci === undefined) {
var Ci = Components.interfaces;
}
if (Cu === undefined) {
var Cu = Components.utils;
}
if (Cr === undefined) {
var Cr = Components.results;
}
if (Cm === undefined) {
var Cm = Components.manager;
}
function MockObjectRegisterer(aContractID, aReplacementCtor)
{
function MockObjectRegisterer(aContractID, aReplacementCtor) {
this._contractID = aContractID;
this._replacementCtor = aReplacementCtor;
}
@ -88,7 +65,6 @@ MockObjectRegisterer.prototype = {
* to ensure that unregister() is called.
*/
register: function MOR_register() {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
if (this._originalCID)
throw new Exception("Invalid object state when calling register()");
@ -106,7 +82,7 @@ MockObjectRegisterer.prototype = {
getService(Components.interfaces.nsIUUIDGenerator).generateUUID();
// Preserve the original CID
var componentRegistrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
var componentRegistrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
this._originalCID = componentRegistrar.contractIDToCID(this._contractID);
// Replace the original factory with the mock one.
@ -120,12 +96,11 @@ MockObjectRegisterer.prototype = {
* Restores the original factory.
*/
unregister: function MOR_unregister() {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
if (!this._originalCID)
throw new Exception("Invalid object state when calling unregister()");
// Free references to the mock factory.
var componentRegistrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
var componentRegistrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
componentRegistrar.unregisterFactory(this._cid,
this._mockFactory);

View File

@ -34,28 +34,30 @@
*
* ***** END LICENSE BLOCK ***** */
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cc["@mozilla.org/moz/jssubscript-loader;1"]
.getService(Ci.mozIJSSubScriptLoader)
.loadSubScript("chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockObjects.js",
this);
var mockTransferCallback;
/**
* This "transfer" object implementation continues the currently running test
* when the download is completed, reporting true for success or false for
* failure as the first argument of the testRunner.continueTest function.
*/
function MockTransferForContinuing()
{
function MockTransfer() {
this._downloadIsSuccessful = true;
}
MockTransferForContinuing.prototype = {
MockTransfer.prototype = {
QueryInterface: XPCOMUtils.generateQI([
Ci.nsIWebProgressListener,
Ci.nsIWebProgressListener2,
Ci.nsITransfer,
]),
//////////////////////////////////////////////////////////////////////////////
//// nsIWebProgressListener
/* nsIWebProgressListener */
onStateChange: function MTFC_onStateChange(aWebProgress, aRequest,
aStateFlags, aStatus) {
// If at least one notification reported an error, the download failed.
@ -66,34 +68,24 @@ MockTransferForContinuing.prototype = {
if ((aStateFlags & Ci.nsIWebProgressListener.STATE_STOP) &&
(aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK))
// Continue the test, reporting the success or failure condition.
testRunner.continueTest(this._downloadIsSuccessful);
mockTransferCallback(this._downloadIsSuccessful);
},
onProgressChange: function(aWebProgress, aRequest, aCurSelfProgress,
aMaxSelfProgress, aCurTotalProgress,
aMaxTotalProgress) { },
onLocationChange: function(aWebProgress, aRequest, aLocation) { },
onProgressChange: function () {},
onLocationChange: function () {},
onStatusChange: function MTFC_onStatusChange(aWebProgress, aRequest, aStatus,
aMessage) {
// If at least one notification reported an error, the download failed.
if (!Components.isSuccessCode(aStatus))
this._downloadIsSuccessful = false;
},
onSecurityChange: function(aWebProgress, aRequest, aState) { },
onSecurityChange: function () {},
//////////////////////////////////////////////////////////////////////////////
//// nsIWebProgressListener2
/* nsIWebProgressListener2 */
onProgressChange64: function () {},
onRefreshAttempted: function () {},
onProgressChange64: function(aWebProgress, aRequest, aCurSelfProgress,
aMaxSelfProgress, aCurTotalProgress,
aMaxTotalProgress) { },
onRefreshAttempted: function(aWebProgress, aRefreshURI, aMillis,
aSameURI) { },
//////////////////////////////////////////////////////////////////////////////
//// nsITransfer
init: function(aSource, aTarget, aDisplayName, aMIMEInfo, aStartTime,
aTempFile, aCancelable) { }
/* nsITransfer */
init: function () {}
};
// Create an instance of a MockObjectRegisterer whose methods can be used to
@ -102,6 +94,5 @@ MockTransferForContinuing.prototype = {
// factory, call the "register" method. Starting from that moment, all the
// transfer objects that are requested will be mock objects, until the
// "unregister" method is called.
var mockTransferForContinuingRegisterer =
new MockObjectRegisterer("@mozilla.org/transfer;1",
MockTransferForContinuing);
var mockTransferRegisterer =
new MockObjectRegisterer("@mozilla.org/transfer;1", MockTransfer);

View File

@ -1,171 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla XUL Toolkit Testing Code.
*
* The Initial Developer of the Original Code is
* Paolo Amadini <http://www.amadzone.org/>.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* Runs a browser-chrome test defined through a generator function.
*
* This object is a singleton, initialized automatically when this script is
* included. Every browser-chrome test file includes a new copy of this script.
*/
var testRunner = {
_testIterator: null,
_lastEventResult: undefined,
_testRunning: false,
_eventRaised: false,
// --- Main test runner ---
/**
* Runs the test described by the provided generator function asynchronously.
*
* Calling yield in the generator will cause it to wait until continueTest is
* called. The parameter provided to continueTest will be the return value of
* the yield operator.
*
* @param aGenerator
* Test generator function. The function will be called with no
* arguments to retrieve its iterator.
*/
runTest: function TR_runTest(aGenerator) {
waitForExplicitFinish();
testRunner._testIterator = aGenerator();
testRunner.continueTest();
},
/**
* Continues the currently running test.
*
* @param aEventResult
* This will be the return value of the yield operator in the test.
*/
continueTest: function TR_continueTest(aEventResult) {
// Store the last event result, or set it to undefined.
testRunner._lastEventResult = aEventResult;
// Never reenter the main loop, but notify that the event has been raised.
if (testRunner._testRunning) {
testRunner._eventRaised = true;
return;
}
// Enter the main iteration loop.
testRunner._testRunning = true;
try {
do {
// Call the iterator, but don't leave the loop if the expected event is
// raised during the execution of the generator.
testRunner._eventRaised = false;
testRunner._testIterator.send(testRunner._lastEventResult);
} while (testRunner._eventRaised);
}
catch (e) {
// This block catches exceptions raised by the generator, including the
// normal StopIteration exception. Unexpected exceptions are reported as
// test failures.
if (!(e instanceof StopIteration))
ok(false, e);
// In any case, stop the tests in this file.
finish();
}
// Wait for the next event or finish.
testRunner._testRunning = false;
},
// --- Auxiliary functions ---
_isFirstEvent: true,
/**
* Continues the running test every second time this function is called.
*/
continueAfterTwoEvents: function TR_continueAfterTwoEvents() {
if (testRunner._isFirstEvent) {
testRunner._isFirstEvent = false;
return;
}
testRunner._isFirstEvent = true;
testRunner.continueTest();
},
// --- Support for multiple tests ---
/**
* This generator function yields each value obtained by the given generators,
* in the order they are specified in the array.
*
* @param aArrayOfGenerators
* Array of generator functions. The functions will be called with no
* arguments to retrieve their iterators.
*
* @return
* The iterator generated by this generator function.
*/
chainGenerator: function TR_chainGenerator(aArrayOfGenerators) {
// Obtain each iterator in turn.
for (let [, curGenerator] in Iterator(aArrayOfGenerators)) {
var curIterator = curGenerator();
// Call each iterator until it completes, while ensuring propagation of
// both the the values provided to and returned by the yield operator.
try {
var value = undefined;
while (true) {
value = yield curIterator.send(value);
}
}
catch(e if e instanceof StopIteration) {
// The iterator has finished providing all the values.
}
}
},
/**
* Runs multiple tests.
*
* This function operates asynchronously. Because of this, it should be called
* by the last line of a test script.
*
* @param aArrayOfTestGenerators
* Array containing references to the test generator functions to run.
*
* @see #runTest
*/
runTests: function TR_runTests(aArrayOfTestGenerators) {
testRunner.runTest(function() {
return testRunner.chainGenerator(aArrayOfTestGenerators);
});
}
};

View File

@ -1,114 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla XUL Toolkit Testing Code.
*
* The Initial Developer of the Original Code is
* Paolo Amadini <http://www.amadzone.org/>.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* Provides a temporary save directory.
*
* @return
* nsIFile pointing to the new or existing directory.
*/
function createTemporarySaveDirectory() {
var saveDir = Cc["@mozilla.org/file/directory_service;1"].
getService(Ci.nsIProperties).get("TmpD", Ci.nsIFile);
saveDir.append("testsavedir");
if (!saveDir.exists())
saveDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0755);
return saveDir;
}
/**
* Calls the provided save function while replacing the file picker component
* with a mock implementation that returns a temporary file path and custom
* filters, and the download component with an implementation that does not
* depend on the download manager.
*
* @param aSaveFunction
* The function to call. This is usually the subject of the entire test
* being run.
*/
function callSaveWithMockObjects(aSaveFunction) {
// Call the provided function while the mock object factories are in place and
// ensure that, even in case of exceptions during the function's execution,
// the mock object factories are unregistered before proceeding with the other
// tests in the suite.
mockFilePickerRegisterer.register();
try {
mockTransferForContinuingRegisterer.register();
try {
aSaveFunction();
}
finally {
mockTransferForContinuingRegisterer.unregister();
}
}
finally {
mockFilePickerRegisterer.unregister();
}
}
/**
* Reads the contents of the provided short file (up to 1 MiB).
*
* @param aFile
* nsIFile object pointing to the file to be read.
*
* @return
* String containing the raw octets read from the file.
*/
function readShortFile(aFile) {
var inputStream = Cc["@mozilla.org/network/file-input-stream;1"].
createInstance(Ci.nsIFileInputStream);
inputStream.init(aFile, -1, 0, 0);
try {
var scrInputStream = Cc["@mozilla.org/scriptableinputstream;1"].
createInstance(Ci.nsIScriptableInputStream);
scrInputStream.init(inputStream);
try {
// Assume that the file is much shorter than 1 MiB.
return scrInputStream.read(1048576);
}
finally {
// Close the scriptable stream after reading, even if the operation
// failed.
scrInputStream.close();
}
}
finally {
// Close the stream after reading, if it is still open, even if the read
// operation failed.
inputStream.close();
}
}