* * * Please do not link to this file here, but store it on your web server instead. * * * /// asserts.js by VisiBone, 2006, copyright schmopyright /// ---------- /// /// Examples: /// assert("2+2 == 4"); /// assertEquals("2+2", "4"); /// assertNull("window.nosuchmember"); /// assertNotNull("window.document"); /// /// Notice you pass JavaScript code as a string, you do NOT assert(2+2 == 4) which would give an error /// To-do: enclose eval() call in a try-catch exception-detector var numAssertFailures = 0; var MAXASSERTFAILURES = 3; // WARNING: do not use single-quotes in any jscode parameters function nottoomanyfailures() { numAssertFailures++; if (numAssertFailures < MAXASSERTFAILURES) { return true; } else if (numAssertFailures == MAXASSERTFAILURES+1) { alert("Too many ASSERT failures, not showing you any more."); return false; } else { return false; } } function assert(jscode) { if (typeof(jscode) === "string") { if (!eval(jscode)) { if (nottoomanyfailures()) alert("ASSERT FAILURE: '" + jscode + "'"); return false; } } else { if (nottoomanyfailures()) alert("ASSERT() wants JavaScript code in a string, not a " + typeof(jscode)); return false; } return true; } function assertEquals(jscode1, jscode2) { var result1 = eval(jscode1); var result2 = eval(jscode2); if (result1 != result2) { if (!assertEquals("typeof(jscode1)", "'string'")) return false; if (!assertEquals("typeof(jscode2)", "'string'")) return false; if (nottoomanyfailures()) alert(jscode1 + " != " + jscode2 + "\n" + '"' + result1 + '" != "' + result2 + '"'); return false; } if (result1 !== result2) { if (!assertEquals("typeof(jscode1)", "'string'")) return false; if (!assertEquals("typeof(jscode2)", "'string'")) return false; if (nottoomanyfailures()) alert(jscode1 + " !== " + jscode2 + "\n" + '"' + result1 + '" (a ' + typeof(result1) + ') !== ' + '"' + result2 + '" (a ' + typeof(result2) + ')'); return false; } return true; } function assertNull(jscode) { if (typeof(jscode) !== "string") { if (nottoomanyfailures()) alert("ASSERTNULL() wants JavaScript code in a string, not a " + typeof(jscode)); return false; } return assert("typeof(" + jscode + ") == 'undefined'"); } function assertNotNull(jscode) { if (typeof(jscode) !== "string") { if (nottoomanyfailures()) alert("ASSERTNOTNULL() wants JavaScript code in a string, not a " + typeof(jscode)); return false; } return assert("typeof(" + jscode + ") != 'undefined'"); }