Bug 1678109 - get rid of the mailnews IOUtils.jsm module. r=freaktechnik

Differential Revision: https://phabricator.services.mozilla.com/D108933

--HG--
extra : rebase_source : d8bd49f8dd04b4b142c9975fe18a422da89587e9
This commit is contained in:
Magnus Melin 2021-03-18 14:28:05 +02:00
Родитель 1919389f7d
Коммит b02c872895
37 изменённых файлов: 342 добавлений и 505 удалений

Просмотреть файл

@ -21,7 +21,6 @@ var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var { MailUtils } = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var { IOUtils } = ChromeUtils.import("resource:///modules/IOUtils.jsm");
var { FeedUtils } = ChromeUtils.import("resource:///modules/FeedUtils.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
@ -143,8 +142,10 @@ var gFolderTreeView = {
/**
* Called when the window is initially loaded. This function initializes the
* folder-pane to the view last shown before the application was closed.
* @param {XULTreeElement} aTree - the tree to load
* @param {string} [aJSONFile] - name of JSON file to load data from.
*/
load(aTree, aJSONFile) {
async load(aTree, aJSONFile = null) {
this._treeElement = aTree;
this.messengerBundle = document.getElementById("bundle_messenger");
this.folderColorStyle = document.getElementById("folderColorsStyle");
@ -167,19 +168,19 @@ var gFolderTreeView = {
if (aJSONFile) {
// Parse our persistent-state json file
let data = IOUtils.loadFileToString(aJSONFile);
if (data) {
try {
let parsedData = JSON.parse(data);
// Migrate all the data from the old stored object if the "open"
// object doesn't exist.
this._persistOpenMap = parsedData.open || parsedData;
this._persistColorMap = parsedData.colors;
} catch (x) {
let spec = OS.Path.join(OS.Constants.Path.profileDir, aJSONFile);
try {
let data = await IOUtils.readJSON(spec);
// Migrate all the data from the old stored object if the "open"
// object doesn't exist.
this._persistOpenMap = data.open || data;
this._persistColorMap = data.colors;
} catch (ex) {
if (!["NotFoundError"].includes(ex.name)) {
Cu.reportError(
gFolderTreeView.messengerBundle.getFormattedString(
"failedToReadFile",
[aJSONFile, x]
[aJSONFile, ex]
)
);
}
@ -201,18 +202,20 @@ var gFolderTreeView = {
/**
* Called when the window is being torn down. Here we undo everything we did
* onload. That means removing our listener and serializing our JSON.
* @param {string} [filename] - Name of the file to serialize to.
*/
unload(aJSONFile) {
async unload(filename = null) {
// Remove our listener
MailServices.mailSession.RemoveFolderListener(this);
if (aJSONFile) {
if (filename) {
// Write out our json file...
let data = JSON.stringify({
let data = {
open: this._persistOpenMap,
colors: this._persistColorMap,
});
IOUtils.saveStringToFile(aJSONFile, data);
};
let spec = OS.Path.join(OS.Constants.Path.profileDir, filename);
await IOUtils.writeJSON(spec, data);
}
},

Просмотреть файл

@ -25,7 +25,6 @@
ChromeUtils.import("resource:///modules/activity/activityModules.jsm");
var { logException } = ChromeUtils.import("resource:///modules/ErrUtils.jsm");
var { IOUtils } = ChromeUtils.import("resource:///modules/IOUtils.jsm");
var { JSTreeSelection } = ChromeUtils.import(
"resource:///modules/JsTreeSelection.jsm"
);
@ -798,7 +797,7 @@ var gMailInit = {
OnMailWindowUnload();
try {
MailInstrumentation.uninit();
MailInstrumentation.uninit.bind(MailInstrumentation);
} catch (ex) {
logException(ex);
}
@ -840,11 +839,11 @@ function _showNewInstallModal() {
* integration dialog since the New Account Provinsioner uses a secondary
* success dialog after a new account has been created.
*/
function LoadPostAccountWizard(isFromProvisioner) {
async function LoadPostAccountWizard(isFromProvisioner) {
InitMsgWindow();
messenger.setWindow(window, msgWindow);
InitPanes();
await InitPanes();
MigrateJunkMailSettings();
MigrateFolderViews();
MigrateOpenMessageBehavior();
@ -1360,8 +1359,8 @@ function AddToSession() {
MailServices.mailSession.AddFolderListener(folderListener, notifyFlags);
}
function InitPanes() {
gFolderTreeView.load(
async function InitPanes() {
await gFolderTreeView.load(
document.getElementById("folderTree"),
"folderTree.json"
);

Просмотреть файл

@ -11,11 +11,6 @@
var EXPORTED_SYMBOLS = ["MailMigrator"];
ChromeUtils.defineModuleGetter(
this,
"IOUtils",
"resource:///modules/IOUtils.jsm"
);
const { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
@ -214,21 +209,23 @@ var MailMigrator = {
// This one is needed also in all new profiles.
// Add an expanded entry for All Address Books.
if (currentUIVersion < 10 || newProfile) {
const DIR_TREE_FILE = "directoryTree.json";
// If the file exists, read its contents, prepend the "All ABs" URI
// and save it, else, just write the "All ABs" URI to the file.
let data = IOUtils.loadFileToString(DIR_TREE_FILE);
if (!data || data == "[]") {
data = "";
} else if (data.length > 0) {
data = data.substring(1, data.length - 1);
}
data =
'["moz-abdirectory://?"' + (data.length > 0 ? "," + data : "") + "]";
IOUtils.saveStringToFile(DIR_TREE_FILE, data);
PathUtils.getProfileDir().then(dir => {
let spec = PathUtils.join(dir, "directoryTree.json");
IOUtils.readJSON(spec)
.then(data => {
data.unshift("moz-abdirectory://?");
IOUtils.writeJSON(spec, data);
})
.catch(ex => {
if (["NotFoundError"].includes(ex.name)) {
IOUtils.writeJSON(spec, ["moz-abdirectory://?"]);
} else {
Cu.reportError(ex);
}
});
});
}
// Several Latin language groups were consolidated into x-western.
@ -605,7 +602,7 @@ var MailMigrator = {
*
* @returns {void}
*/
_migrateRSS() {
async _migrateRSS() {
// Find all the RSS IncomingServers.
let rssServers = [];
for (let server of MailServices.accounts.allServers) {
@ -616,48 +613,46 @@ var MailMigrator = {
// For each one...
for (let server of rssServers) {
this._migrateRSSServer(server);
await this._migrateRSSServer(server);
}
},
_migrateRSSServer(server) {
async _migrateRSSServer(server) {
let rssServer = server.QueryInterface(Ci.nsIRssIncomingServer);
// Convert feeds.rdf to feeds.json (if needed).
let feedsFile = rssServer.subscriptionsPath;
let legacyFeedsFile = server.localPath;
legacyFeedsFile.append("feeds.rdf");
if (!feedsFile.exists() && legacyFeedsFile.exists()) {
try {
this._migrateRSSSubscriptions(legacyFeedsFile, feedsFile);
} catch (err) {
Cu.reportError(
"Failed to migrate '" +
feedsFile.path +
"' to '" +
legacyFeedsFile.path +
"': " +
err
);
}
try {
await this._migrateRSSSubscriptions(legacyFeedsFile, feedsFile);
} catch (err) {
Cu.reportError(
"Failed to migrate '" +
feedsFile.path +
"' to '" +
legacyFeedsFile.path +
"': " +
err
);
}
// Convert feeditems.rdf to feeditems.json (if needed).
let itemsFile = rssServer.feedItemsPath;
let legacyItemsFile = server.localPath;
legacyItemsFile.append("feeditems.rdf");
if (!itemsFile.exists() && legacyItemsFile.exists()) {
try {
this._migrateRSSItems(legacyItemsFile, itemsFile);
} catch (err) {
Cu.reportError(
"Failed to migrate '" +
itemsFile.path +
"' to '" +
legacyItemsFile.path +
"': " +
err
);
}
try {
await this._migrateRSSItems(legacyItemsFile, itemsFile);
} catch (err) {
Cu.reportError(
"Failed to migrate '" +
itemsFile.path +
"' to '" +
legacyItemsFile.path +
"': " +
err
);
}
},
@ -675,11 +670,17 @@ var MailMigrator = {
* @param {nsIFile} legacyFile - Location of the rdf file.
* @param {nsIFile} jsonFile - Location for the output JSON file.
* @returns {void}
* @throws Will throw an error if the conversion fails.
*/
_migrateRSSSubscriptions(legacyFile, jsonFile) {
async _migrateRSSSubscriptions(legacyFile, jsonFile) {
// Load .rdf file into an XMLDocument.
let rawXMLRDF = IOUtils.loadFileToString(legacyFile);
let rawXMLRDF;
try {
rawXMLRDF = await IOUtils.readUTF8(legacyFile.path);
} catch (ex) {
if (["NotFoundError"].includes(ex.name)) {
return; // nothing legacy file to migrate
}
}
let parser = new DOMParser();
let doc = parser.parseFromString(rawXMLRDF, "text/xml");
@ -737,8 +738,7 @@ var MailMigrator = {
}
}
let data = JSON.stringify(feeds);
IOUtils.saveStringToFile(jsonFile, data);
await IOUtils.writeJSON(jsonFile.path, feeds);
legacyFile.remove(false);
},
@ -749,11 +749,17 @@ var MailMigrator = {
* @param {nsIFile} legacyFile - Location of the rdf file.
* @param {nsIFile} jsonFile - Location for the output JSON file.
* @returns {void}
* @throws Will throw an error if the conversion fails.
*/
_migrateRSSItems(legacyFile, jsonFile) {
async _migrateRSSItems(legacyFile, jsonFile) {
// Load .rdf file into an XMLDocument.
let rawXMLRDF = IOUtils.loadFileToString(legacyFile);
let rawXMLRDF;
try {
rawXMLRDF = await IOUtils.readUTF8(legacyFile.path);
} catch (ex) {
if (["NotFoundError"].includes(ex.name)) {
return; // nothing legacy file to migrate
}
}
let parser = new DOMParser();
let doc = parser.parseFromString(rawXMLRDF, "text/xml");
@ -834,8 +840,7 @@ var MailMigrator = {
}
}
let data = JSON.stringify(items);
IOUtils.saveStringToFile(jsonFile, data);
await IOUtils.writeJSON(jsonFile.path, items);
legacyFile.remove(false);
},

Просмотреть файл

@ -12,7 +12,6 @@
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var { IOUtils } = ChromeUtils.import("resource:///modules/IOUtils.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { FileUtils } = ChromeUtils.import("resource://gre/modules/FileUtils.jsm");
var { PrivateBrowsingUtils } = ChromeUtils.import(

Просмотреть файл

@ -17,7 +17,6 @@ var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var { IOUtils } = ChromeUtils.import("resource:///modules/IOUtils.jsm");
/**
* Each abDirTreeItem corresponds to one row in the tree view.
@ -121,12 +120,22 @@ directoryTreeView.prototype = {
"addrbook-reloaded",
],
init(aTree, aJSONFile) {
/**
* Init the tree view.
*
* @param {XULTreeElement} aTree - The element to init.
* @param {string} [aJSONFile] - The persistent-open-state JSON file; directoryTree.json
*/
async init(aTree, aJSONFile = null) {
if (aJSONFile) {
// Parse our persistent-open-state json file
let data = IOUtils.loadFileToString(aJSONFile);
if (data) {
this._persistOpenMap = JSON.parse(data);
let spec = PathUtils.join(await PathUtils.getProfileDir(), aJSONFile);
try {
this._persistOpenMap = await IOUtils.readJSON(spec);
} catch (ex) {
if (!["NotFoundError"].includes(ex.name)) {
Cu.reportError(ex);
}
}
}
@ -138,12 +147,12 @@ directoryTreeView.prototype = {
}
},
shutdown(aJSONFile) {
async shutdown(aJSONFile) {
// Write out the persistOpenMap to our JSON file
if (aJSONFile) {
// Write out our json file...
let data = JSON.stringify(this._persistOpenMap);
IOUtils.saveStringToFile(aJSONFile, data);
let spec = PathUtils.join(await PathUtils.getProfileDir(), aJSONFile);
await IOUtils.writeJSON(spec, this._persistOpenMap);
}
},

Просмотреть файл

@ -61,7 +61,7 @@ var kFirstNameFirst = 2;
// of IM contacts).
var kChatProperties = ["_GoogleTalk", "_JabberId"];
function OnUnloadAddressBook() {
async function OnUnloadAddressBook() {
// If there's no default startupURI, save the last used URI as new startupURI.
let saveLastURIasStartupURI = !Services.prefs.getBoolPref(
"mail.addr_book.view.startupURIisDefault"
@ -76,7 +76,7 @@ function OnUnloadAddressBook() {
// Shutdown the tree view - this will also save the open/collapsed
// state of the tree view to a JSON file.
gDirectoryTreeView.shutdown(kPersistCollapseMapStorage);
await gDirectoryTreeView.shutdown(kPersistCollapseMapStorage);
MailServices.mailSession.RemoveMsgWindow(msgWindow);
@ -145,10 +145,10 @@ function OnLoadAddressBook() {
chatHandler.ChatCore.init();
}
setTimeout(delayedOnLoadAddressBook, 0); // when debugging, set this to 5000, so you can see what happens after the window comes up.
delayedOnLoadAddressBook();
}
function delayedOnLoadAddressBook() {
async function delayedOnLoadAddressBook() {
InitCommonJS();
GetCurrentPrefs();
@ -157,7 +157,7 @@ function delayedOnLoadAddressBook() {
OnLoadCardView();
// Initialize the Address Book tree view
gDirectoryTreeView.init(gDirTree, kPersistCollapseMapStorage);
await gDirectoryTreeView.init(gDirTree, kPersistCollapseMapStorage);
selectStartupViewDirectory();
gAbResultsTree.focus();

Просмотреть файл

@ -73,7 +73,8 @@ add_task(async function test_additions_and_removals() {
observer.setUp();
openRootDirectory();
await openRootDirectory();
info("Performing check #1");
checkCardsListed(contactA1, contactB1);
// While in bookA, add a contact and list. Check that they show up.
@ -87,7 +88,8 @@ add_task(async function test_additions_and_removals() {
listC.addCard(contactA1);
checkCardsListed(contactA1, contactA2, listC);
openRootDirectory();
await openRootDirectory();
info("Performing check #2");
checkCardsListed(contactA1, contactA2, contactB1, listC);
// While in listC, add a member and remove a member. Check that they show up
@ -99,7 +101,8 @@ add_task(async function test_additions_and_removals() {
await deleteRowWithPrompt(0);
checkCardsListed(contactA2);
openRootDirectory();
await openRootDirectory();
info("Performing check #3");
checkCardsListed(contactA1, contactA2, contactB1, listC);
// While in bookA, delete a contact. Check it disappears.
@ -116,7 +119,8 @@ add_task(async function test_additions_and_removals() {
listD.addCard(contactB1);
checkCardsListed(contactA2, listC);
openRootDirectory();
await openRootDirectory();
info("Performing check #4");
checkCardsListed(contactA2, contactB1, contactB2, listC, listD);
// While in listC, do some things in an unrelated list. Check nothing
@ -130,7 +134,8 @@ add_task(async function test_additions_and_removals() {
bookB.deleteCards([contactB1]);
checkCardsListed(contactA2);
openRootDirectory();
await openRootDirectory();
info("Performing check #5");
checkCardsListed(contactA2, contactB2, listC, listD);
// While in bookA, do some things in an unrelated book. Check nothing
@ -145,7 +150,8 @@ add_task(async function test_additions_and_removals() {
// While in "All Address Books", make some changes and check that things
// appear or disappear as appropriate.
openRootDirectory();
await openRootDirectory();
info("Performing check #6");
checkCardsListed(contactA2, contactB2);
let listE = bookB.addMailList(createMailingList("list E")); // Add E.
checkDirectoryDisplayed(null);

Просмотреть файл

@ -40,6 +40,7 @@ add_task(async () => {
let abWindow = await openAddressBookWindow();
let dirTree = abWindow.document.getElementById("dirTree");
Assert.equal(
dirTree.view.getCellText(2, dirTree.columns[0]),
inputs.abName,

Просмотреть файл

@ -42,7 +42,6 @@ async function openAddressBookWindow() {
abWindow,
"address book window has focus"
);
return abWindow;
}
@ -60,7 +59,7 @@ function getAddressBookWindow() {
return Services.wm.getMostRecentWindow("mail:addressbook");
}
function openRootDirectory() {
async function openRootDirectory() {
let abWindow = getAddressBookWindow();
let abDirTree = abWindow.gDirTree;
mailTestUtils.treeClick(EventUtils, abWindow, abDirTree, 0, 0, {});

Просмотреть файл

@ -50,7 +50,6 @@ add_task(function test_re_test_config() {
// unwind before opening the next one, so do that here.
mc.sleep(0);
open_mail_account_setup_wizard(function(awc) {
dump("xxxmagnus opened!\n");
// Input user's account information
awc.click(awc.eid("realname"));
if (awc.e("realname").value) {

Просмотреть файл

@ -31,8 +31,6 @@ var { close_window } = ChromeUtils.import(
"resource://testing-common/mozmill/WindowHelpers.jsm"
);
var { IOUtils } = ChromeUtils.import("resource:///modules/IOUtils.jsm");
var gImageFolder;
add_task(function setupModule(module) {
@ -89,7 +87,7 @@ add_task(async function test_cid_image_load() {
);
// Make sure there is a cid: referenced image in the message.
let msgSource = IOUtils.loadFileToString(file);
let msgSource = await IOUtils.readUTF8(file.path);
Assert.ok(msgSource.includes('<img src="cid:'));
// Our image should be in the loaded eml document.

Просмотреть файл

@ -37,7 +37,6 @@ var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var { IOUtils } = ChromeUtils.import("resource:///modules/IOUtils.jsm");
var statusHeader = "X-Mozilla-Status: ";
@ -94,7 +93,7 @@ add_task(function setupModule(module) {
* @param aStatusOffset Offset from the start of the message where the status line is. Optional.
* @param aStatus The required status of the message.
*/
function check_status(aMsgHdr, aOffset, aStatusOffset, aStatus) {
async function check_status(aMsgHdr, aOffset, aStatusOffset, aStatus) {
if (aOffset == null) {
aOffset = aMsgHdr.messageOffset;
}
@ -103,8 +102,7 @@ function check_status(aMsgHdr, aOffset, aStatusOffset, aStatus) {
}
let folder = aMsgHdr == null ? gInbox : aMsgHdr.folder;
let mboxstring = IOUtils.loadFileToString(folder.filePath);
let mboxstring = await IOUtils.readUTF8(folder.filePath.path);
let expectedStatusString = aStatus.toString(16);
while (expectedStatusString.length < 4) {
@ -127,7 +125,7 @@ function check_status(aMsgHdr, aOffset, aStatusOffset, aStatus) {
);
}
add_task(function test_mark_messages_read() {
add_task(async function test_mark_messages_read() {
// 5 messages in the folder
be_in_folder(gInbox);
let curMessage = select_click_row(0);
@ -135,10 +133,10 @@ add_task(function test_mark_messages_read() {
// after the message is deleted.
let offset = curMessage.messageOffset;
let statusOffset = curMessage.statusOffset;
check_status(curMessage, null, null, 0); // status = unread
await check_status(curMessage, null, null, 0); // status = unread
press_delete(mc);
Assert.notEqual(curMessage, select_click_row(0));
check_status(
await check_status(
null,
offset,
statusOffset,
@ -147,7 +145,7 @@ add_task(function test_mark_messages_read() {
// 4 messages in the folder.
curMessage = select_click_row(0);
check_status(curMessage, null, null, 0); // status = unread
await check_status(curMessage, null, null, 0); // status = unread
// Make sure we can mark all read with >0 messages unread.
right_click_on_row(0);
@ -158,16 +156,16 @@ add_task(function test_mark_messages_read() {
// All the 4 messages should now be read.
Assert.ok(curMessage.isRead, "Message should have been marked Read!");
check_status(curMessage, null, null, Ci.nsMsgMessageFlags.Read);
await check_status(curMessage, null, null, Ci.nsMsgMessageFlags.Read);
curMessage = select_click_row(1);
Assert.ok(curMessage.isRead, "Message should have been marked Read!");
check_status(curMessage, null, null, Ci.nsMsgMessageFlags.Read);
await check_status(curMessage, null, null, Ci.nsMsgMessageFlags.Read);
curMessage = select_click_row(2);
Assert.ok(curMessage.isRead, "Message should have been marked Read!");
check_status(curMessage, null, null, Ci.nsMsgMessageFlags.Read);
await check_status(curMessage, null, null, Ci.nsMsgMessageFlags.Read);
curMessage = select_click_row(3);
Assert.ok(curMessage.isRead, "Message should have been marked Read!");
check_status(curMessage, null, null, Ci.nsMsgMessageFlags.Read);
await check_status(curMessage, null, null, Ci.nsMsgMessageFlags.Read);
// Let's have the last message unread.
right_click_on_row(3);
@ -176,10 +174,10 @@ add_task(function test_mark_messages_read() {
{ id: "mailContext-markUnread" },
]);
Assert.ok(!curMessage.isRead, "Message should have not been marked Read!");
check_status(curMessage, null, null, 0);
await check_status(curMessage, null, null, 0);
});
add_task(function test_mark_messages_flagged() {
add_task(async function test_mark_messages_flagged() {
// Mark a message with the star.
let curMessage = select_click_row(1);
right_click_on_row(1);
@ -188,7 +186,7 @@ add_task(function test_mark_messages_flagged() {
{ id: "mailContext-markFlagged" },
]);
Assert.ok(curMessage.isFlagged, "Message should have been marked Flagged!");
check_status(
await check_status(
curMessage,
null,
null,
@ -196,11 +194,11 @@ add_task(function test_mark_messages_flagged() {
);
});
function subtest_check_queued_message() {
async function subtest_check_queued_message() {
// Always check the last message in the Outbox for the correct flag.
be_in_folder(gOutbox);
let lastMsg = [...gOutbox.messages].pop();
check_status(lastMsg, null, null, Ci.nsMsgMessageFlags.Queued);
await check_status(lastMsg, null, null, Ci.nsMsgMessageFlags.Queued);
}
/**
@ -209,7 +207,7 @@ function subtest_check_queued_message() {
* @param aMsgRow Row index of message in Inbox that is to be replied/forwarded.
* @param aReply true = reply, false = forward.
*/
function reply_forward_message(aMsgRow, aReply) {
async function reply_forward_message(aMsgRow, aReply) {
be_in_folder(gInbox);
select_click_row(aMsgRow);
let cwc;
@ -237,7 +235,7 @@ function reply_forward_message(aMsgRow, aReply) {
);
wait_for_window_close(cwc);
subtest_check_queued_message();
await subtest_check_queued_message();
// Now this is hacky. We can't get the message to be sent out of TB because there
// is no fake SMTP server support yet.
@ -253,10 +251,10 @@ function reply_forward_message(aMsgRow, aReply) {
gInbox.addMessageDispositionState(curMessage, disposition);
}
add_task(function test_mark_messages_replied() {
reply_forward_message(2, true);
add_task(async function test_mark_messages_replied() {
await reply_forward_message(2, true);
let curMessage = select_click_row(2);
check_status(
await check_status(
curMessage,
null,
null,
@ -264,23 +262,23 @@ add_task(function test_mark_messages_replied() {
);
});
add_task(function test_mark_messages_forwarded() {
add_task(async function test_mark_messages_forwarded() {
be_in_folder(gInbox);
// Forward a clean message.
reply_forward_message(3, false);
await reply_forward_message(3, false);
let curMessage = select_click_row(3);
check_status(curMessage, null, null, Ci.nsMsgMessageFlags.Forwarded);
await check_status(curMessage, null, null, Ci.nsMsgMessageFlags.Forwarded);
// Forward a message that is read and already replied to.
curMessage = select_click_row(2);
check_status(
await check_status(
curMessage,
null,
null,
Ci.nsMsgMessageFlags.Replied + Ci.nsMsgMessageFlags.Read
);
reply_forward_message(2, false);
check_status(
await reply_forward_message(2, false);
await check_status(
curMessage,
null,
null,

Просмотреть файл

@ -9,6 +9,10 @@
"use strict";
var { mailTestUtils } = ChromeUtils.import(
"resource://testing-common/mailnews/MailTestUtils.jsm"
);
var controller = ChromeUtils.import(
"resource://testing-common/mozmill/controller.jsm"
);
@ -41,7 +45,6 @@ var {
wait_for_window_close,
} = ChromeUtils.import("resource://testing-common/mozmill/WindowHelpers.jsm");
var { IOUtils } = ChromeUtils.import("resource:///modules/IOUtils.jsm");
var { FileUtils } = ChromeUtils.import("resource://gre/modules/FileUtils.jsm");
var { SessionStoreManager } = ChromeUtils.import(
"resource:///modules/SessionStoreManager.jsm"
@ -61,20 +64,32 @@ var asyncFileWriteDelayMS = 3000;
/**
* Reads the contents of the session file into a JSON object.
*/
function readFile() {
async function readFile2() {
try {
let data = IOUtils.loadFileToString(SessionStoreManager.sessionFile);
if (data) {
return JSON.parse(data);
}
return await IOUtils.readJSON(SessionStoreManager.sessionFile.path);
} catch (ex) {
if (!["NotFoundError"].includes(ex.name)) {
Cu.reportError(ex);
}
// fall through and return null if the session file cannot be read
// or is bad
dump(ex + "\n");
}
return null;
}
/**
* Reads the contents of the session file into a JSON object.
* FIXME: readFile2 should really be used instead. For some weird reason using
* that, OR making this function async (+ await the results) will
* not work - seem like the file reading just dies (???)
* So use the sync file reading for now...
*/
function readFile() {
let data = mailTestUtils.loadFileToString(SessionStoreManager.sessionFile);
return JSON.parse(data);
}
function waitForFileRefresh() {
controller.sleep(kSaveDelayMs);
utils.waitFor(
@ -169,7 +184,7 @@ add_task(function test_periodic_nondirty_session_persistence() {
utils.waitFor(() => !sessionFile.exists(), "session file should not exist");
});
add_task(function test_single_3pane_periodic_session_persistence() {
add_task(async function test_single_3pane_periodic_session_persistence() {
be_in_folder(folderA);
// get the state object. this assumes there is one and only one
@ -453,7 +468,7 @@ add_task(function test_message_pane_width_persistence() {
wait_for_window_close();
});
add_task(function test_multiple_3pane_periodic_session_persistence() {
add_task(async function test_multiple_3pane_periodic_session_persistence() {
// open a few more 3pane windows
for (var i = 0; i < 3; ++i) {
open3PaneWindow();
@ -470,6 +485,7 @@ add_task(function test_multiple_3pane_periodic_session_persistence() {
// load the saved state from disk
let loadedState = readFile();
Assert.ok(loadedState, "previously saved state should be non-null");
Assert.equal(
@ -486,11 +502,9 @@ add_task(function test_multiple_3pane_periodic_session_persistence() {
}
// close all but one 3pane window
let enumerator = Services.wm.getEnumerator("mail:3pane");
for (let window of enumerator) {
if (enumerator.hasMoreElements()) {
window.close();
}
let windows = Services.wm.getEnumerator("mail:3pane");
for (let win of windows) {
win.close();
}
});
@ -520,7 +534,7 @@ async function test_bad_session_file_simple() {
);
}
add_task(function test_clean_shutdown_session_persistence_simple() {
add_task(async function test_clean_shutdown_session_persistence_simple() {
// open a few more 3pane windows
for (var i = 0; i < 3; ++i) {
open3PaneWindow();

Просмотреть файл

@ -162,6 +162,7 @@ ABView.prototype = {
if (tree) {
Services.obs.addObserver(this, topic, true);
} else {
// XXX: seems |this| is not usually a valid observer here
Services.obs.removeObserver(this, topic);
}
}

Просмотреть файл

@ -14,7 +14,6 @@ XPCOMUtils.defineLazyModuleGetters(this, {
setTimeout: "resource://gre/modules/Timer.jsm",
clearTimeout: "resource://gre/modules/Timer.jsm",
MailE10SUtils: "resource:///modules/MailE10SUtils.jsm",
Services: "resource://gre/modules/Services.jsm",
});
/* globals for a particular window */

Просмотреть файл

@ -1,143 +0,0 @@
/* 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/. */
const EXPORTED_SYMBOLS = ["IOUtils"];
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var kStringBlockSize = 4096;
var kStreamBlockSize = 8192;
var IOUtils = {
/**
* Read a file containing ASCII text into a string.
*
* @param aFile An nsIFile representing the file to read or a string containing
* the file name of a file under user's profile.
* @returns A string containing the contents of the file, presumed to be ASCII
* text. If the file didn't exist, returns null.
*/
loadFileToString(aFile) {
let file;
if (!(aFile instanceof Ci.nsIFile)) {
file = Services.dirsvc.get("ProfD", Ci.nsIFile);
file.append(aFile);
} else {
file = aFile;
}
if (!file.exists()) {
return null;
}
let fstream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(
Ci.nsIFileInputStream
);
// PR_RDONLY
fstream.init(file, 0x01, 0, 0);
let sstream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(
Ci.nsIScriptableInputStream
);
sstream.init(fstream);
let data = "";
while (sstream.available()) {
data += sstream.read(kStringBlockSize);
}
sstream.close();
fstream.close();
return data;
},
/**
* Save a string containing ASCII text into a file. The file will be overwritten
* and contain only the given text.
*
* @param aFile An nsIFile representing the file to write or a string containing
* the file name of a file under user's profile.
* @param aData The string to write.
* @param aPerms The octal file permissions for the created file. If unset
* the default of 0o600 is used.
*/
saveStringToFile(aFile, aData, aPerms = 0o600) {
let file;
if (!(aFile instanceof Ci.nsIFile)) {
file = Services.dirsvc.get("ProfD", Ci.nsIFile);
file.append(aFile);
} else {
file = aFile;
}
let foStream = Cc[
"@mozilla.org/network/safe-file-output-stream;1"
].createInstance(Ci.nsIFileOutputStream);
// PR_WRONLY + PR_CREATE_FILE + PR_TRUNCATE
foStream.init(file, 0x02 | 0x08 | 0x20, aPerms, 0);
// safe-file-output-stream appears to throw an error if it doesn't write everything at once
// so we won't worry about looping to deal with partial writes.
// In case we try to use this function for big files where buffering
// is needed we could use the implementation in saveStreamToFile().
foStream.write(aData, aData.length);
foStream.QueryInterface(Ci.nsISafeOutputStream).finish();
foStream.close();
},
/**
* Saves the given input stream to a file.
*
* @param aIStream The input stream to save.
* @param aFile The file to which the stream is saved.
* @param aPerms The octal file permissions for the created file. If unset
* the default of 0o600 is used.
*/
saveStreamToFile(aIStream, aFile, aPerms = 0o600) {
if (!(aIStream instanceof Ci.nsIInputStream)) {
throw new Error("Invalid stream passed to saveStreamToFile");
}
if (!(aFile instanceof Ci.nsIFile)) {
throw new Error("Invalid file passed to saveStreamToFile");
}
let fstream = Cc[
"@mozilla.org/network/safe-file-output-stream;1"
].createInstance(Ci.nsIFileOutputStream);
let buffer = Cc[
"@mozilla.org/network/buffered-output-stream;1"
].createInstance(Ci.nsIBufferedOutputStream);
// Write the input stream to the file.
// PR_WRITE + PR_CREATE + PR_TRUNCATE
fstream.init(aFile, 0x04 | 0x08 | 0x20, aPerms, 0);
buffer.init(fstream, kStreamBlockSize);
buffer.writeFrom(aIStream, aIStream.available());
// Close the output streams.
if (buffer instanceof Ci.nsISafeOutputStream) {
buffer.finish();
} else {
buffer.close();
}
if (fstream instanceof Ci.nsISafeOutputStream) {
fstream.finish();
} else {
fstream.close();
}
// Close the input stream.
aIStream.close();
return aFile;
},
/**
* Returns size of system memory.
*/
getPhysicalMemorySize() {
return Services.sysinfo.getPropertyAsInt64("memsize");
},
};

Просмотреть файл

@ -103,7 +103,6 @@ EXTRA_JS_MODULES += [
"FolderLookupService.jsm",
"folderUtils.jsm",
"hostnameUtils.jsm",
"IOUtils.jsm",
"iteratorUtils.jsm",
"JsTreeSelection.jsm",
"JXON.jsm",

Просмотреть файл

@ -2,7 +2,6 @@ var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var { IOUtils } = ChromeUtils.import("resource:///modules/IOUtils.jsm");
var { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);

Просмотреть файл

@ -206,7 +206,6 @@ function testReply(aHrdIdx, aTemplateHdrIdx = 0) {
let headers, body;
[headers, body] = MimeParser.extractHeadersAndBody(gServer._daemon.post);
// dump("xxxmagnus gServer._daemon.post=" + gServer._daemon.post + "\n");
Assert.ok(headers.get("Subject").startsWith("Auto: "));
Assert.equal(headers.get("Auto-submitted"), "auto-replied");
Assert.equal(headers.get("In-Reply-To"), "<" + msgHdr.messageId + ">");

Просмотреть файл

@ -187,9 +187,9 @@ function sendMessageLater() {
}
}
function run_test() {
add_task(async function run_the_test() {
// Test file - for bug 429891
originalData = IOUtils.loadFileToString(testFile);
originalData = await IOUtils.readUTF8(testFile.path);
// Ensure we have a local mail account, an normal account and appropriate
// servers and identities.
@ -250,4 +250,4 @@ function run_test() {
// Now we wait till we get copy notification of completion.
do_test_pending();
}
});

Просмотреть файл

@ -94,7 +94,7 @@ msll.prototype = {
},
};
function run_test() {
add_task(async function run_the_test() {
// The point of this test - send in background.
Services.prefs.setBoolPref("mailnews.sendInBackground", true);
@ -108,7 +108,7 @@ function run_test() {
);
// Test file - for bug 429891
originalData = IOUtils.loadFileToString(testFile1);
originalData = await IOUtils.readUTF8(testFile1.path);
// Check that the send later service thinks we don't have messages to send
Assert.equal(gMsgSendLater.hasUnsentMessages(identity), false);
@ -220,4 +220,4 @@ function run_test() {
thread.processNextEvent(true);
}
}
}
});

Просмотреть файл

@ -125,7 +125,7 @@ MsgSendListener.prototype = {
]),
};
function DoSendTest(aRecipient, aRecipientExpected) {
async function doSendTest(aRecipient, aRecipientExpected) {
info(`Testing send to ${aRecipient} will get sent to ${aRecipientExpected}`);
test = aRecipient;
server = setupServerDaemon();
@ -136,7 +136,7 @@ function DoSendTest(aRecipient, aRecipientExpected) {
// Random test file with data we don't actually care about. ;-)
var testFile = do_get_file("data/message1.eml");
var originalData = IOUtils.loadFileToString(testFile);
var originalData = await IOUtils.readUTF8(testFile.path);
// Handle the server in a try/catch/finally loop so that we always will stop
// the server if something fails.
@ -191,13 +191,13 @@ add_task(function setup() {
sentFolder = localAccountUtils.rootFolder.createLocalSubfolder("Sent");
});
add_task(function plainASCIIRecipient() {
add_task(async function plainASCIIRecipient() {
// Test 1:
// Plain ASCII recipient address.
DoSendTest(kToASCII, kToASCII);
await doSendTest(kToASCII, kToASCII);
});
add_task(function domainContainsNonAscii() {
add_task(async function domainContainsNonAscii() {
// Test 2:
// The recipient's domain part contains a non-ASCII character, hence the
// address needs to be converted to ACE before sending.
@ -205,21 +205,21 @@ add_task(function domainContainsNonAscii() {
// the message to the remaining - wrong! - address.
// The new code will translate the domain part to ACE for the SMTP
// transaction (only), i.e. the To: header will stay as stated by the sender.
DoSendTest(kToValid, kToValidACE);
await doSendTest(kToValid, kToValidACE);
});
add_task(function localContainsNonAscii() {
add_task(async function localContainsNonAscii() {
// Test 3:
// The recipient's local part contains a non-ASCII character, which is not
// allowed with unextended SMTP.
// The old code would just strip the invalid character and try to send the
// message to the remaining - wrong! - address.
// The new code will present an informational message box and deny sending.
DoSendTest(kToInvalid, kToInvalid);
await doSendTest(kToInvalid, kToInvalid);
});
add_task(function invalidCharNoAt() {
add_task(async function invalidCharNoAt() {
// Test 4:
// Bug 856506. invalid char without '@' causes crash.
DoSendTest(kToInvalidWithoutDomain, kToInvalidWithoutDomain);
await doSendTest(kToInvalidWithoutDomain, kToInvalidWithoutDomain);
});

Просмотреть файл

@ -94,12 +94,12 @@ msl.prototype = {
]),
};
function run_test() {
add_task(async function run_the_test() {
server = setupServerDaemon();
// Test file - for bug 429891
var testFile = do_get_file("data/429891_testcase.eml");
originalData = IOUtils.loadFileToString(testFile);
originalData = await IOUtils.readUTF8(testFile.path);
// Ensure we have at least one mail account
localAccountUtils.loadLocalMailAccount();
@ -169,4 +169,4 @@ function run_test() {
thread.processNextEvent(true);
}
}
}
});

Просмотреть файл

@ -192,9 +192,9 @@ function sendMessageLater() {
}
}
function run_test() {
add_task(async function run_the_test() {
// Test file - for bug 429891
originalData = IOUtils.loadFileToString(testFile);
originalData = await IOUtils.readUTF8(testFile.path);
// Ensure we have a local mail account, an normal account and appropriate
// servers and identities.
@ -258,4 +258,4 @@ function run_test() {
// Now we wait till we get copy notification of completion.
do_test_pending();
}
});

Просмотреть файл

@ -235,10 +235,10 @@ function* actually_run_test() {
do_test_finished();
}
function run_test() {
add_task(async function run_the_test() {
// Load in the test files so we have a record of length and their data.
for (var i = 0; i < gMsgFile.length; ++i) {
gMsgFileData[i] = IOUtils.loadFileToString(gMsgFile[i]);
gMsgFileData[i] = await IOUtils.readUTF8(gMsgFile[i].path);
}
// Ensure we have a local mail account, an normal account and appropriate
@ -287,4 +287,4 @@ function run_test() {
// Do the test
async_run({ func: actually_run_test });
}
});

Просмотреть файл

@ -122,11 +122,11 @@ function sendMessageLater() {
msgSendLater.sendUnsentMessages(identity);
}
function run_test() {
add_task(async function run_the_test() {
registerAlertTestUtils();
// Test file - for bug 429891
originalData = IOUtils.loadFileToString(testFile);
originalData = await IOUtils.readUTF8(testFile.path);
// Ensure we have a local mail account, an normal account and appropriate
// servers and identities.
@ -186,4 +186,4 @@ function run_test() {
// Now we wait till we get copy notification of completion.
do_test_pending();
}
});

Просмотреть файл

@ -10,7 +10,6 @@
const EXPORTED_SYMBOLS = ["GlodaDatastore"];
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { IOUtils } = ChromeUtils.import("resource:///modules/IOUtils.jsm");
const {
GlodaAttributeDBDef,
@ -1363,7 +1362,7 @@ var GlodaDatastore = {
);
cachePermillage = Math.min(cachePermillage, 50);
cachePermillage = Math.max(cachePermillage, 0);
let physMem = IOUtils.getPhysicalMemorySize();
let physMem = Services.sysinfo.getPropertyAsInt64("memsize");
if (physMem == 0) {
physMem = MEMSIZE_FALLBACK_BYTES;
}

Просмотреть файл

@ -33,7 +33,7 @@ async function migrationTest(testDataDir) {
}
// Perform the migration
MailMigrator._migrateRSSServer(account.incomingServer);
await MailMigrator._migrateRSSServer(account.incomingServer);
// Check actual results against expectations.
let loadJSON = async function(filename) {

Просмотреть файл

@ -2,10 +2,9 @@
* Test bug 460636 - nsMsgSaveAsListener sometimes inserts extra LF characters
*/
/* import-globals-from ../../../test/resources/logHelper.js */
/* import-globals-from ../../../test/resources/asyncTestUtils.js */
load("../../../resources/logHelper.js");
load("../../../resources/asyncTestUtils.js");
var { PromiseTestUtils } = ChromeUtils.import(
"resource://testing-common/mailnews/PromiseTestUtils.jsm"
);
var gSavedMsgFile;
@ -16,15 +15,17 @@ var gIMAPService = Cc[
var gFileName = "bug460636";
var gMsgFile = do_get_file("../../../data/" + gFileName);
var tests = [setup, checkSavedMessage, teardown];
add_task(async function run_the_test() {
await setup();
await checkSavedMessage();
teardown();
});
function* setup() {
async function setup() {
setupIMAPPump();
/*
* Ok, prelude done. Read the original message from disk
* (through a file URI), and add it to the Inbox.
*/
// Ok, prelude done. Read the original message from disk
// (through a file URI), and add it to the Inbox.
var msgfileuri = Services.io
.newFileURI(gMsgFile)
.QueryInterface(Ci.nsIFileURL);
@ -32,44 +33,41 @@ function* setup() {
IMAPPump.mailbox.addMessage(
new imapMessage(msgfileuri.spec, IMAPPump.mailbox.uidnext++, [])
);
IMAPPump.inbox.updateFolderWithListener(null, asyncUrlListener);
yield false;
let promiseUrlListener = new PromiseTestUtils.PromiseUrlListener();
IMAPPump.inbox.updateFolderWithListener(null, promiseUrlListener);
await promiseUrlListener.promise;
/*
* Save the message to a local file. IMapMD corresponds to
* <profile_dir>/mailtest/ImapMail (where fakeserver puts the IMAP mailbox
* files). If we pass the test, we'll remove the file afterwards
* (cf. UrlListener), otherwise it's kept in IMapMD.
*/
// Save the message to a local file. IMapMD corresponds to
// <profile_dir>/mailtest/ImapMail (where fakeserver puts the IMAP mailbox
// files). If we pass the test, we'll remove the file afterwards
// (cf. UrlListener), otherwise it's kept in IMapMD.
gSavedMsgFile = Services.dirsvc.get("IMapMD", Ci.nsIFile);
gSavedMsgFile.append(gFileName + ".eml");
/*
* From nsIMsgMessageService.idl:
* void SaveMessageToDisk(in string aMessageURI, in nsIFile aFile,
* in boolean aGenerateDummyEnvelope,
* in nsIUrlListener aUrlListener, out nsIURI aURL,
* in boolean canonicalLineEnding,
* in nsIMsgWindow aMsgWindow);
* Enforcing canonicalLineEnding (i.e., CRLF) makes sure that the
* test also runs successfully on platforms not using CRLF by default.
*/
// From nsIMsgMessageService.idl:
// void SaveMessageToDisk(in string aMessageURI, in nsIFile aFile,
// in boolean aGenerateDummyEnvelope,
// in nsIUrlListener aUrlListener, out nsIURI aURL,
// in boolean canonicalLineEnding,
// in nsIMsgWindow aMsgWindow);
// Enforcing canonicalLineEnding (i.e., CRLF) makes sure that the
let promiseUrlListener2 = new PromiseTestUtils.PromiseUrlListener();
gIMAPService.SaveMessageToDisk(
"imap-message://user@localhost/INBOX#" + (IMAPPump.mailbox.uidnext - 1),
gSavedMsgFile,
false,
asyncUrlListener,
promiseUrlListener2,
{},
true,
null
);
yield false;
await promiseUrlListener2.promise;
}
function checkSavedMessage() {
async function checkSavedMessage() {
Assert.equal(
IOUtils.loadFileToString(gMsgFile),
IOUtils.loadFileToString(gSavedMsgFile)
await IOUtils.readUTF8(gMsgFile.path),
await IOUtils.readUTF8(gSavedMsgFile.path)
);
}
@ -82,7 +80,3 @@ function teardown() {
}
teardownIMAPPump();
}
function run_test() {
async_run_tests(tests);
}

Просмотреть файл

@ -11,11 +11,9 @@
* that are run externally.
*/
// async support
/* import-globals-from ../../../test/resources/logHelper.js */
/* import-globals-from ../../../test/resources/asyncTestUtils.js */
load("../../../resources/logHelper.js");
load("../../../resources/asyncTestUtils.js");
var { PromiseTestUtils } = ChromeUtils.import(
"resource://testing-common/mailnews/PromiseTestUtils.jsm"
);
var gFile = do_get_file("../../../data/bug92111b");
var gIMAPDaemon, gIMAPServer, gIMAPIncomingServer;
@ -29,7 +27,7 @@ function addMessageToServer(file, mailbox) {
mailbox.addMessage(msg);
}
function run_test() {
add_task(async function verifyContentLength() {
// Disable new mail notifications
Services.prefs.setBoolPref("mail.biff.play_sound", false);
Services.prefs.setBoolPref("mail.biff.show_alert", false);
@ -56,10 +54,6 @@ function run_test() {
// We aren't interested in downloading messages automatically
Services.prefs.setBoolPref("mail.server.server1.download_on_biff", false);
async_run_tests([verifyContentLength, endTest]);
}
function* verifyContentLength() {
dump("adding message to server\n");
// Add a message to the IMAP server
addMessageToServer(gFile, gIMAPDaemon.getMailbox("INBOX"));
@ -68,7 +62,6 @@ function* verifyContentLength() {
"@mozilla.org/messenger/messageservice;1?type=imap"
].getService(Ci.nsIMsgMessageService);
dump("getting uri\n");
let uri = imapS.getUrlForUri("imap-message://user@localhost/INBOX#1");
// Get a channel from this URI, and check its content length
@ -81,15 +74,15 @@ function* verifyContentLength() {
Ci.nsIContentPolicy.TYPE_OTHER
);
dump(channel + "\n");
let promiseStreamListener = new PromiseTestUtils.PromiseStreamListener();
// Read all the contents
channel.asyncOpen(gStreamListener, null);
yield false;
channel.asyncOpen(promiseStreamListener, null);
let streamData = (await promiseStreamListener.promise).replace(/\r\n/g, "\n");
// Now check whether our stream listener got the right bytes
// First, clean up line endings to avoid CRLF vs. LF differences
let origData = IOUtils.loadFileToString(gFile).replace(/\r\n/g, "\n");
let streamData = gStreamListener._data.replace(/\r\n/g, "\n");
let origData = (await IOUtils.readUTF8(gFile.path)).replace(/\r\n/g, "\n");
Assert.equal(origData.length, streamData.length);
Assert.equal(origData, streamData);
@ -106,38 +99,10 @@ function* verifyContentLength() {
// entire message
// do_check_eq(attachmentChannel.contentLength, gFile.fileSize);
yield true;
}
function* endTest() {
gIMAPIncomingServer.closeCachedConnections();
gIMAPServer.stop();
let thread = gThreadManager.currentThread;
while (thread.hasPendingEvents()) {
thread.processNextEvent(true);
}
yield true;
}
var gStreamListener = {
QueryInterface: ChromeUtils.generateQI(["nsIStreamListener"]),
_stream: null,
_data: null,
onStartRequest(aRequest) {
this._data = "";
this._stream = null;
},
onStopRequest(aRequest, aStatusCode) {
async_driver();
},
onDataAvailable(aRequest, aInputStream, aOff, aCount) {
if (this._stream == null) {
this._stream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(
Ci.nsIScriptableInputStream
);
this._stream.init(aInputStream);
}
this._data += this._stream.read(aCount);
},
};
});

Просмотреть файл

@ -1,10 +1,8 @@
/*
/**
* Test bug 92111 - imap download-by-chunks doesn't download complete file if the
* server lies about rfc822.size (known to happen for Exchange and gmail)
*/
var { IOUtils } = ChromeUtils.import("resource:///modules/IOUtils.jsm");
var gIMAPDaemon, gServer, gIMAPIncomingServer, gSavedMsgFile;
var gIMAPService = Cc[
@ -14,7 +12,7 @@ var gIMAPService = Cc[
var gFileName = "bug92111";
var gMsgFile = do_get_file("../../../data/" + gFileName);
function run_test() {
add_task(async function run_the_test() {
/*
* Set up an IMAP server. The bug is only triggered when nsMsgSaveAsListener
* is used (i.e., for IMAP and NNTP).
@ -55,12 +53,10 @@ function run_test() {
message.setSize(gMsgFile.fileSize - 100);
inbox.addMessage(message);
/*
* Save the message to a local file. IMapMD corresponds to
* <profile_dir>/mailtest/ImapMail (where fakeserver puts the IMAP mailbox
* files). If we pass the test, we'll remove the file afterwards
* (cf. UrlListener), otherwise it's kept in IMapMD.
*/
// Save the message to a local file. IMapMD corresponds to
// <profile_dir>/mailtest/ImapMail (where fakeserver puts the IMAP mailbox
// files). If we pass the test, we'll remove the file afterwards
// (cf. UrlListener), otherwise it's kept in IMapMD.
gSavedMsgFile = Services.dirsvc.get("IMapMD", Ci.nsIFile);
gSavedMsgFile.append(gFileName + ".eml");
@ -72,26 +68,30 @@ function run_test() {
);
});
/*
* From nsIMsgMessageService.idl:
* void SaveMessageToDisk(in string aMessageURI, in nsIFile aFile,
* in boolean aGenerateDummyEnvelope,
* in nsIUrlListener aUrlListener, out nsIURI aURL,
* in boolean canonicalLineEnding,
* in nsIMsgWindow aMsgWindow);
* Enforcing canonicalLineEnding (i.e., CRLF) makes sure that the
* test also runs successfully on platforms not using CRLF by default.
*/
// Enforcing canonicalLineEnding (i.e., CRLF) makes sure that the
// test also runs successfully on platforms not using CRLF by default.
let promiseUrlListener = new PromiseTestUtils.PromiseUrlListener();
gIMAPService.SaveMessageToDisk(
"imap-message://user@localhost/INBOX#" + (inbox.uidnext - 1),
gSavedMsgFile,
false,
UrlListener,
promiseUrlListener,
{},
true,
null
);
}
await promiseUrlListener.promise;
let msgFileContent = await IOUtils.readUTF8(gMsgFile.path);
let savedMsgFileContent = await IOUtils.readUTF8(gSavedMsgFile.path);
// File contents should not have been modified.
Assert.equal(msgFileContent, savedMsgFileContent);
// The file doesn't get closed straight away, but does after a little bit.
// So wait, and then remove it. We need to test this to ensure we don't
// indefinitely lock the file.
do_timeout(1000, endTest);
});
function endTest() {
gIMAPIncomingServer.closeCachedConnections();
@ -110,24 +110,5 @@ function endTest() {
do_test_finished();
}
var UrlListener = {
OnStartRunningUrl(url) {},
OnStopRunningUrl(url, rc) {
// operation succeeded
Assert.equal(rc, 0);
// File contents were not modified
Assert.equal(
IOUtils.loadFileToString(gMsgFile),
IOUtils.loadFileToString(gSavedMsgFile)
);
// The file doesn't get closed straight away, but does after a little bit.
// So wait, and then remove it. We need to test this to ensure we don't
// indefinitely lock the file.
do_timeout(1000, endTest);
},
};
// XXX IRVING we need a separate check somehow to make sure we store the correct
// content size for chunked messages where the server lied

Просмотреть файл

@ -2,19 +2,21 @@
* 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/. */
var { IOUtils } = ChromeUtils.import("resource:///modules/IOUtils.jsm");
var { PromiseTestUtils } = ChromeUtils.import(
"resource://testing-common/mailnews/PromiseTestUtils.jsm"
);
var MSG_LINEBREAK = "\r\n";
function run_test() {
add_task(async function run_the_test() {
localAccountUtils.loadLocalMailAccount();
test_parse_headers_without_crash("./data/mailformed_recipients.eml");
test_parse_headers_without_crash("./data/mailformed_subject.eml");
test_parse_headers_without_crash("./data/invalid_mozilla_keys.eml");
}
await test_parse_headers_without_crash("./data/mailformed_recipients.eml");
await test_parse_headers_without_crash("./data/mailformed_subject.eml");
await test_parse_headers_without_crash("./data/invalid_mozilla_keys.eml");
});
function test_parse_headers_without_crash(eml) {
async function test_parse_headers_without_crash(eml) {
let file = do_get_file(eml);
let parser = Cc["@mozilla.org/messenger/messagestateparser;1"].createInstance(
@ -24,7 +26,8 @@ function test_parse_headers_without_crash(eml) {
parser.SetMailDB(localAccountUtils.inboxFolder.getDatabaseWOReparse());
parser.state = Ci.nsIMsgParseMailMsgState.ParseHeadersState;
let mailData = IOUtils.loadFileToString(file);
let bytes = await IOUtils.read(file.path);
let mailData = new TextDecoder().decode(bytes);
let lines = mailData.split(MSG_LINEBREAK);
for (let line = 0; line < lines.length; line++) {
@ -33,4 +36,7 @@ function test_parse_headers_without_crash(eml) {
lines[line].length + 2
);
}
// Apparently getDatabaseWOReparse doesn't like being called too often
// in a row.
await PromiseTestUtils.promiseDelay(200);
}

Просмотреть файл

@ -1,8 +1,10 @@
/*
/**
* Test bug 460636 - Saving message in local folder as .EML removes starting dot in all lines, and ignores line if single dot only line.
*/
var { IOUtils } = ChromeUtils.import("resource:///modules/IOUtils.jsm");
var { PromiseTestUtils } = ChromeUtils.import(
"resource://testing-common/mailnews/PromiseTestUtils.jsm"
);
var MSG_LINEBREAK = "\r\n";
var dot = do_get_file("data/dot");
@ -22,7 +24,7 @@ function run_test() {
copyFileMessageInLocalFolder(dot, 0, "", null, save_message);
}
function save_message(aMessageHeaderKeys, aStatus) {
async function save_message(aMessageHeaderKeys, aStatus) {
let headerKeys = aMessageHeaderKeys;
Assert.notEqual(headerKeys, null);
@ -31,15 +33,22 @@ function save_message(aMessageHeaderKeys, aStatus) {
let messageService = Cc[
"@mozilla.org/messenger/messageservice;1?type=mailbox-message"
].getService(Ci.nsIMsgMessageService);
let promiseUrlListener = new PromiseTestUtils.PromiseUrlListener();
messageService.SaveMessageToDisk(
msgURI,
saveFile,
false,
UrlListener,
promiseUrlListener,
{},
true,
null
);
await promiseUrlListener.promise;
check_each_line(
await IOUtils.readUTF8(dot.path),
await IOUtils.readUTF8(saveFile.path)
);
do_test_finished();
}
function check_each_line(aExpectedLines, aActualLines) {
@ -53,18 +62,6 @@ function check_each_line(aExpectedLines, aActualLines) {
}
}
var UrlListener = {
OnStartRunningUrl(aUrl) {},
OnStopRunningUrl(aUrl, aExitCode) {
Assert.equal(aExitCode, 0);
check_each_line(
IOUtils.loadFileToString(dot),
IOUtils.loadFileToString(saveFile)
);
do_test_finished();
},
};
function teardown() {
if (saveFile.exists()) {
saveFile.remove(false);

Просмотреть файл

@ -9,7 +9,6 @@
const { localAccountUtils } = ChromeUtils.import(
"resource://testing-common/mailnews/LocalAccountUtils.jsm"
);
var { IOUtils } = ChromeUtils.import("resource:///modules/IOUtils.jsm");
var gTestFiles = ["../../../data/bug505221", "../../../data/bug513543"];
@ -26,19 +25,19 @@ var gUrlListener = {
localAccountUtils.loadLocalMailAccount();
function run_test() {
add_task(async function run_the_test() {
do_test_pending();
localAccountUtils.inboxFolder.QueryInterface(Ci.nsIMsgLocalMailFolder);
for (let fileName of gTestFiles) {
localAccountUtils.inboxFolder.addMessage(
IOUtils.loadFileToString(do_get_file(fileName))
await IOUtils.readUTF8(do_get_file(fileName).path)
);
}
gMessages = [
...localAccountUtils.inboxFolder.msgDatabase.EnumerateMessages(),
];
doNextTest();
}
});
function streamMsg(msgHdr) {
let msgURI = localAccountUtils.inboxFolder.getUriForMsg(msgHdr);

Просмотреть файл

@ -8,7 +8,6 @@
// HeaderParser methods are run correctly.
const { MimeParser } = ChromeUtils.import("resource:///modules/mimeParser.jsm");
var { IOUtils } = ChromeUtils.import("resource:///modules/IOUtils.jsm");
// Utility method to compare objects
function compare_objects(real, expected) {
@ -46,10 +45,12 @@ var file_cache = {};
/**
* Read a file into a string (all line endings become CRLF).
*/
function read_file(file, start, end) {
async function read_file(file, start, end) {
if (!(file in file_cache)) {
var realFile = do_get_file("../../../data/" + file);
file_cache[file] = IOUtils.loadFileToString(realFile).split(/\r\n|[\r\n]/);
file_cache[file] = (await IOUtils.readUTF8(realFile.path)).split(
/\r\n|[\r\n]/
);
}
var contents = file_cache[file];
if (start !== undefined) {
@ -76,12 +77,21 @@ function read_file(file, start, end) {
* accumulated body part data for partnum would be the contents
* of the file from [line start, line end) [1-based lines]
*/
function make_body_test(test, file, opts, partspec) {
var results = partspec.map(p => [p[0], read_file(file, p[1], p[2])]);
var msgcontents = read_file(file);
async function make_body_test(test, file, opts, partspec) {
let results = [];
for (let p of partspec) {
results.push([p[0], await read_file(file, p[1], p[2])]);
}
let msgcontents = await read_file(file);
return [test, msgcontents, opts, results];
}
async function make_bodydecode_test(test, file, opts, expected) {
let msgcontents = await read_file(file);
return [test, msgcontents, opts, expected];
}
// This is the expected part specifier for the multipart-complex1 test file,
// specified here because it is used in several cases.
var mpart_complex1 = [
@ -100,8 +110,8 @@ var mpart_complex1 = [
// either a {partnum: header object} (to check headers)
// or a [[partnum body], [partnum body], ...] (to check bodies)
// (the partnums refer to the expected part numbers of the MIME test)
// Note that for body tests, unless you're testing decoding, it is preferable to
// use make_body_test instead of writing the array yourself.
// For body tests, unless you're testing decoding, use make_body_test.
// For decoding tests, use make_bodydecode_test
var parser_tests = [
// Body tests from data
// (Note: line numbers are 1-based. Also, to capture trailing EOF, add 2 to
@ -124,9 +134,9 @@ var parser_tests = [
make_body_test("Raw body", "multipart1", { bodyformat: "raw" }, [
["", 4, 14],
]),
[
make_bodydecode_test(
"Base64 decode 1",
read_file("base64-1"),
"base64-1",
{ bodyformat: "decode" },
[
[
@ -136,11 +146,11 @@ var parser_tests = [
"'s even a CRLF at the end and one at the beginning, but the output" +
" shouldn't have it.\r\n",
],
],
],
[
]
),
make_bodydecode_test(
"Base64 decode 2",
read_file("base64-2"),
"base64-2",
{ bodyformat: "decode" },
[
[
@ -148,12 +158,12 @@ var parser_tests = [
"<html><body>This is base64 encoded HTML text, and the tags shouldn" +
"'t be stripped.\r\n<b>Bold text is bold!</b></body></html>\r\n",
],
],
],
]
),
make_body_test("Base64 nodecode", "base64-1", {}, [["", 4, 9]]),
[
make_bodydecode_test(
"QP decode",
read_file("bug505221"),
"bug505221",
{ pruneat: "1", bodyformat: "decode" },
[
[
@ -163,8 +173,8 @@ var parser_tests = [
'tml; charset=us-ascii">\r\n\r\n\r\n<META content="MSHTML 6.00.600' +
'0.16735" name=GENERATOR></HEAD>\r\n<BODY> bbb\r\n</BODY></HTML>',
],
],
],
]
),
// Comprehensive tests from the torture test
make_body_test("Torture regular body", "mime-torture", {}, [
@ -212,12 +222,12 @@ function test_parser(message, opts, results) {
var emitter = {
stack: [],
startMessage: function emitter_startMsg() {
Assert.equal(this.stack.length, 0);
Assert.equal(this.stack.length, 0, "no stack at start");
calls++;
this.partData = "";
},
endMessage: function emitter_endMsg() {
Assert.equal(this.stack.length, 0);
Assert.equal(this.stack.length, 0, "no stack at end");
calls++;
},
startPart: function emitter_startPart(partNum, headers) {
@ -294,8 +304,9 @@ function test_header(headerValue, flags, expected) {
compare_objects(result, expected[1]);
}
function run_test() {
add_task(async function testit() {
for (let test of parser_tests) {
test = await test;
dump("Testing message " + test[0]);
if (test[1] instanceof Array) {
dump(" using " + test[1].length + " packets");
@ -307,4 +318,4 @@ function run_test() {
dump("Testing value ->" + test[0] + "<- with flags " + test[1] + "\n");
test_header(test[0], test[1], test[2]);
}
}
});

Просмотреть файл

@ -14,10 +14,12 @@ var EXPORTED_SYMBOLS = [
];
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { IOUtils } = ChromeUtils.import("resource:///modules/IOUtils.jsm");
var { AuthPLAIN, AuthLOGIN, AuthCRAM } = ChromeUtils.import(
"resource://testing-common/mailnews/Auth.jsm"
);
var { mailTestUtils } = ChromeUtils.import(
"resource://testing-common/mailnews/MailTestUtils.jsm"
);
// Since we don't really need to worry about peristence, we can just
// use a UIDL counter.
@ -64,7 +66,7 @@ function readFile(fileName) {
throw new Error("Cannot find file named " + fileName);
}
return IOUtils.loadFileToString(file);
return mailTestUtils.loadFileToString(file);
}
function pop3Daemon(flags) {

Просмотреть файл

@ -13,7 +13,6 @@
*/
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { IOUtils } = ChromeUtils.import("resource:///modules/IOUtils.jsm");
// eslint-disable-next-line mozilla/reject-importGlobalProperties
Cu.importGlobalProperties(["Element", "Node"]);