株式会社クリアコード > フリーソフトウェア開発 > UxU - UnitTest.XUL > Helper methods for testcases

Helper methods for testcases UxU - UnitTest.XUL

Explanatory Note

<type of the returned value> <method name>(<argument>, [<optional argument>])

<descriptions.>

Action helpers

Mouse events

You can emulate operations with modifier keys, by specifying an object which has following properties:

Boolean altKey
Alt key is pressed or not (default:false)
Boolean ctrlKey
Ctrl key is pressed or not (default:false)
Boolean metaKey
Meta key (Command key on Mac OS X) is pressed or not (default:false)
Boolean shiftKey
Shift key is pressed or not (default:false)

Note: On Firefox 2 and Thudnerbird 2, click events fired by these methods never fire command event. This is a restriction of Gecko 1.8.

Mouse events on DOMElement

void action.clickOn([options]) alias: action.leftClickOn(), actionClickOn(), actionLeftClickOn()
void action.middleClickOn([options]) alias: actionMiddleClickOn()
void action.rightClickOn([options]) alias: actionRightClickOn()

Does left-click, middle-click, or right-click on the specified element.

action.clickOn($('button'));
action.clickOn($('button'), { ctrlKey : true, shiftKey : true });
// random order
action.middleClickOn({ shiftKey : true }, $('link'));
void action.dblclickOn([options]) alias: action.dblClickOn(), action.leftDblclickOn(), action.leftDblClickOn(), actionDblclickOn(), actionDblClickOn(), actionLeftDblclickOn(), actionLeftDblClickOn()
void action.middleDblclickOn([options]) alias: action.middleDblClickOn(), actionMiddleDblclickOn(), actionMiddleDblClickOn()
void action.rightDblclickOn([options]) alias: action.rightDblClickOn(), actionRightDblclickOn(), actionRightDblClickOn()

Does left-double-click, middle-double-click, or right-double-click on the specified element.

action.dblclickOn($('button'));
action.dblclickOn($('button'), { ctrlKey : true, shiftKey : true });
// random order
action.middleDblclickOn({ shiftKey : true }, $('link'));
void action.mousedownOn([options]) alias: action.dblClickOn(), action.leftMousedownOn(), action.leftMouseDownOn(), actionMousedownOn(), actionMouseDownOn(), actionLeftMousedownOn(), actionLeftMouseDownOn()
void action.middleMousedownOn([options]) alias: action.middleMouseDownOn(), actionMiddleMousedownOn(), actionMiddleMouseDownOn()
void action.rightMousedownOn([options]) alias: action.rightMouseDownOn(), actionRightMousedownOn(), actionRightMouseDownOn()

Presses down the left, the middle, or the right button on the specified element. This doesn't click, but only presses the button.

action.mousedownOn($('button'));
action.mousedownOn($('button'), { ctrlKey : true, shiftKey : true });
// random order
action.middleMousedownOn({ shiftKey : true }, $('link'));
void action.mouseupOn([options]) alias: action.dblClickOn(), action.leftMouseupOn(), action.leftMouseUpOn(), actionMouseupOn(), actionMouseUpOn(), actionLeftMouseupOn(), actionLeftMouseUpOn()
void action.middleMouseupOn([options]) alias: action.middleMouseUpOn(), actionMiddleMouseupOn(), actionMiddleMouseUpOn()
void action.rightMouseupOn([options]) alias: action.rightMouseUpOn(), actionRightMouseupOn(), actionRightMouseUpOn()

Releases the left, the middle, or the right button on the specified element. If you call this method for same button specified to action.mousedownOn(), "click" event will fire.

action.mouseupOn($('button'));
action.mouseupOn($('button'), { ctrlKey : true, shiftKey : true });
// random order
action.middleMouseupOn({ shiftKey : true }, $('link'));

Mouse events at specified position

These methods require two numbers as the position; X and Y. The position 0, 0 is the top-left edge of the screen. If you specify an DOMWindow object as an extra argument, then 0, 0 means the top-left edge of the frame (DOMWindow).

void action.clickAt([options]) alias: action.leftClickAt(), actionClickAt(), actionLeftClickAt()
void action.middleClickAt([options]) alias: actionMiddleClickAt()
void action.rightClickAt([options]) alias: actionRightClickAt()

Does left-click, middle-click, or right-click at the specified position.

action.clickAt(300, 250);
action.clickAt(content, 20, 5, { ctrlKey : true, shiftKey : true });
// random order
action.middleClickAt({ shiftKey : true }, 100, 100, content.frames[2]);
void action.dblclickAt([options]) alias: action.dblClickAt(), action.leftDblclickAt(), action.leftDblClickAt(), actionDblclickAt(), actionDblClickAt(), actionLeftDblclickAt(), actionLeftDblClickAt()
void action.middleDblclickAt([options]) alias: action.middleDblClickAt(), actionMiddleDblclickAt(), actionMiddleDblClickAt()
void action.rightDblclickAt([options]) alias: action.rightDblClickAt(), actionRightDblclickAt(), actionRightDblClickAt()

Does left-double-click, middle-double-click, or right-double-click at the specified position.

action.dblclickAt(300, 250);
action.dblclickAt(content, 20, 5, { ctrlKey : true, shiftKey : true });
// random order
action.middleDblclickAt({ shiftKey : true }, 100, 100, content.frames[2]);
void action.mousedownAt([options]) alias: action.mouseDownAt(), action.leftMousedownAt(), action.leftMouseDownAt(), actionMousedownAt(), actionMouseDownAt(), actionLeftMousedownAt(), actionLeftMouseDownAt()
void action.middleMousedownAt([options]) alias: action.middleMouseDownAt(), actionMiddleMousedownAt(), actionMiddleMouseDownAt()
void action.rightMousedownAt([options]) alias: action.rightMouseDownAt(), actionRightMousedownAt(), actionRightMouseDownAt()

Presses down the left, the middle, or the right button at the specified position. This doesn't click, but only presses the button.

action.mousedownAt(300, 250);
action.mousedownAt(content, 20, 5, { ctrlKey : true, shiftKey : true });
// random order
action.middleMousedownAt({ shiftKey : true }, 100, 100, content.frames[2]);
void action.mouseupAt([options]) alias: action.mouseUpAt(), action.leftMouseupAt(), action.leftMouseUpAt(), actionMouseupAt(), actionMouseUpAt(), actionLeftMouseupAt(), actionLeftMouseUpAt()
void action.middleMouseupAt([options]) alias: action.middleMouseUpAt(), actionMiddleMouseupAt(), actionMiddleMouseUpAt()
void action.rightMouseupAt([options]) alias: action.rightMouseUpAt(), actionRightMouseupAt(), actionRightMouseUpAt()

Releases the left, the middle, or the right button at the specified position. If you call this method for same button specified to action.mousedownAt(), "click" event will fire.

action.mouseupAt(300, 250);
action.mouseupAt(content, 20, 5, { ctrlKey : true, shiftKey : true });
// random order
action.middleMouseupAt({ shiftKey : true }, 100, 100, content.frames[2]);

Keyboard events

You can emulate operations with modifier keys, by specifying an object which has following properties:

Boolean altKey
Alt key is pressed or not (default:false)
Boolean ctrlKey
Ctrl key is pressed or not (default:false)
Boolean metaKey
Meta key (Command key on Mac OS X) is pressed or not (default:false)
Boolean shiftKey
Shift key is pressed or not (default:false)

Note: On Firefox 2 and Thudnerbird 2, keyboard events fired by these methods never fire command event. This is a restriction of Gecko 1.8.

General keyboard operations

void action.keypressOn([options]) alias: action.keyPressOn(), actionKeypressOn(), actionKeyPressOn()

Presses and releases the specified key, on the specified element.

If you specify only one character, then the key in the keyboard will be pressed. Moreover, function keys and other special keys can be specified by its key code defined as constant properties of Components.interfaces.nsIDOMKeyEvent (e.g. DOM_VK_RETURN), or a string of the key code name (case insensitive).

// Ctrl-A
action.keypressOn($('input'), 'a', { ctrlKey : true });

// input "FooBar", and delete "Bar"
action.keypressOn($('input'), 'f', { shiftKey : true });
action.keypressOn($('input'), 'o');
action.keypressOn($('input'), 'o');
action.keypressOn($('input'), 'b', { shiftKey : true });
action.keypressOn($('input'), 'a');
action.keypressOn($('input'), 'r');
action.keypressOn($('input'), Ci.nsIDOMKeyEvent.DOM_VK_BACK_SPACE);
action.keypressOn($('input'), Ci.nsIDOMKeyEvent.DOM_VK_BACK_SPACE);
action.keypressOn($('input'), Ci.nsIDOMKeyEvent.DOM_VK_BACK_SPACE);

// random order
action.keypressOn('F3', { shiftKey : true }, $('searchbar'));
void action.keydownOn([options]) alias: action.keyDownOn(), actionKeydownOn(), actionKeyDownOn()

Presses down the specified key, on the specified element. This doesn't releases the key, but only presses. This never repeats key-inputs like a real keyboard.

If you specify only one character, then the key in the keyboard will be pressed. Moreover, function keys and other special keys can be specified by its key code defined as constant properties of Components.interfaces.nsIDOMKeyEvent (e.g. DOM_VK_RETURN), or a string of the key code name (case insensitive).

// Ctrl-Tab
action.keydownOn($('tabbrowser'), 'Control');
action.keypressOn($('tabbrowser'), 'Tab', { ctrlKey : true });
action.keypressOn($('tabbrowser'), 'Tab', { ctrlKey : true });
action.keyupOn($('tabbrowser'), 'Control');

// random order
action.keydownOn(Ci.nsIDOMKeyEvent.DOM_VK_TAB, $('field'), { shiftKey : true });
void action.keyupOn([options]) alias: action.keyUpOn(), actionKeyupOn(), actionKeyUpOn()

Releases the specified key, on the specified element. If you call this method for the same key specified to action.keydownOn(), then a keypress even will fire.

If you specify only one character, then the key in the keyboard will be released. Moreover, function keys and other special keys can be specified by its key code defined as constant properties of Components.interfaces.nsIDOMKeyEvent (e.g. DOM_VK_RETURN), or a string of the key code name (case insensitive).

// Ctrl-Tab
action.keydownOn($('tabbrowser'), 'Control');
action.keypressOn($('tabbrowser'), 'Tab', { ctrlKey : true });
action.keypressOn($('tabbrowser'), 'Tab', { ctrlKey : true });
action.keyupOn($('tabbrowser'), 'Control');

// random order
action.keyupOn(Ci.nsIDOMKeyEvent.DOM_VK_TAB, $('field'), { shiftKey : true });

Input opereations by keyboard

void action.inputTo([options]) alias: actionInputTo()

Inputs the specified text to the input field. keydown, keyup, keypress and input are fired for each character. For non-ASCII characters like kanji, this doesn't fire key events and fires only input events like input operations via IME.

This clears existing text in the field. action.appendTo() keeps the old text.

action.inputTo($('yomigana'), 'Sakamoto Ryoma');
action.inputTo($('kanji'), '坂本龍馬');
// random order
action.inputTo('31', $('age'));
void action.appendTo([options]) alias: actionAppendTo()

Inputs the specified text to the input field. keydown, keyup, keypress and input are fired for each character. For non-ASCII characters like kanji, this doesn't fire key events and fires only input events like input operations via IME.

This keeps existing text in the field and append the specified text to it. action.inputTo() clears the old text automatically.

action.appendTo($('comment'), 'My name is');
action.appendTo($('comment'), ' Sakamoto, Ryoma.');
// random order
action.appendTo(' Nice to meet you!', $('comment'));
void action.pasteTo([options]) alias: actionPasteTo()

Sets the specified text to the input field. Like a copy-and-paste, this fires only one input event.

This clears existing text in the field. action.additionallyPasteTo() keeps the old text.

action.pasteTo($('yomigana'), 'Sakamoto Ryoma');
action.pasteTo($('kanji'), '坂本龍馬');
// random order
action.pasteTo('31', $('age'));
void action.additionallyPasteTo([options]) alias: actionAdditionallyPasteTo()

Sets the specified text to the input field. Like a copy-and-paste, this fires only one input event.

This keeps existing text in the field and append the specified text to it. action.pasteTo() clears the old text automatically.

action.additionallyPasteTo($('comment'), 'My name is');
action.additionallyPasteTo($('comment'), ' Sakamoto, Ryoma.');
// random order
action.additionallyPasteTo(' Nice to meet you!', $('comment'));

Getting something from a position

DOMWindow action.getFrameFromScreenPoint(in Number aScreenX, in Number aScreenY) alias: action.getWindowFromScreenPoint(), actionGetFrameFromScreenPoint(), actionGetWindowFromScreenPoint()
DOMWindow action.getFrameFromScreenPoint(in DOMWindow aWindow, in Number aScreenX, in Number aScreenY)

Returns the Window object of the frame at the specified screen position. When there is no frame, null will be returned.

This finds frames from the most front window. If you want to find a frame from an behind windows, then specify the parent frame or the window includes the frame you want to get.

Note: Even if you specify parent frame to this method, (0, 0) still means the top-left edge of the screen.

var frame = action.getWindowFromScreenPoint(500, 200);
assert.isNotNull(frame);
assert.equals($('sidebar', topWindow).contentWindow, frame);

var frame2 = action.getWindowFromScreenPoint(bottomWindow, 500, 200);
DOMElement action.getElementFromScreenPoint(in Number aScreenX, in Number aScreenY) alias: actionGetElementFromScreenPoint()
DOMElement action.getElementFromScreenPoint(in DOMWindow aWindow, in Number aScreenX, in Number aScreenY)

Returns the element node at the specified screen position. When there is no element, null will be returned.

This finds elements from the most front window. If you want to find an element from an behind windows, then specify the parent frame or the window includes the element you want to get.

Note: Even if you specify parent frame to this method, (0, 0) still means the top-left edge of the screen.

var element = action.getElementFromScreenPoint(240, 10);
assert.equals($('accept-button', topWindow), element);

var element2 = action.getElementFromScreenPoint(bottomWindow, 240, 10);

Obsolete API

For backward compatibility, old APIs are still available.

void action.fireMouseEvent(in DOMWindow aWindow, [in Object aOptions]) alias: actionFireMouseEvent()

Dispatches mouse event to the window. Event details are specified by a hash which have following parameters:

String type
Event type (click, dblclick, mousedown or mouseup. default:click)
Number button
Clicked button (default:0=left button
Number detail
Click count (default:1)
Number screenX
Clicked X (left) position on the screen (default:0)
Number screenY
Clicked Y (top) position on the screen (default:0)
Number x
Clicked X (left) position in the frame (default:0)
Number y
Clicked Y (yop) position in the frame (default:0)
Boolean altKey
Alt key is pressed or not (default:false)
Boolean ctrlKey
Ctrl key is pressed or not (default:false)
Boolean metaKey
Meta key (Command key on Mac OS X) is pressed or not (default:false)
Boolean shiftKey
Shift key is pressed or not (default:false)

If you specify no option, then this works as "Single left click on (0, 0)". If there is no element on the position, this fires no event.

function testDblClickOnTarget() {
  action.fireMouseEvent(content, { type    : 'dblclick',
                                   screenX : 120,
                                   screenY : 250,
                                   ctrlKey : true });
}

On Firefox 2 and Thudnerbird 2, click events fired by this method never fire command event. This is a restriction of Gecko 1.8.

void action.fireMouseEventOnElement(in DOMElement aElement, [in Object aOptions]) alias: actionFireMouseEventOnElement()

Dispatches mouse event on the center of the specified element. You can specify options same as action.fireMouseEvent()'s.

action.fireMouseEventOnElement($('button'),
                               { type    : 'dblclick',
                                 ctrlKey : true });

On Firefox 2 and Thudnerbird 2, click events fired by this method never fire command event. This is a restriction of Gecko 1.8.

void action.fireKeyEventOnElement(in DOMElement aElement, [in Object aOptions]) alias: actionFireKeyEventOnElement()

Dispatches keyboard event on the specified element. Event details are specified by a hash which have following parameters:

String type
Event type (keydown, keyup, or keypress. default:keypress)
Number keyCode
Key code of the pressed key. (default:0)
Number charCode
Character code of the pressed key. (default:0)
Boolean altKey
Alt key is pressed or not (default:false)
Boolean ctrlKey
Ctrl key is pressed or not (default:false)
Boolean metaKey
Meta key (Command key on Mac OS X) is pressed or not (default:false)
Boolean shiftKey
Shift key is pressed or not (default:false)

You can specify key codes by constant properties of Components.interfaces.nsIDOMKeyEvent, like DOM_VK_RETURN.

action.fireKeyEventOnElement($('button'),
                             { keyCode : Ci.nsIDOMKeyEvent.DOM_VK_ENTER,
                               ctrlKey : true });

On Firefox 2 and Thudnerbird 2, key events fired by this method never fire command event. This is a restriction of Gecko 1.8.

Boolean action.fireXULCommandEvent(in DOMWindow aWindow, [in Object aOptions]) alias: actionFireXULCommandEvent()

Dispatches command event caused by click events, to the specified window. You can specify options same as action.fireMouseEvent()'s. This does nothing if the XUL element on the specified position cannot fire command event (unclickable elements like "label", disabled elements, etc.) This returns true if command event is successfully fired. If not, returns false.

action.fireXULCommandEvent(testWindow,
                           { screenX : buttonInTestWindow.boxObject.screenX+5,
                             screenY : buttonInTestWindow.boxObject.screenY+5 });

This doesn't work on Firefox 2 and Thudnerbird 2. This is a restriction of Gecko 1.8.

Boolean action.fireXULCommandEventOnElement(in DOMElement aElement, [in Object aOptions]) alias: actionFireXULCommandEventOnElement()

Dispatches command event caused by click events, to the center of the specified element. You can specify options same as action.fireMouseEvent()'s. This does nothing if the specified element cannot fire command event (unclickable elements like "label", disabled elements, etc.) This returns true if command event is successfully fired. If not, returns false.

action.fireXULCommandEventOnElement($('toolbarbutton', testWindow));

This doesn't work on Firefox 2 and Thudnerbird 2. This is a restriction of Gecko 1.8.

void action.inputTextToField(in DOMElement aElement, in String aValue, [in Boolean aAppend], [in Boolean aDontFireKeyEvents]) alias: actionInputTextToField()

Emulates text input operation for the specified text field. keydown, keyup, keypress and input are fired for each character. For non-ASCII characters like kanji, this doesn't fire key events and fires only input events like input operations via IME.

This clears the old value in the field before doing new input, by default. If you specify true as the third argument, this doesn't clear the old value and appends new input to the existing one.

If you specify true as the fourth argument, key evenrs are never fired like copy-and-paste. This is same to the old behavior on Ver.0.2.8 or older.

action.inputTextToField($('input'), 'message foobar');
action.inputTextToField($('input'), ' and more...', true);

Location of the testcase

String fileURL alias: utils.fileURL

Returns the URL of the current testcase.

var data = utils.readCSV(fileURL+'.data.csv');
String baseURL alias: utils.baseURL

Returns the URL of the folder which the current testcase exists in.

utils.include(baseURL+'common.inc.js');
utils.include(baseURL+'../content/myadoon/myModule.js');

Window helpers

Object utils.setUpTestWindow([in Object aOptions]) alias: setUpTestWindow()

Sets up a Firefox (or Thunderbird) window for testing. This opens new Firefox (or Thunderbird) window if it is not opened yet, and returns an waiting object for deferred operations.

// Wait that the testing window is completely loaded.
// After that, go forward.
function setUp() {
  utils.wait(utils.setUpTestWindow());
  var win = utils.getTestWindow();
  assert.isTrue(win.MyAddonService.initialized);
}

You can specify window size, position, and other options for the newly opened window.

void utils.tearDownTestWindow([in Object aOptions]) alias: utils.closeTestWindow(), closeTestWindow(), tearDownTestWindow()

Closes the testing window opened by utils.setUpTestWindow(). If there is no testing window, this does nothing.

function tearDown() {
  utils.tearDownTestWindow();
}

You can specify which window have to be closed, by options.

DOMWindow utils.getTestWindow([in Object aOptions]) alias: getTestWindow()

Returns the testing window opened by utils.setUpTestWindow(). If there is no testing window, this returns null.

var win = utils.getTestWindow();
assert.isDefined(win.MyAddonService);

You can specify which window have to be gotten by options.

DOMWindow Array utils.getChromeWindows([in Object aOptions]) alias: getChromeWindows()

Returns an array of existing XUL (chrome) windows' DOMWindow.

var addonManager = utils.getChromeWindows({
      type : 'Extension:Manager'
    });
addonManager = addonManager[0];

You can specify what type or the URI to collect.

Options for windows

You can specify detailed information to open/close/get windows. Options are specified by a hash and all options are just optional. If both of uri and type are not specified, or no option is specified, then UxU guesses that the main window (browser window of Firefox, 3-pane window of Thunderbird) is specified.

var options = {
  uri       : 'chrome://browser/content/browser.xul', // default: auto detect
  type      : 'navigator:browser',                    // default: null
  name      : '_blank',                               // default: _blank
  flags     : 'chrome,all,dialog=no',                 // default: chrome,all
  arguments : ['http://...', 'http://...'],           // default: blank array
  width     : 200,
  height    : 400,
  screenX   : 100,
  screenY   : 100
};

DOM Helpers

DOMNode $(in nsIVariant aNodeOrIdString, [in nsIVariant aOwner]) alias: utils.$()

Provides features like $() of some JavaScript libraries, prototype.js, etc. For example:

  • When a DOMNode is handed, this returns it as is.
  • When a string is hahded, then returns the result of DOMDocument.getElementById().
    • When you don't specify the 2nd argument, returns the result of contentDocument.getElementById().
    • When aOwner is a DOMDocument object, returns the result of aOwner.getElementById().
    • When aOwner is a DOMWindow object, returns the result of aOwner.document.getElementById().
    • When aOwner is a DOMNode object, returns the result of aOwner.ownerDocument.getElementById().
var button = $('button');
var toolbar = $('navigator-toolbox', utils.getTestWindow());
nsIVariant $X(arguments) alias: utils.$X()

Provides a feature like syntax sugar for DOM3 XPath. For example:

nsIVariant $X(in String aExpression)
Returns a boolean, a number, a string, or a DOMNode value based on the result of contentDocument.evaluate(aExpression, contentDocument, null, XPathResult.ANY_TYPE, null).
nsIVariant $X(in String aExpression, in DOMNode aContext)
Returns a boolean, a number, a string, or a DOMNode value based on the result of (aContext.ownerDocument || aContext).evaluate(aExpression, aContext, null, XPathResult.ANY_TYPE, null).
nsIVariant $X(in String aExpression, in DOMNode aContext, in Number aResultType)
Returns a boolean, a number, a string, a DOMNode, or an array of DOMNodes based on the result of (aContext.ownerDocument || aContext).evaluate(aExpression, aContext, null, aResultType, null).
nsIVariant $X(in String aExpression, in DOMNode aContext, in DOMXPathNSResolver aNSResolver, in Number aResultType)
Returns a boolean, a number, a string, a DOMNode, or an array of DOMNodes based on the result of (aContext.ownerDocument || aContext).evaluate(aExpression, aContext, aNSResolver, aResultType, null).
var disabledItems = $X(
      '/descendant::*[local-name()="menuitem" and @disabled="true"]',
      utils.getTestWindow()
    );
disabledItems.forEach(function(aItem) {
  assert.isTrue(aItem.disabled);
});

Browser helpers

These features are available only on Firefox.

DOMWindow content alias: contentWindow, utils.content, utils.contentWindow

Returns the content area of the testing Firefox window opened by utils.setUpTestWindow(), as a DOMWindow object. If there is no testing window, this returns the testing frame in the test runner window.

assert.equals('selected', content.getSelection());
content.close();
DOMDocument contentDocument alias: utils.contentDocument

Returns the document object of the content area in the testing Firefox window opened by utils.setUpTestWindow(), as a DOMDocument. If there is no testing window, this returns the document of the testing frame in the test runner window.

assert.equals('UxU - UnitTest.XUL',
              contentDocument.title);
assert.contains('password', contentDocument.cookie);
DOMElement gBrowser alias: utils.gBrowser

Returns the gBrowser object (<tabbrowser/> element) in the testing Firefox window opened by utils.setUpTestWindow(), as a DOMElement. If there is no testing window, this returns the <browser/> element in the test runner window.

assert.equals('www.example.com', gBrowser.currentURI.host);
assert.equals('tabbrowser', gBrowser.localName);
DOMElement utils.getBrowser() alias: getBrowser()

Same to gBrowser.

assert.equals('www.example.com', utils.getBrowser().currentURI.host);
assert.equals('tabbrowser', utils.getBrowser().localName);
DOMElement Array utils.getTabs() alias: getTabs()

Returns an array of existing tabs in the testing Firefox window opened by utils.setUpTestWindow(), as an array of DOMElement. If there is no testing window, this returns a blank array.

assert.equals(3, utils.getTabs().length);
assert.equals('true', utils.getTabs()[1].getAttribute('selected'));
Object utils.loadURI(in String aURI, [in Object aOptions]) alias: loadURI()

Loads the specified URI into the current tab of the testing Firefox window opened by utils.setUpTestWindow(). If there is no testing window, this loads the URI into the testing frame in the test runner window. This returns an waiting object for deferred operations.

// Wait that the page is completely loaded
utils.wait(utils.loadURI('http://www.clear-code.com/'));
var win = utils.getTestWindow();
assert.equals('http://www.clear-code.com/', win.content.location.href);

You can specify the referrer URI.

utils.wait(utils.loadURI('http://www.clear-code.com/',
                    { referrer: 'http://www.clear-code.com/about.html' }));
Object utils.addTab(in String aURI, [in Object aOptions]) alias: addTab()

Opens new tab in the testing Firefox window opened by utils.setUpTestWindow(), and loads the specified URI into the new tab. If there is no testing window, this returns null. Otherwise, this returns an waiting object for deferred operations. Moreover, after that the tab is completely loaded, you can access the newly opened tab via the tab property of the waiting object.

// Open, and wait
var win = utils.getTestWindow();
var obj = utils.addTab('http://www.clear-code.com/');
utils.wait(obj);
assert.equals('ClearCode Inc.', obj.tab.getAttribute('label'));

You can specify the referrer URI.

utils.wait(utils.addTab('http://www.clear-code.com/',
                   { referrer: 'http://www.clear-code.com/about.html' }));

If you put relative pathes to utils.loadURI() or utils.addTab(), then, they are resolved based on the place of the testcase file. It just same to baseURL + '<relative path>'.

Mail operation helpers

These features are available only on Thunderbird.

Folder Helpers

nsIMsgFolder mail.getFolderByURI(in String aURI)

Returns a message folder from URI strings like mailbox://nobody@Local%20Folders/....

nsIMsgFolder mail.localFolder

Returns the root folder of the local folder account.

void mail.deleteFolder(in nsIMsgFolder aFolder)

Deletes the specified folder. This doesn't move the folder into the Trash folder, just deletes the folder and all of messagees in it.

void mail.deleteFolderByURI(in String aURI)

Deletes the folder specified by URI strings like mailbox://nobody@Local%20Folders/.... This doesn't move the folder into the Trash folder, just deletes the folder and all of messagees in it.

Compose Helpers

DOMWindow mail.compose.window

Returns the topmost window of existing message composition windows.

Object mail.compose.setUp()

Opens new message composition window, and returns an waiting object for deferred operations. If there is no main window, this opens the main window too.

void mail.compose.tearDown()

Closes the topmost message composition window opened by mail.compose.setUp(). If the main window was opened by mail.compose.setUp(), and all of composition windows are closed, then the main window is closed too.

Object Array mail.compose.recipients

Returns an array of object which have following properties, from all of recipients in the message composition window (mail.compose.window)

String type
Selected type (to, cc, bcc, reply-to, followup-to or newsgroups)
String address
E-mail address
mail.compose.recipients = Object Array

Inputs E-mail addresses specified as an array, to the message composition window (mail.compose.window). When you set new value to this property, all of old recipients are cleared.

You can set an array of objects which have both type and address properties, or an array of E-mail address strings. If you set an array of strings, then they become "To:" addesses.

String mail.compose.subject

Returns the contents of the subject field from the message composition window (mail.compose.window).

mail.compose.subject = String

Sets the specified string to the subject field in the message composition window (mail.compose.window). This clears the old subject.

DOMElement mail.compose.body

Returns the document body from the message composition window (mail.compose.window), as a DOMElement object. Event if the message is plain-text type, this always returns DOMElement.

mail.compose.body = contents

Sets specified contents as the body of the message composition window (mail.compose.window). This clears the old contents.

You can specify contents as a string, a DOMNode, or a DOMDocumentFragment. Otherwise, it is converted to a string.

nsIFile Array mail.compose.attachments

Returns attached files an array of nsIFile objects, from the message composition window (mail.compose.window).

mail.compose.attachments = Object Array

Sets the specified array of files as attachments of the message composition window (mail.compose.window). You can specify files as an array of strings of local file path, strings of File URL, or nsIFile objects. Old attachments are always cleared.

Send Helpers

void mail.compose.send(in Boolean aAsync, [in DOMWindow aComposeWindow])

Sends the message which is edited by the message composition window (mail.compose.window). However, this doesn't send the message to the SMTP server. This only simulates the sending processes, and stores result objects of sent messages to mail.deliveries.

Object Array mail.deliveries

Returns an array of messages sent by mail.compose.send(). Each message have following properties:

  • String from
  • String replyTo
  • String to
  • String cc
  • String bcc
  • String subject
  • String organization
  • String priority
  • String messageId
  • String characterSet
  • String body
  • String newsgroups
  • String newshost
  • String newspostUrl
  • String followupTo

File helpers

File I/O

String utils.readFrom(in Object aFile, [in String aEncoding]) alias: readFrom()

Returns the contents of the specified file, as a string. You can specify file as a native file path, a file URL, a nsIFileURL object, or a nsIFile object.

You can specify the encoding of the contents as the 2nd argument. When you don't specify the encoding, this reads and returns the contents as is. If you want to read a text file encoded in UTF-8, then do utils.readFrom(file, "UTF-8").

var contents = utils.readFrom('../../fixtures/data.txt', 'Shift_JIS');
nsIFile utils.writeTo(in String aContent, in Object aFile, [in String aEncoding]) alias: writeTo()

Writes the specified string to the specified file. You can specify output file as a native file path, a file URL, a nsIFileURL object, or a nsIFile object as the 2nd argument.

You can specify the encoding of the contents as the 3rd argument. When you don't specify the encoding, this outputs the string (internally encoded in UCS-2) to the file as is. If you want to write a text file encoded in UTF-8, then do utils.writeTo(content, file, "UTF-8").

This overwrites the existing file without confirming.

utils.writeTo(result.join('\n'), 'tmp/data.txt', 'Shift_JIS');

If you put relative pathes to these methods, then, they are resolved based on the place of the testcase file. It just same to baseURL + '<relative path>'.

File creation, copying, and removing

nsIFile utils.cosmeticClone(in Object aOriginalFile, in Object aDestinationFolder, [in String aName]) alias: cosmeticClone()

Clones the original file (1st argument), into the destination folder (2nd argument), as the specified name (3rd argument). If you don't specify the 3rd argument, cloned files will have the name same to the original.

If you specify a folder as the original file, whole contents excluding hidden files (files with "hidden" attribute on Windows, files which have name starting with "." on Linux) will be cloned.

This returns the cloned file or folder which is in the destination folder.

utils.cosmeticClone('./logs', logDir, Date.now());
nsIFile utils.makeTempFile([in Object aOriginalFile]) alias: utils.createTempFile(), makeTempFile(), createTempFile()

Creates a new file in the system temporary folder, and returns it. If you specify a native file path, a file URL, or a nsIFile object, then the created temporary file will be a clone of the specified original file. If an folder is specified as the 1st argument, then this works as an alias of utils.makeTempFolder().

var newTempFile = utils.makeTempFile();
var cloned = utils.makeTempFile('../fixtures/file.txt');
nsIFile utils.makeTempFolder([in Object aOriginalFolder], [in Boolean aCosmetic]) alias: utils.makeTempDirectory(), utils.makeTempDir(), utils.createTempFolder(), utils.createTempDirectory(), utils.createTempDir(), makeTempFolder(), makeTempDirectory(), makeTempDir(), createTempFolder(), createTempDirectory(), createTempDir()

Creates a new folder in the system temporary folder, and returns it. If you specify a native file path, a file URL, or a nsIFile object, then the created folder will be a clone of the specified original folder. Hidden files (files with "hidden" attribute on Windows, files which have name starting with "." on Linux) are not cloned if you specify true as the 2nd argument.

var newTempFolder = utils.makeTempFolder();
var cloned = utils.makeTempFolder('../fixtures', true);
void utils.cleanUpTempFiles() alias: cleanUpTempFiles()

Deletes all of temporary files created by utils.makeTempFile() or utils.makeTempFolder() in the testcase. However, files locked by someone will stay there.

function tearDown() {
  utils.cleanUpTempFiles();
}
void utils.scheduleToRemove(in Object aFile) alias: scheduleToRemove()

Deletes the specified file. Instead of remove() method of nsIFile, this tries to delete the file after a delay, and retries if the operation fails.

utils.scheduleToRemove('temp/tempFile.zip');

If you put relative pathes to these methods, then, they are resolved based on the place of the testcase file. It just same to baseURL + '<relative path>'.

Conversion of file URL and file path

nsIFile utils.normalizeToFile(in Object aFile) alias: normalizeToFile()

Returns nsIFile object from a native file path string, a file URL, a nsIFileURL object, or a nsIFile obejct. If you put relative pathes to this method, then, they are resolved based on the place of the testcase file. It just same to baseURL + '<relative path>'.

var file1 = utils.normalizeToFile('c:\\file.txt');
var file2 = utils.normalizeToFile(baseURL+'/file.txt');
nsIFile utils.makeFileWithPath(in String aFilePath) alias: utils.getFileFromPath(), makeFileWithPath(), getFileFromPath()

Returns nsIFile object from a native file path on the platform.

var file = utils.makeFileWithPath('d:\\test\\file.txt');
nsIFile utils.getFileFromURL(in nsIFile aFileURL) alias: getFileFromURL()

Returns nsIFile object from a nsIFileURL object.

var file = utils.getFileFromURL(gBrowser.currentURI);
nsIFile utils.getFileFromURLSpec(in String aFileURLSpec) alias: getFileFromURLSpec()

Returns nsIFile object from a file URL string.

var file = utils.getFileFromURLSpec(gBrowser.currentURI.spec);
nsIFile utils.getFileFromKeyword(in String aKeyword) alias: getFileFromKeyword()

Returns nsIFile object from a keyword. Lists of available keywords are nsDirectoryServiceDefs.h, nsXULAppAPI.h, and others.

var extensions = utils.getFileFromKeyword('ProfD');
extensions.append('extensions');
String utils.getFilePathFromURL(in nsIFileURL aFileURL) alias: getFilePathFromURL()

Returns a native file path from a nsIFileURL object.

var path = utils.getFilePathFromURL(gBrowser.currentURI);
String utils.getFilePathFromURLSpec(in String aFileURLSpec) alias: getFilePathFromURLSpec()

Returns a native file path from a file URL string.

var path = utils.getFilePathFromURL(gBrowser.currentURI.spec);
String utils.getFilePathFromKeyword(in String aKeyword) alias: getFilePathFromKeyword()

Returns a native file path from a keyword. Lists of available keywords are nsDirectoryServiceDefs.h, nsXULAppAPI.h, and others.

var path = utils.getFilePathFromKeyword('ProfD');
nsIURI utils.getURLFromFile(in nsIFile aFile) alias: getURLFromFile()

Returns a nsIFileURL object from a nsIFile object.

var parentURL = utils.getURLFromFile(profile.parent);
nsIURI utils.getURLFromFilePath(in String aFilePath) alias: getURLFromFilePath()

Returns a nsIFileURL object from a native file path on the platform.

var fileURL = utils.getURLFromFilePath('d:\\test\\file.txt');
String utils.getURLSpecFromFile(in nsIFile aFileURL) alias: getURLSpecFromFile()

Returns a file URL string from a nsIFile object.

image.src = utils.getURLSpecFromFile(imageFile);
String utils.getURLSpecFromFilePath(in String aFileURL) alias: getURLSpecFromFilePath()

Returns a file URL string from a native file path on the platform.

image.src = utils.getURLSpecFromFilePath('d:\\test\\image.jpg');

Compute hash of file contents

String utils.computeHashFromFile(in Object aFile, in String aAlgorithm) alias: computeHash()

Computes the hash and returns hash string, from a file specified as the 1st argument, by the algorithm specified as the 2nd argument. Available hash algorithms are: md2, md5, sha1, sha256, sha384, and sha512.

assert.equals('7BD6E50A060F9D63CDD89082CC215025A800333E',
              utils.computeHashFromFile('../result.jpg', 'sha1'));
String utils.md2FromFile(in Object aFile) alias: md2FromFile()

Computes and returns the MD2 hash string from the specified file. Just same to utils.computeHashFromFile(aString, 'md2').

String utils.md5FromFile(in Object aFile) alias: md5FromFile()

Computes and returns the MD5 hash string from the specified file. Just same to utils.computeHashFromFile(aString, 'md5').

String utils.sha1FromFile(in Object aFile) alias: sha1FromFile()

Computes and returns the SHA-1 hash string from the specified file. Just same to utils.computeHashFromFile(aString, 'sha1').

String utils.sha256FromFile(in Object aFile) alias: sha256FromFile()

Computes and returns the SHA-256 hash string from the specified file. Just same to utils.computeHashFromFile(aString, 'sha256').

String utils.sha384FromFile(in Object aFile) alias: sha384FromFile()

Computes and returns the SHA-384 hash string from the specified file. Just same to utils.computeHashFromFile(aString, 'sha384').

String utils.sha512FromFile(in Object aFile) alias: sha512FromFile()

Computes and returns the SHA-512 hash string from the specified file. Just same to utils.computeHashFromFile(aString, 'sha512').

If you put relative pathes to utils.computeHashFromFile(), then, they are resolved based on the place of the testcase file. It just same to baseURL + '<relative path>'.

String operation helpers

String utils.UTF8ToUCS2(in String aInput) alias: utils.UTF8ToUnicode(), UTF8ToUCS2(), UTF8ToUnicode()

Returns a UCS-2 (Unicode) string from an UTF-8 string.

var string = utils.UTF8ToUCS2(someXPCOMComponent.getResult());
String utils.UCS2ToUTF8(in String aInput) alias: utils.UnicodeToUTF8(), UCS2ToUTF8(), UnicodeToUTF8()

Returns a UTF-8 string from an UCS-2 (Unicode) string.

someXPCOMComponent.setValue(utils.UCS2ToUTF8(string));
String utils.XToUCS2(in String aInput, in String aEncoding) alias: utils.XToUnicode(), XToUCS2(), XToUnicode()

Returns a UCS-2 (Unicode) string from an encoded string specified as the 1st argument. You must specify the encoding of the string (ex. Shift_JIS, EUC-JP) as the 2nd argument.

var string = utils.XToUCS2(string, 'EUC-JP');
String utils.UCS2ToX(in String aInput, in String aEncoding) alias: utils.UnicodeToX(), UCS2ToX(), UnicodeToX()

Returns an encoded string from aa UCS-2 (Unicode) string specified as the 1st argument. You must specify the target encoding (ex. Shift_JIS, EUC-JP) as the 2nd argument.

var string = utils.UCS2ToX(string, 'EUC-JP');
String utils.inspect(in Object aObject, [in String aIndent]) alias: inspect()

Returns the result of inspection about the specified JavaScript object, in human-readable style. Stringization rules are:

Array
utils.inspect() result of all elements are returned.
Object (object literals, hash, instances of custom classes)
utils.inspect() result of all properties are returned.

If you specify the 2nd argument, this returns formatted result with the indentation. For exmaple, if you specify " " (two spaces), then the result becomes 2-indented text.

utils.log(utils.inspect(result));
String utils.inspectDOMNode(in DOMNode aNode) alias: inspectDOMNode()

Returns XML source string from the specified DOM node. This will be useful for assertions of HTML fragments structures.

assert.equals(utils.inspectDOMNode($('template')),
              utils.inspectDOMNode(generated));
String utils.getClipBoard() alias: getClipBoard()

Returns the contents in the system clipboard as a string.

assert.equals('copied', utils.getClipBoard());
void utils.setClipBoard(in String aString) alias: setClipBoard()

Puts a string to the system clipboard.

utils.setClipBoard('foobar');
assert.equals('foobar', service.getStringFromClipBoard());
void utils.processTemplate(in String aString, [in Object aScope]) alias: processTemplate(), parseTemplate(), utils.parseTemplate()

Evaluates embedded JavaScript codes in the specified string, and returns the result. You can embed script fragments into <% ... %>. If you wish some value to be embedded, put statements into <%= ... %>.

This runs embedded codes in the scope specified as the 2nd argument or the current scope. You can access properties of the 2nd argument from embedded codes, as variables.

var source = <![CDATA[
      I say it three times because it is very important.
      <% for (var i = 0; i < 3; i++) { %>
        It is <%= today %>, today.
      <% } %>
      OK?
    ]]>.toString();
var params = {
      today : (new Date()).toString()
    };
var result = utils.processTemplate(source, params);
Boolean utils.compareVersions(in String aVersionA, in String aOperator, in String aVersionB) alias: compareVersions()

Compares two strings as version numbers, with the operator specified as the 2nd argument, and returns the result as a boolean value. Available operators are ==, !=, <, <=, >, and >=. Otherwise raises an error.

utils.compareVersions('2.0.0.16', '<', '3.0.10'); // true
utils.compareVersions('3.0', '==', '3.0.0'); // true
utils.compareVersions('3.6a1pre', '>=', '3.5b5'); // true
Number utils.compareVersions(in String aVersionA, in String aVersionB) alias: compareVersions()

This is another behavior of utils.compareVersions() when you call the method only with two arguments.

Compares two strings as version numbers, and returns the result as a number. If aVersionA < aVersionB, returns -1. aVersionA > aVersionB returns 1. If they are same, returns 0.

utils.compareVersions('2.0.0.16', '3.0.10'); // -1
utils.compareVersions('3.0', '3.0.0'); // 0
utils.compareVersions('3.6a1pre', '3.5b5'); // 1
String utils.computeHash(in String aString, in String aAlgorithm) alias: computeHash()

Computes the hash and returns hash string, from a string specified as the 1st argument, by the algorithm specified as the 2nd argument. Available hash algorithms are: md2, md5, sha1, sha256, sha384, and sha512.

assert.equals('2AAE6C35C94FCFB415DBE95F408B9CE91EE846ED',
              utils.computeHash('hello world', 'sha1'));
String utils.md2(in String aString) alias: md2()

Computes and returns the MD2 hash string from the specified file. Just same to utils.computeHash(aString, 'md2').

String utils.md5(in String aString) alias: md5()

Computes and returns the MD5 hash string from the specified file. Just same to utils.computeHash(aString, 'md5').

String utils.sha1(in String aString) alias: sha1()

Computes and returns the SHA-1 hash string from the specified file. Just same to utils.computeHash(aString, 'sha1').

String utils.sha256(in String aString) alias: sha256()

Computes and returns the SHA-256 hash string from the specified file. Just same to utils.computeHash(aString, 'sha256').

String utils.sha384(in String aString) alias: sha384()

Computes and returns the SHA-384 hash string from the specified file. Just same to utils.computeHash(aString, 'sha384').

String utils.sha512(in String aString) alias: sha512()

Computes and returns the SHA-512 hash string from the specified file. Just same to utils.computeHash(aString, 'sha512').

JSON operation helpers

Object utils.readJSON(in Object aFile, [in String aEncoding], [in Object aScope]) alias: readJSON()

Reads the specified file as a text, and returns the result of eval(). You can specify file as a native file path, a file URL, a nsIFileURL object, or a nsIFile object. By default UxU reads the file as UTF-8 encoded text, but you can override the encoding by the 2nd argument.

If you specify an object as the 3rd argument, then, this runs utils.processTemplate(script, aScope) internally before doing eval().

var data1 = utils.readJSON('../fixtures/data.json');

var data2 = utils.readJSON(
              '../fixtures/SJIS.json',
              'Shift_JIS',
              { date : Date.now() }
            );

CSV operation helpers

String Array utils.parseCSV(in String aCSV) alias: parseCSV()

Parses the specified string as a CSV (comma separated values) and returns an 2D array. Parsing rules are:

  • Only the CVS format defined in RFC4180 is available.
  • Fields are returned as strings.
  • Other special characters like Tab or expressions, they are returned as strings too.
var CSV = <![CDATA[name,party,country
"Aso, Taro",LDP,Japan
"Hatoyama, Yukio",DPJ,Japan
George W Bush,PP,USA
Barack Obama,DP,USA]]>.toString();

assert.equals(
  [['name', 'party', 'country'],
   ['Aso, Taro', 'LDP', 'Japan'],
   ['Hatoyama, Yukio', 'DPJ', 'Japan'],
   ['George W Bush', 'PP', 'USA'],
   ['Barack Obama', 'DP', 'USA']],
  utils.parseCSV(CSV)
);
String Array utils.readCSV(in Object aFile, [in String aEncoding], [in Object aScope]) alias: readCSV()

Reads the specified file, and returns the result of utils.parseCSV(). You can specify file as a native file path, a file URL, a nsIFileURL object, or a nsIFile object. By default UxU reads the file as UTF-8 encoded text, but you can override the encoding by the 2nd argument.

If you specify an object as the 3rd argument, then, this runs utils.processTemplate(script, aScope) internally before doing utils.parseCSV().

var data1 = utils.readCSV('../fixtures/data.csv');

var data2 = utils.readCSV(
              '../fixtures/SJIS.csv',
              'Shift_JIS',
              { date : Date.now() }
            );
Object utils.readParametersFromCSV(in Object aFile, [in String aEncoding], [in Object aScope]) alias: readParametersFromCSV(), readParameterFromCSV(), readParamsFromCSV(), readParamFromCSV(), utils.readParameterFromCSV(), utils.readParamsFromCSV(), utils.readParamFromCSV()

Reads the specified file, does utils.parseCSV(), and returns an array or a hash for data driven tests. You can specify file as a native file path, a file URL, a nsIFileURL object, or a nsIFile object. By default UxU reads the file as UTF-8 encoded text, but you can override the encoding by the 2nd argument.

If you specify an object as the 3rd argument, then, this runs utils.processTemplate(script, aScope) internally before doing utils.parseCSV().

var data = utils.readParametersFromCSV('../fixtures/data.csv', 'UTF-8');
test_myFunc.parameters = data;
function test_myFunc(aParameter) {
  assert.equals(aParameter.expected, myFunc(aParameter.input));
}

Parsing rules for data driven tests from CSV are:

  • Each record becomes to a hash.
  • The first record is the definition of columns. Column names are used as hash keys of following records.
  • If the first field of the first record is blank, then, this returns a hash. First fields of records are used as hash key. Otherwise this returns an array.
  • "[something]" suffix of each column name is parsed as the type of the column. The suffix will be removed from the column name automatically.
    type definitiontype of values
    [string]string
    [char]
    [number]number
    [float]
    [double]
    [int]integer
    [boolean]boolean
    [bool]
    [object]JSON string (parsed as JavaScript object)
    [json]
    otherwiseAuto detect. "true" or "false" become boolean, decimal real number become number, otherwise string.
  • Each name of columns and records is unique. If there are duplicated names, they will be made unique with suffix like "(2)", "(3)" etc.

For example, a CSV:

inputtoString16 [string]toUpperCase16 [string]
10aA
255ffFF

to:

[{ input: 10,  toString16: 'a',  toUpperCase16: 'A' },
 { input: 255, toString16: 'ff', toUpperCase16: 'FF' }]

Another CSV:

 inputtoString16 [string]toUpperCase16 [string]
first10aA
second255ffFF

to:

{ first:  { input: 10,  toString16: 'a',  toUpperCase16: 'A' },
  second: { input: 255, toString16: 'ff', toUpperCase16: 'FF' }}
String Array utils.parseTSV(in String aTSV) alias: parseTSV()

Parses the specified string TSV (tab separated values) and returns an 2D array. This works just same as utils.parseCSV() excepting the delimiter: not commas (",") but tabs ("\t").

String Array utils.readTSV(in Object aFile, [in String aEncoding], [in Object aScope]) alias: readTSV()

Reads the specified file, and returns the result of utils.parseTSV(). This works just same as utils.readCSV() excepting the delimiter: not commas (",") but tabs ("\t").

Object utils.readParametersFromTSV(in Object aFile, [in String aEncoding], [in Object aScope]) alias: readParametersFromTSV(), readParameterFromTSV(), readParamsFromTSV(), readParamFromTSV(), utils.readParameterFromTSV(), utils.readParamsFromTSV(), utils.readParamFromTSV()

Reads the specified file, does utils.parseTSV(), and returns an array or a hash for data driven tests. This works just same as utils.readParametersFromCSV() excepting the delimiter: not commas (",") but tabs ("\t").

Local HTTP server helpers

Function utils.setUpHttpServer(in Number aPort, in Object aDocumentRoot) alias: setUpHttpServer()

Starts an HTTP server daemon, with the port specified as the 1st argument and the document root specified by the 2nd argument (a native file path, a file URL, a nsIFileURL object, or a nsIFile object). This returns an waiting function, for deferred operations after the daemon successfully started.

utils.wait(utils.setUpHttpServer(4445, '../fixtures/'));
utils.loadURI('http://localhost:4445/sample.html');
assert.equals('sample page', content.document.title);
Object utils.tearDownHttpServer(in Number aPort) alias: tearDownHttpServer()

Stops an HTTP server daemon started by utils.setUpHttpServer() with the port specified as the 1st argument. This returns an waiting object, for deferred operations after the daemon successfully stopped.

utils.wait(utils.tearDownHttpServer(4445));
Function utils.tearDownAllHttpServers() alias: tearDownAllHttpServers()

Stops all HTTP server daemons started by utils.setUpHttpServer(), from the test case. This returns an waiting object, for deferred operations after all daemons successfully stopped.

utils.wait(utils.tearDownAllHttpServers());

All HTTP server daemons automatically stops after all tests in the testcase are done, even if they are not stopped manually.

Database operation helpers

mozIStorageConnection utils.openDatabase(in Object aFile) alias: openDatabase()

Creates and returns a connection object for an SQLite database from the specified file, a native file path, a file URL, a nsIFileURL object, or a nsIFile object.

var dbconn = utils.openDatabase('../fixtures/test.sqlite');
var statement = dbconn.createStatement('SELECT value FROM test_table WHERE key = "foo"');
statement.executeStep();
var value = statement.getString(0);
mozIStorageConnection utils.createDatabase() alias: createDatabase()

Creates a new temporary database into the temporary directory of the platform, and returns a connection object for the SQLite database.

var dbconn = utils.createDatabase();
dbconn.executeSimpleSQL('CREATE TABLE test_table (key TEXT PRIMARY KEY, value TEXT)');
mozIStorageConnection utils.createDatabaseFromSQL(in String aSQL) alias: createDatabaseFromSQL()

Creates a new temporary database into the temporary directory of the platform, runs the specified SQL, and returns a connection object for the SQLite database.

var dbconn = utils.createDatabaseFromSQL(<![CDATA[
               DROP TABLE IF EXISTS "foo_table";
               CREATE TABLE "foo_table" ("key" TEXT PRIMARY KEY  NOT NULL , "value" TEXT);
               INSERT INTO "foo_table" VALUES('foo','bar');
               INSERT INTO "foo_table" VALUES('hoge','fuga');
             ]]>.toString());
var statement = dbconn.createStatement('SELECT value FROM foo_table WHERE key = "foo"');
statement.executeStep();
var value = statement.getString(0);
mozIStorageConnection utils.createDatabaseFromSQLFile(in Object aFile, [in String aEncoding], [in Object aScope]) alias: createDatabaseFromSQLFile()

Creates a new temporary database into the temporary directory of the platform, runs an SQL in the specified file (a native file path, a file URL, a nsIFileURL object, or a nsIFile object), and returns a connection object for the SQLite database. By default UxU reads the file as UTF-8 encoded text, but you can override the encoding by the 2nd argument.

If you specify an object as the 3rd argument, then, this runs utils.processTemplate(SQLFromFile, aScope) internally.

var dbconn = utils.createDatabaseFromSQLFile('../fixtures/test.sql', 'Shift_JIS');
var statement = dbconn.createStatement('SELECT value FROM test_table WHERE key = "key1"');
statement.executeStep();
var value = statement.getString(0);

Script loading helpers

void utils.include(in Object aFile, [in String aEncoding], [in Object aScope]) alias: include()
void utils.include(in Object aFile, [in Object aScope])

Loads the script specified as the 1st argument (a native file path, a file URL, a nsIFileURL object, or a nsIFile object), and runs it in the scope specified as (the 2nd or) the 3rd argument. By default UxU reads the file as UTF-8 encoded text, but you can override the encoding by the 2nd argument.

utils.include('../test/basic.js');

var namespace = { window : {} };
utils.include('../../content/library.js', 'Shfit_JIS', namespace);
var service = namespace.window.globalObject;

If you put relative pathes to utils.include(), then, they are resolved based on the place of the testcase file. It just same to baseURL + '<relative path>'.

Preferences helpers

value utils.getPref(in String aKey) alias: getPref()

Reads and returns the specified preference. This works for any type of preferences.

var locale = utils.getPref('general.useragent.locale');
void utils.setPref(in String aKey, in Object aValue) alias: setPref()

Saves the specified value to the preferences database. You don't have to care the type of the value (strings, number, or boolean). All changes in testcases are rolled back after all tests finished.

utils.setPref('extensions.myaddon.feature.enabled', true);
void utils.clearPref(in String aKey) alias: clearPref()

Clears the user value of the specified preference. All changes in testcases are rolled back after all tests finished.

utils.clearPref('browser.tabs.loadInBackground');
Object utils.loadPrefs(in Object aOriginalFile, [out Object aPrefs]) alias: loadPrefs()

Loads the specified preferences file (prefs.js, user.js, default prefs of addons, etc. including pref definitions like pref(aKey, aValue); or user_pref(aKey, aValue);) as a native file path, a file URL, a nsIFileURL object, or a nsIFile object. Defined values are temporally applied to the preferences database. This returns a hash of preferences loaded from the file.

All changes in testcases are rolled back after all tests finished.

If you specify any object as the 2nd argument, then, key-value pairs are added to the object as hash, from loaded preferences. In this case, loaded preferences are not applied to the database.

This method is completely compatible to the original feature of Firefox (Thunderbird) itself, like:

  • Comments started with # are available.
  • Custom functions are not available. Only pref(aKey, aValue); and user_pref(aKey, aValue); work correctly.
  • Only following escapes are available: \", \', \\, \r, \n, \xXX (escaped with hex number), and \uXXXX (Unicode escape). Otherwise, gotten as \\character. For example, tab character \t will be gotten as "\\t".
function setUp() {
  utils.loadPrefs('../../defaults/preferences/myaddon.js');
}

var prefs = {};
utils.loadPrefs('../fixtures/clearedPrefs.js', prefs);
for (var i in prefs) {
  utils.clearPref(prefs[i]);
}

Application informations

String utils.product alias: product

Returns the name of the application itself.

ApplicationValue
FirefoxFirefox
ThunderbirdThunderbird
SunbirdSunbird
Mozilla Application SuiteMozilla
SeaMonkeySeaMonkey
FennecFennec
Otherwiseblank string
var data = utils.readFrom('../fixtures/'+utils.product+'.txt');
String utils.productVersion alias: productVersion

Returns the version string of the application itself.

if (utils.compareVersions(utils.productVersion, '>=', '3.0')) {
  // something for Firefox 3.0 or later
}
String utils.platformVersion alias: platformVersion

Returns the version string of the Gecko.

if (utils.compareVersions(utils.platformVersion, '>=', '1.9.2')) {
  // something for Firefox 3.6 or later
}
nsIFile utils.productExecutable alias: productExecutable

Returns the executable file of the application itself. For example, "C:\Program Files\Mozilla Firefox\firefox.exe" for Firefox on Windows.

var applicationIni = utils.productExecutable.parent;
applicationIni.append('application.ini');

Windows registry helpers

Windows registry helpers are available only on Windows platform. If you call them on other platforms, they will raise exceptions.

Object utils.getWindowsRegistry(in String aKey) alias: getWindowsRegistry()

Reads and returns the value of the specified registry key. The type of the returned value depends on the original type on the registry. This returns null for unexisting keys.

data type on the registryreturned value
stringstring
integernumber
binarybytes array
othertrue if the key exists
var type = utils.getWindowsRegistry('HKCR\\.txt\\Content Type');
// => maybe "text/plain"
var proxySetting = utils.getWindowsRegistry(
                     'HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\'+
                       'CurrentVersion\\Internet Settings\\MigrateProxy'
                   );
Object utils.setWindowsRegistry(in String aKey, in Object aValue) alias: setWindowsRegistry()

Saves the value specified as the 2nd argument, to the registry key specified as the 1st argument. The value will be saved as the type of existing value, if the key already exists. Otherwise, the value will be saved as one of type in the following table. This method returns the specified value as is.

type of the 2nd argumentdata type on the registry
stringstring
numberinteger
bytes arraybinary
otherDoes nothing and raises exception.
utils.setWindowsRegistry(
  'HKEY_CLASSES_ROOT\\.foobar\\Content Type',
  'application/x-foobar'
);
void utils.clearWindowsRegistry(in String aKey) alias: clearWindowsRegistry()

Deletes the specified registry key. All of sub keys will be deleted too.

utils.clearWindowsRegistry(
  'HKEY_CURRENT_USER\\Software\\My Company\\My Product'
);

Others

void utils.wait(in Object aWaitingCondition) alias: wait()

Stops main thread on the line, and restarts by the specified condition. This is available on Gecko 1.9 or later (ex. Firefox 3, Thunderbird 3).

Ref: Complex testcases (functional-tests) with deferred operations

void utils.log(in String aMessage) alias: log()
void utils.dump(in String aMessage) alias: dump()

Outputs a message to both test runner and error console. When you specify multiple arguments, they are joined with "\n" before output.

utils.log('step 1:', object.value);
void utils.notify(in nsISupports aSubject, in String aTopic, in String aData) alias: notify()

Sends a message to existing observers, via nsIObserverService. This is a syntax sugar of ObserverService.notifyObservers().

utils.notify(window, 'CustomEvent:CloseRequest', Date.now());

To call Window.dump(), you have to write as window.dump(). If you write only dump(), then it works as utils.dump().