Updated QUnit

This commit is contained in:
Trevor Parscal 2012-03-09 21:50:24 +00:00
parent c977591886
commit 15b3515a1b
Notes: Trevor Parscal 2012-03-09 21:50:24 +00:00
2 changed files with 311 additions and 233 deletions

View file

@ -1,9 +1,9 @@
/** /**
* QUnit 1.2.0pre - A JavaScript Unit Testing Framework * QUnit v1.4.0pre - A JavaScript Unit Testing Framework
* *
* http://docs.jquery.com/QUnit * http://docs.jquery.com/QUnit
* *
* Copyright (c) 2011 John Resig, Jörn Zaefferer * Copyright (c) 2012 John Resig, Jörn Zaefferer
* Dual licensed under the MIT (MIT-LICENSE.txt) * Dual licensed under the MIT (MIT-LICENSE.txt)
* or GPL (GPL-LICENSE.txt) licenses. * or GPL (GPL-LICENSE.txt) licenses.
*/ */
@ -54,6 +54,10 @@
color: #fff; color: #fff;
} }
#qunit-header label {
display: inline-block;
}
#qunit-banner { #qunit-banner {
height: 5px; height: 5px;
} }
@ -223,4 +227,6 @@
position: absolute; position: absolute;
top: -10000px; top: -10000px;
left: -10000px; left: -10000px;
width: 1000px;
height: 1000px;
} }

View file

@ -1,9 +1,9 @@
/** /**
* QUnit 1.2.0pre - A JavaScript Unit Testing Framework * QUnit v1.4.0pre - A JavaScript Unit Testing Framework
* *
* http://docs.jquery.com/QUnit * http://docs.jquery.com/QUnit
* *
* Copyright (c) 2011 John Resig, Jörn Zaefferer * Copyright (c) 2012 John Resig, Jörn Zaefferer
* Dual licensed under the MIT (MIT-LICENSE.txt) * Dual licensed under the MIT (MIT-LICENSE.txt)
* or GPL (GPL-LICENSE.txt) licenses. * or GPL (GPL-LICENSE.txt) licenses.
*/ */
@ -13,23 +13,25 @@
var defined = { var defined = {
setTimeout: typeof window.setTimeout !== "undefined", setTimeout: typeof window.setTimeout !== "undefined",
sessionStorage: (function() { sessionStorage: (function() {
var x = "qunit-test-string";
try { try {
return !!sessionStorage.getItem; sessionStorage.setItem(x, x);
sessionStorage.removeItem(x);
return true;
} catch(e) { } catch(e) {
return false; return false;
} }
})() }())
}; };
var testId = 0, var testId = 0,
toString = Object.prototype.toString, toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty; hasOwn = Object.prototype.hasOwnProperty;
var Test = function(name, testName, expected, testEnvironmentArg, async, callback) { var Test = function(name, testName, expected, async, callback) {
this.name = name; this.name = name;
this.testName = testName; this.testName = testName;
this.expected = expected; this.expected = expected;
this.testEnvironmentArg = testEnvironmentArg;
this.async = async; this.async = async;
this.callback = callback; this.callback = callback;
this.assertions = []; this.assertions = [];
@ -62,6 +64,10 @@ Test.prototype = {
runLoggingCallbacks( 'moduleStart', QUnit, { runLoggingCallbacks( 'moduleStart', QUnit, {
name: this.module name: this.module
} ); } );
} else if (config.autorun) {
runLoggingCallbacks( 'moduleStart', QUnit, {
name: this.module
} );
} }
config.current = this; config.current = this;
@ -69,9 +75,6 @@ Test.prototype = {
setup: function() {}, setup: function() {},
teardown: function() {} teardown: function() {}
}, this.moduleTestEnvironment); }, this.moduleTestEnvironment);
if (this.testEnvironmentArg) {
extend(this.testEnvironment, this.testEnvironmentArg);
}
runLoggingCallbacks( 'testStart', QUnit, { runLoggingCallbacks( 'testStart', QUnit, {
name: this.testName, name: this.testName,
@ -82,14 +85,17 @@ Test.prototype = {
// TODO why?? // TODO why??
QUnit.current_testEnvironment = this.testEnvironment; QUnit.current_testEnvironment = this.testEnvironment;
try {
if ( !config.pollution ) { if ( !config.pollution ) {
saveGlobal(); saveGlobal();
} }
if ( config.notrycatch ) {
this.testEnvironment.setup.call(this.testEnvironment);
return;
}
try {
this.testEnvironment.setup.call(this.testEnvironment); this.testEnvironment.setup.call(this.testEnvironment);
} catch(e) { } catch(e) {
QUnit.ok( false, "Setup failed on " + this.testName + ": " + e.message ); QUnit.pushFailure( "Setup failed on " + this.testName + ": " + e.message, extractStacktrace( e, 1 ) );
} }
}, },
run: function() { run: function() {
@ -105,8 +111,7 @@ Test.prototype = {
try { try {
this.callback.call(this.testEnvironment); this.callback.call(this.testEnvironment);
} catch(e) { } catch(e) {
fail("Test " + this.testName + " died, exception and test follows", e, this.callback); QUnit.pushFailure( "Died on test #" + (this.assertions.length + 1) + ": " + e.message, extractStacktrace( e, 1 ) );
QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) );
// else next test will carry the responsibility // else next test will carry the responsibility
saveGlobal(); saveGlobal();
@ -118,20 +123,28 @@ Test.prototype = {
}, },
teardown: function() { teardown: function() {
config.current = this; config.current = this;
if ( config.notrycatch ) {
this.testEnvironment.teardown.call(this.testEnvironment);
return;
} else {
try { try {
this.testEnvironment.teardown.call(this.testEnvironment); this.testEnvironment.teardown.call(this.testEnvironment);
checkPollution();
} catch(e) { } catch(e) {
QUnit.ok( false, "Teardown failed on " + this.testName + ": " + e.message ); QUnit.pushFailure( "Teardown failed on " + this.testName + ": " + e.message, extractStacktrace( e, 1 ) );
} }
}
checkPollution();
}, },
finish: function() { finish: function() {
config.current = this; config.current = this;
if ( this.expected != null && this.expected != this.assertions.length ) { if ( this.expected != null && this.expected != this.assertions.length ) {
QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" ); QUnit.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" );
} else if ( this.expected == null && !this.assertions.length ) {
QUnit.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions." );
} }
var good = 0, bad = 0, var good = 0, bad = 0,
li, i,
tests = id("qunit-tests"); tests = id("qunit-tests");
config.stats.all += this.assertions.length; config.stats.all += this.assertions.length;
@ -140,10 +153,10 @@ Test.prototype = {
if ( tests ) { if ( tests ) {
var ol = document.createElement("ol"); var ol = document.createElement("ol");
for ( var i = 0; i < this.assertions.length; i++ ) { for ( i = 0; i < this.assertions.length; i++ ) {
var assertion = this.assertions[i]; var assertion = this.assertions[i];
var li = document.createElement("li"); li = document.createElement("li");
li.className = assertion.result ? "pass" : "fail"; li.className = assertion.result ? "pass" : "fail";
li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed"); li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed");
ol.appendChild( li ); ol.appendChild( li );
@ -166,7 +179,7 @@ Test.prototype = {
} }
} }
if (bad == 0) { if (bad === 0) {
ol.style.display = "none"; ol.style.display = "none";
} }
@ -193,7 +206,7 @@ Test.prototype = {
} }
}); });
var li = id(this.id); li = id(this.id);
li.className = bad ? "fail" : "pass"; li.className = bad ? "fail" : "pass";
li.removeChild( li.firstChild ); li.removeChild( li.firstChild );
li.appendChild( b ); li.appendChild( b );
@ -201,7 +214,7 @@ Test.prototype = {
li.appendChild( ol ); li.appendChild( ol );
} else { } else {
for ( var i = 0; i < this.assertions.length; i++ ) { for ( i = 0; i < this.assertions.length; i++ ) {
if ( !this.assertions[i].result ) { if ( !this.assertions[i].result ) {
bad++; bad++;
config.stats.bad++; config.stats.bad++;
@ -210,11 +223,7 @@ Test.prototype = {
} }
} }
try {
QUnit.reset(); QUnit.reset();
} catch(e) {
fail("reset() failed, following Test " + this.testName + ", exception and reset fn follows", e, QUnit.reset);
}
runLoggingCallbacks( 'testDone', QUnit, { runLoggingCallbacks( 'testDone', QUnit, {
name: this.testName, name: this.testName,
@ -251,7 +260,7 @@ Test.prototype = {
run(); run();
} else { } else {
synchronize(run, true); synchronize(run, true);
}; }
} }
}; };
@ -274,17 +283,12 @@ var QUnit = {
}, },
test: function(testName, expected, callback, async) { test: function(testName, expected, callback, async) {
var name = '<span class="test-name">' + testName + '</span>', testEnvironmentArg; var name = '<span class="test-name">' + escapeInnerText(testName) + '</span>';
if ( arguments.length === 2 ) { if ( arguments.length === 2 ) {
callback = expected; callback = expected;
expected = null; expected = null;
} }
// is 2nd argument a testEnvironment?
if ( expected && typeof expected === 'object') {
testEnvironmentArg = expected;
expected = null;
}
if ( config.currentModule ) { if ( config.currentModule ) {
name = '<span class="module-name">' + config.currentModule + "</span>: " + name; name = '<span class="module-name">' + config.currentModule + "</span>: " + name;
@ -294,49 +298,45 @@ var QUnit = {
return; return;
} }
var test = new Test(name, testName, expected, testEnvironmentArg, async, callback); var test = new Test(name, testName, expected, async, callback);
test.module = config.currentModule; test.module = config.currentModule;
test.moduleTestEnvironment = config.currentModuleTestEnviroment; test.moduleTestEnvironment = config.currentModuleTestEnviroment;
test.queue(); test.queue();
}, },
/** // Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
* Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
*/
expect: function(asserts) { expect: function(asserts) {
config.current.expected = asserts; config.current.expected = asserts;
}, },
/** // Asserts true.
* Asserts true. // @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
* @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); ok: function(result, msg) {
*/ if (!config.current) {
ok: function(a, msg) { throw new Error("ok() assertion outside test context, was " + sourceFromStacktrace(2));
a = !!a; }
result = !!result;
var details = { var details = {
result: a, result: result,
message: msg message: msg
}; };
msg = escapeInnerText(msg); msg = escapeInnerText(msg || (result ? "okay" : "failed"));
if ( !result ) {
var source = sourceFromStacktrace(2);
if (source) {
details.source = source;
msg += '<table><tr class="test-source"><th>Source: </th><td><pre>' + escapeInnerText(source) + '</pre></td></tr></table>';
}
}
runLoggingCallbacks( 'log', QUnit, details ); runLoggingCallbacks( 'log', QUnit, details );
config.current.assertions.push({ config.current.assertions.push({
result: a, result: result,
message: msg message: msg
}); });
}, },
/** // Checks that the first two arguments are equal, with an optional message. Prints out both actual and expected values.
* Checks that the first two arguments are equal, with an optional message. // @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." );
* Prints out both actual and expected values.
*
* Prefered to ok( actual == expected, message )
*
* @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." );
*
* @param Object actual
* @param Object expected
* @param String message (optional)
*/
equal: function(actual, expected, message) { equal: function(actual, expected, message) {
QUnit.push(expected == actual, actual, expected, message); QUnit.push(expected == actual, actual, expected, message);
}, },
@ -440,16 +440,21 @@ var QUnit = {
//We want access to the constructor's prototype //We want access to the constructor's prototype
(function() { (function() {
function F(){}; function F(){}
F.prototype = QUnit; F.prototype = QUnit;
QUnit = new F(); QUnit = new F();
//Make F QUnit's constructor so that we can add to the prototype later //Make F QUnit's constructor so that we can add to the prototype later
QUnit.constructor = F; QUnit.constructor = F;
})(); }());
// Backwards compatibility, deprecated // deprecated; still export them to window to provide clear error messages
QUnit.equals = QUnit.equal; // next step: remove entirely
QUnit.same = QUnit.deepEqual; QUnit.equals = function() {
QUnit.push(false, false, false, "QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead");
};
QUnit.same = function() {
QUnit.push(false, false, false, "QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead");
};
// Maintain internal state // Maintain internal state
var config = { var config = {
@ -504,17 +509,14 @@ var config = {
config.filter = urlParams.filter; config.filter = urlParams.filter;
// Figure out if we're running the tests from a server or not // Figure out if we're running the tests from a server or not
QUnit.isLocal = !!(location.protocol === 'file:'); QUnit.isLocal = location.protocol === 'file:';
})(); }());
// Expose the API as global variables, unless an 'exports' // Expose the API as global variables, unless an 'exports'
// object exists, in that case we assume we're in CommonJS // object exists, in that case we assume we're in CommonJS - export everything at the end
if ( typeof exports === "undefined" || typeof require === "undefined" ) { if ( typeof exports === "undefined" || typeof require === "undefined" ) {
extend(window, QUnit); extend(window, QUnit);
window.QUnit = QUnit; window.QUnit = QUnit;
} else {
extend(exports, QUnit);
exports.QUnit = QUnit;
} }
// define these after exposing globals to keep them in these QUnit namespace only // define these after exposing globals to keep them in these QUnit namespace only
@ -526,7 +528,7 @@ extend(QUnit, {
extend(config, { extend(config, {
stats: { all: 0, bad: 0 }, stats: { all: 0, bad: 0 },
moduleStats: { all: 0, bad: 0 }, moduleStats: { all: 0, bad: 0 },
started: +new Date, started: +new Date(),
updateRate: 1000, updateRate: 1000,
blocking: false, blocking: false,
autostart: true, autostart: true,
@ -536,6 +538,16 @@ extend(QUnit, {
semaphore: 0 semaphore: 0
}); });
var qunit = id( "qunit" );
if ( qunit ) {
qunit.innerHTML =
'<h1 id="qunit-header">' + escapeInnerText( document.title ) + '</h1>' +
'<h2 id="qunit-banner"></h2>' +
'<div id="qunit-testrunner-toolbar"></div>' +
'<h2 id="qunit-userAgent"></h2>' +
'<ol id="qunit-tests"></ol>';
}
var tests = id( "qunit-tests" ), var tests = id( "qunit-tests" ),
banner = id( "qunit-banner" ), banner = id( "qunit-banner" ),
result = id( "qunit-testresult" ); result = id( "qunit-testresult" );
@ -561,11 +573,8 @@ extend(QUnit, {
} }
}, },
/** // Resets the test setup. Useful for tests that modify the DOM.
* Resets the test setup. Useful for tests that modify the DOM. // If jQuery is available, uses jQuery's html(), otherwise just innerHTML.
*
* If jQuery is available, uses jQuery's html(), otherwise just innerHTML.
*/
reset: function() { reset: function() {
if ( window.jQuery ) { if ( window.jQuery ) {
jQuery( "#qunit-fixture" ).html( config.fixture ); jQuery( "#qunit-fixture" ).html( config.fixture );
@ -577,14 +586,8 @@ extend(QUnit, {
} }
}, },
/** // Trigger an event on an element.
* Trigger an event on an element. // @example triggerEvent( document.body, "click" );
*
* @example triggerEvent( document.body, "click" );
*
* @param DOMElement elem
* @param String type
*/
triggerEvent: function( elem, type, event ) { triggerEvent: function( elem, type, event ) {
if ( document.createEvent ) { if ( document.createEvent ) {
event = document.createEvent("MouseEvents"); event = document.createEvent("MouseEvents");
@ -618,9 +621,8 @@ extend(QUnit, {
case 'Number': case 'Number':
if (isNaN(obj)) { if (isNaN(obj)) {
return "nan"; return "nan";
} else {
return "number";
} }
return "number";
case 'String': case 'String':
case 'Boolean': case 'Boolean':
case 'Array': case 'Array':
@ -636,6 +638,9 @@ extend(QUnit, {
}, },
push: function(result, actual, expected, message) { push: function(result, actual, expected, message) {
if (!config.current) {
throw new Error("assertion outside test context, was " + sourceFromStacktrace());
}
var details = { var details = {
result: result, result: result,
message: message, message: message,
@ -645,21 +650,22 @@ extend(QUnit, {
message = escapeInnerText(message) || (result ? "okay" : "failed"); message = escapeInnerText(message) || (result ? "okay" : "failed");
message = '<span class="test-message">' + message + "</span>"; message = '<span class="test-message">' + message + "</span>";
var output = message;
if (!result) {
expected = escapeInnerText(QUnit.jsDump.parse(expected)); expected = escapeInnerText(QUnit.jsDump.parse(expected));
actual = escapeInnerText(QUnit.jsDump.parse(actual)); actual = escapeInnerText(QUnit.jsDump.parse(actual));
var output = message + '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>'; output += '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>';
if (actual != expected) { if (actual != expected) {
output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>'; output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>';
output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) +'</pre></td></tr>'; output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) +'</pre></td></tr>';
} }
if (!result) {
var source = sourceFromStacktrace(); var source = sourceFromStacktrace();
if (source) { if (source) {
details.source = source; details.source = source;
output += '<tr class="test-source"><th>Source: </th><td><pre>' + escapeInnerText(source) + '</pre></td></tr>'; output += '<tr class="test-source"><th>Source: </th><td><pre>' + escapeInnerText(source) + '</pre></td></tr>';
} }
}
output += "</table>"; output += "</table>";
}
runLoggingCallbacks( 'log', QUnit, details ); runLoggingCallbacks( 'log', QUnit, details );
@ -669,6 +675,23 @@ extend(QUnit, {
}); });
}, },
pushFailure: function(message, source) {
var details = {
result: false,
message: message
};
var output = escapeInnerText(message);
if (source) {
details.source = source;
output += '<table><tr class="test-source"><th>Source: </th><td><pre>' + escapeInnerText(source) + '</pre></td></tr></table>';
}
runLoggingCallbacks( 'log', QUnit, details );
config.current.assertions.push({
result: false,
message: output
});
},
url: function( params ) { url: function( params ) {
params = extend( extend( {}, QUnit.urlParams ), params ); params = extend( extend( {}, QUnit.urlParams ), params );
var querystring = "?", var querystring = "?",
@ -724,7 +747,8 @@ QUnit.load = function() {
config.blocking = false; config.blocking = false;
var urlConfigHtml = '', len = config.urlConfig.length; var urlConfigHtml = '', len = config.urlConfig.length;
for ( var i = 0, val; i < len, val = config.urlConfig[i]; i++ ) { for ( var i = 0, val; i < len; i++ ) {
val = config.urlConfig[i];
config[val] = QUnit.urlParams[val]; config[val] = QUnit.urlParams[val];
urlConfigHtml += '<label><input name="' + val + '" type="checkbox"' + ( config[val] ? ' checked="checked"' : '' ) + '>' + val + '</label>'; urlConfigHtml += '<label><input name="' + val + '" type="checkbox"' + ( config[val] ? ' checked="checked"' : '' ) + '>' + val + '</label>';
} }
@ -792,10 +816,10 @@ addEvent(window, "load", QUnit.load);
// addEvent(window, "error") gives us a useless event object // addEvent(window, "error") gives us a useless event object
window.onerror = function( message, file, line ) { window.onerror = function( message, file, line ) {
if ( QUnit.config.current ) { if ( QUnit.config.current ) {
ok( false, message + ", " + file + ":" + line ); QUnit.pushFailure( message, file + ":" + line );
} else { } else {
test( "global failure", function() { QUnit.test( "global failure", function() {
ok( false, message + ", " + file + ":" + line ); QUnit.pushFailure( message, file + ":" + line );
}); });
} }
}; };
@ -815,7 +839,7 @@ function done() {
var banner = id("qunit-banner"), var banner = id("qunit-banner"),
tests = id("qunit-tests"), tests = id("qunit-tests"),
runtime = +new Date - config.started, runtime = +new Date() - config.started,
passed = config.stats.all - config.stats.bad, passed = config.stats.all - config.stats.bad,
html = [ html = [
'Tests completed in ', 'Tests completed in ',
@ -847,6 +871,15 @@ function done() {
].join(" "); ].join(" ");
} }
// clear own sessionStorage items if all tests passed
if ( config.reorder && defined.sessionStorage && config.stats.bad === 0 ) {
for (var key in sessionStorage) {
if (sessionStorage.hasOwnProperty(key) && key.indexOf("qunit-") === 0 ) {
sessionStorage.removeItem(key);
}
}
}
runLoggingCallbacks( 'done', QUnit, { runLoggingCallbacks( 'done', QUnit, {
failed: config.stats.bad, failed: config.stats.bad,
passed: passed, passed: passed,
@ -881,21 +914,34 @@ function validTest( name ) {
// so far supports only Firefox, Chrome and Opera (buggy) // so far supports only Firefox, Chrome and Opera (buggy)
// could be extended in the future to use something like https://github.com/csnover/TraceKit // could be extended in the future to use something like https://github.com/csnover/TraceKit
function sourceFromStacktrace() { function extractStacktrace( e, offset ) {
offset = offset || 3;
if (e.stacktrace) {
// Opera
return e.stacktrace.split("\n")[offset + 3];
} else if (e.stack) {
// Firefox, Chrome
var stack = e.stack.split("\n");
if (/^error$/i.test(stack[0])) {
stack.shift();
}
return stack[offset];
} else if (e.sourceURL) {
// Safari, PhantomJS
// hopefully one day Safari provides actual stacktraces
// exclude useless self-reference for generated Error objects
if ( /qunit.js$/.test( e.sourceURL ) ) {
return;
}
// for actual exceptions, this is useful
return e.sourceURL + ":" + e.line;
}
}
function sourceFromStacktrace(offset) {
try { try {
throw new Error(); throw new Error();
} catch ( e ) { } catch ( e ) {
if (e.stacktrace) { return extractStacktrace( e, offset );
// Opera
return e.stacktrace.split("\n")[6];
} else if (e.stack) {
// Firefox, Chrome
return e.stack.split("\n")[4];
} else if (e.sourceURL) {
// Safari, PhantomJS
// TODO sourceURL points at the 'throw new Error' line above, useless
//return e.sourceURL + ":" + e.line;
}
} }
} }
@ -923,6 +969,9 @@ function synchronize( callback, last ) {
} }
function process( last ) { function process( last ) {
function next() {
process( last );
}
var start = new Date().getTime(); var start = new Date().getTime();
config.depth = config.depth ? config.depth + 1 : 1; config.depth = config.depth ? config.depth + 1 : 1;
@ -930,9 +979,7 @@ function process( last ) {
if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) { if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) {
config.queue.shift()(); config.queue.shift()();
} else { } else {
window.setTimeout( function(){ window.setTimeout( next, 13 );
process( last );
}, 13 );
break; break;
} }
} }
@ -961,12 +1008,12 @@ function checkPollution( name ) {
var newGlobals = diff( config.pollution, old ); var newGlobals = diff( config.pollution, old );
if ( newGlobals.length > 0 ) { if ( newGlobals.length > 0 ) {
ok( false, "Introduced global variable(s): " + newGlobals.join(", ") ); QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join(", ") );
} }
var deletedGlobals = diff( old, config.pollution ); var deletedGlobals = diff( old, config.pollution );
if ( deletedGlobals.length > 0 ) { if ( deletedGlobals.length > 0 ) {
ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") ); QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join(", ") );
} }
} }
@ -985,17 +1032,6 @@ function diff( a, b ) {
return result; return result;
} }
function fail(message, exception, callback) {
if ( typeof console !== "undefined" && console.error && console.warn ) {
console.error(message);
console.error(exception);
console.warn(callback.toString());
} else if ( window.opera && opera.postError ) {
opera.postError(message, exception, callback.toString);
}
}
function extend(a, b) { function extend(a, b) {
for ( var prop in b ) { for ( var prop in b ) {
if ( b[prop] === undefined ) { if ( b[prop] === undefined ) {
@ -1047,7 +1083,7 @@ function runLoggingCallbacks(key, scope, args) {
// Test for equality any JavaScript type. // Test for equality any JavaScript type.
// Author: Philippe Rathé <prathe@gmail.com> // Author: Philippe Rathé <prathe@gmail.com>
QUnit.equiv = function () { QUnit.equiv = (function() {
var innerEquiv; // the real equiv function var innerEquiv; // the real equiv function
var callers = []; // stack to decide between skip/abort functions var callers = []; // stack to decide between skip/abort functions
@ -1065,7 +1101,11 @@ QUnit.equiv = function () {
} }
} }
var callbacks = function () { var getProto = Object.getPrototypeOf || function (obj) {
return obj.__proto__;
};
var callbacks = (function () {
// for string, boolean, number and null // for string, boolean, number and null
function useStrictEquality(b, a) { function useStrictEquality(b, a) {
@ -1092,17 +1132,18 @@ QUnit.equiv = function () {
}, },
"date" : function(b, a) { "date" : function(b, a) {
return QUnit.objectType(b) === "date" return QUnit.objectType(b) === "date" && a.valueOf() === b.valueOf();
&& a.valueOf() === b.valueOf();
}, },
"regexp" : function(b, a) { "regexp" : function(b, a) {
return QUnit.objectType(b) === "regexp" return QUnit.objectType(b) === "regexp" &&
&& a.source === b.source && // the regex itself // the regex itself
a.global === b.global && // and its modifers a.source === b.source &&
// and its modifers
a.global === b.global &&
// (gmi) ... // (gmi) ...
a.ignoreCase === b.ignoreCase a.ignoreCase === b.ignoreCase &&
&& a.multiline === b.multiline; a.multiline === b.multiline;
}, },
// - skip when the property is a method of an instance (OOP) // - skip when the property is a method of an instance (OOP)
@ -1118,7 +1159,7 @@ QUnit.equiv = function () {
var len; var len;
// b could be an object literal here // b could be an object literal here
if (!(QUnit.objectType(b) === "array")) { if (QUnit.objectType(b) !== "array") {
return false; return false;
} }
@ -1154,8 +1195,14 @@ QUnit.equiv = function () {
// comparing constructors is more strict than using // comparing constructors is more strict than using
// instanceof // instanceof
if (a.constructor !== b.constructor) { if (a.constructor !== b.constructor) {
// Allow objects with no prototype to be equivalent to
// objects with Object as their constructor.
if (!((getProto(a) === null && getProto(b) === Object.prototype) ||
(getProto(b) === null && getProto(a) === Object.prototype)))
{
return false; return false;
} }
}
// stack constructor before traversing properties // stack constructor before traversing properties
callers.push(a.constructor); callers.push(a.constructor);
@ -1166,9 +1213,10 @@ QUnit.equiv = function () {
// and go deep // and go deep
loop = false; loop = false;
for (j = 0; j < parents.length; j++) { for (j = 0; j < parents.length; j++) {
if (parents[j] === a[i]) if (parents[j] === a[i]) {
loop = true; // don't go down the same path // don't go down the same path twice
// twice loop = true;
}
} }
aProperties.push(i); // collect a's properties aProperties.push(i); // collect a's properties
@ -1186,12 +1234,10 @@ QUnit.equiv = function () {
} }
// Ensures identical properties name // Ensures identical properties name
return eq return eq && innerEquiv(aProperties.sort(), bProperties.sort());
&& innerEquiv(aProperties.sort(), bProperties
.sort());
} }
}; };
}(); }());
innerEquiv = function() { // can take multiple arguments innerEquiv = function() { // can take multiple arguments
var args = Array.prototype.slice.apply(arguments); var args = Array.prototype.slice.apply(arguments);
@ -1202,23 +1248,21 @@ QUnit.equiv = function () {
return (function(a, b) { return (function(a, b) {
if (a === b) { if (a === b) {
return true; // catch the most you can return true; // catch the most you can
} else if (a === null || b === null || typeof a === "undefined" } else if (a === null || b === null || typeof a === "undefined" ||
|| typeof b === "undefined" typeof b === "undefined" ||
|| QUnit.objectType(a) !== QUnit.objectType(b)) { QUnit.objectType(a) !== QUnit.objectType(b)) {
return false; // don't lose time with error prone cases return false; // don't lose time with error prone cases
} else { } else {
return bindCallbacks(a, callbacks, [ b, a ]); return bindCallbacks(a, callbacks, [ b, a ]);
} }
// apply transition with (1..n) arguments // apply transition with (1..n) arguments
})(args[0], args[1]) }(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length - 1)));
&& arguments.callee.apply(this, args.splice(1,
args.length - 1));
}; };
return innerEquiv; return innerEquiv;
}(); }());
/** /**
* jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com |
@ -1233,28 +1277,31 @@ QUnit.equiv = function () {
QUnit.jsDump = (function() { QUnit.jsDump = (function() {
function quote( str ) { function quote( str ) {
return '"' + str.toString().replace(/"/g, '\\"') + '"'; return '"' + str.toString().replace(/"/g, '\\"') + '"';
}; }
function literal( o ) { function literal( o ) {
return o + ''; return o + '';
}; }
function join( pre, arr, post ) { function join( pre, arr, post ) {
var s = jsDump.separator(), var s = jsDump.separator(),
base = jsDump.indent(), base = jsDump.indent(),
inner = jsDump.indent(1); inner = jsDump.indent(1);
if ( arr.join ) if ( arr.join ) {
arr = arr.join( ',' + s + inner ); arr = arr.join( ',' + s + inner );
if ( !arr ) }
if ( !arr ) {
return pre + post; return pre + post;
}
return [ pre, inner + arr, base + post ].join(s); return [ pre, inner + arr, base + post ].join(s);
}; }
function array( arr, stack ) { function array( arr, stack ) {
var i = arr.length, ret = Array(i); var i = arr.length, ret = new Array(i);
this.up(); this.up();
while ( i-- ) while ( i-- ) {
ret[i] = this.parse( arr[i] , undefined , stack); ret[i] = this.parse( arr[i] , undefined , stack);
}
this.down(); this.down();
return join( '[', ret, ']' ); return join( '[', ret, ']' );
}; }
var reName = /^function (\w+)/; var reName = /^function (\w+)/;
@ -1311,12 +1358,14 @@ QUnit.jsDump = (function() {
return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? '&nbsp;' : ' '; return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? '&nbsp;' : ' ';
}, },
indent: function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing indent: function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing
if ( !this.multiline ) if ( !this.multiline ) {
return ''; return '';
}
var chr = this.indentChar; var chr = this.indentChar;
if ( this.HTML ) if ( this.HTML ) {
chr = chr.replace(/\t/g,' ').replace(/ /g,'&nbsp;'); chr = chr.replace(/\t/g,' ').replace(/ /g,'&nbsp;');
return Array( this._depth_ + (extra||0) ).join(chr); }
return new Array( this._depth_ + (extra||0) ).join(chr);
}, },
up: function( a ) { up: function( a ) {
this._depth_ += a || 1; this._depth_ += a || 1;
@ -1344,8 +1393,9 @@ QUnit.jsDump = (function() {
'function': function( fn ) { 'function': function( fn ) {
var ret = 'function', var ret = 'function',
name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE
if ( name ) if ( name ) {
ret += ' ' + name; ret += ' ' + name;
}
ret += '('; ret += '(';
ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join(''); ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join('');
@ -1353,12 +1403,20 @@ QUnit.jsDump = (function() {
}, },
array: array, array: array,
nodelist: array, nodelist: array,
arguments: array, 'arguments': array,
object: function( map, stack ) { object: function( map, stack ) {
var ret = [ ]; var ret = [ ], keys, key, val, i;
QUnit.jsDump.up(); QUnit.jsDump.up();
for ( var key in map ) { if (Object.keys) {
var val = map[key]; keys = Object.keys( map );
} else {
keys = [];
for (key in map) { keys.push( key ); }
}
keys.sort();
for (i = 0; i < keys.length; i++) {
key = keys[ i ];
val = map[ key ];
ret.push( QUnit.jsDump.parse( key, 'key' ) + ': ' + QUnit.jsDump.parse( val, undefined, stack ) ); ret.push( QUnit.jsDump.parse( key, 'key' ) + ': ' + QUnit.jsDump.parse( val, undefined, stack ) );
} }
QUnit.jsDump.down(); QUnit.jsDump.down();
@ -1373,18 +1431,22 @@ QUnit.jsDump = (function() {
for ( var a in QUnit.jsDump.DOMAttrs ) { for ( var a in QUnit.jsDump.DOMAttrs ) {
var val = node[QUnit.jsDump.DOMAttrs[a]]; var val = node[QUnit.jsDump.DOMAttrs[a]];
if ( val ) if ( val ) {
ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' ); ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' );
} }
}
return ret + close + open + '/' + tag + close; return ret + close + open + '/' + tag + close;
}, },
functionArgs: function( fn ) {//function calls it internally, it's the arguments part of the function functionArgs: function( fn ) {//function calls it internally, it's the arguments part of the function
var l = fn.length; var l = fn.length;
if ( !l ) return ''; if ( !l ) {
return '';
}
var args = Array(l); var args = new Array(l);
while ( l-- ) while ( l-- ) {
args[l] = String.fromCharCode(97+l);//97 is 'a' args[l] = String.fromCharCode(97+l);//97 is 'a'
}
return ' ' + args.join(', ') + ' '; return ' ' + args.join(', ') + ' ';
}, },
key: quote, //object calls it internally, the key part of an item in a map key: quote, //object calls it internally, the key part of an item in a map
@ -1407,7 +1469,7 @@ QUnit.jsDump = (function() {
}; };
return jsDump; return jsDump;
})(); }());
// from Sizzle.js // from Sizzle.js
function getText( elems ) { function getText( elems ) {
@ -1427,7 +1489,7 @@ function getText( elems ) {
} }
return ret; return ret;
}; }
//from jquery.js //from jquery.js
function inArray( elem, array ) { function inArray( elem, array ) {
@ -1462,26 +1524,29 @@ QUnit.diff = (function() {
function diff(o, n) { function diff(o, n) {
var ns = {}; var ns = {};
var os = {}; var os = {};
var i;
for (var i = 0; i < n.length; i++) { for (i = 0; i < n.length; i++) {
if (ns[n[i]] == null) if (ns[n[i]] == null) {
ns[n[i]] = { ns[n[i]] = {
rows: [], rows: [],
o: null o: null
}; };
}
ns[n[i]].rows.push(i); ns[n[i]].rows.push(i);
} }
for (var i = 0; i < o.length; i++) { for (i = 0; i < o.length; i++) {
if (os[o[i]] == null) if (os[o[i]] == null) {
os[o[i]] = { os[o[i]] = {
rows: [], rows: [],
n: null n: null
}; };
}
os[o[i]].rows.push(i); os[o[i]].rows.push(i);
} }
for (var i in ns) { for (i in ns) {
if ( !hasOwn.call( ns, i ) ) { if ( !hasOwn.call( ns, i ) ) {
continue; continue;
} }
@ -1497,7 +1562,7 @@ QUnit.diff = (function() {
} }
} }
for (var i = 0; i < n.length - 1; i++) { for (i = 0; i < n.length - 1; i++) {
if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null && if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null &&
n[i + 1] == o[n[i].row + 1]) { n[i + 1] == o[n[i].row + 1]) {
n[i + 1] = { n[i + 1] = {
@ -1511,7 +1576,7 @@ QUnit.diff = (function() {
} }
} }
for (var i = n.length - 1; i > 0; i--) { for (i = n.length - 1; i > 0; i--) {
if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null && if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null &&
n[i - 1] == o[n[i].row - 1]) { n[i - 1] == o[n[i].row - 1]) {
n[i - 1] = { n[i - 1] = {
@ -1534,9 +1599,10 @@ QUnit.diff = (function() {
return function(o, n) { return function(o, n) {
o = o.replace(/\s+$/, ''); o = o.replace(/\s+$/, '');
n = n.replace(/\s+$/, ''); n = n.replace(/\s+$/, '');
var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/)); var out = diff(o === "" ? [] : o.split(/\s+/), n === "" ? [] : n.split(/\s+/));
var str = ""; var str = "";
var i;
var oSpace = o.match(/\s+/g); var oSpace = o.match(/\s+/g);
if (oSpace == null) { if (oSpace == null) {
@ -1553,8 +1619,8 @@ QUnit.diff = (function() {
nSpace.push(" "); nSpace.push(" ");
} }
if (out.n.length == 0) { if (out.n.length === 0) {
for (var i = 0; i < out.o.length; i++) { for (i = 0; i < out.o.length; i++) {
str += '<del>' + out.o[i] + oSpace[i] + "</del>"; str += '<del>' + out.o[i] + oSpace[i] + "</del>";
} }
} }
@ -1565,7 +1631,7 @@ QUnit.diff = (function() {
} }
} }
for (var i = 0; i < out.n.length; i++) { for (i = 0; i < out.n.length; i++) {
if (out.n[i].text == null) { if (out.n[i].text == null) {
str += '<ins>' + out.n[i] + nSpace[i] + "</ins>"; str += '<ins>' + out.n[i] + nSpace[i] + "</ins>";
} }
@ -1582,6 +1648,12 @@ QUnit.diff = (function() {
return str; return str;
}; };
})(); }());
})(this); // for CommonJS enviroments, export everything
if ( typeof exports !== "undefined" || typeof require !== "undefined" ) {
extend(exports, QUnit);
}
// get at whatever the global object is, like window in browsers
}( (function() {return this;}.call()) ));