Added equals helper for easier debugging of failed tests, soon to be used more often...
[jquery.git] / build / test / data / testrunner.js
1 var _config = {
2         fixture: null,
3         Test: [],
4         stats: {
5                 all: 0,
6                 bad: 0
7         },
8         queue: [],
9         blocking: true,
10         timeout: null,
11         expected: null,
12         currentModule: null,
13         asyncTimeout: 2 // seconds for async timeout
14 };
15
16 $(function() {
17         $('#userAgent').html(navigator.userAgent);
18         if($.browser.safari)
19                 $("h1").append(" - Slowed down for Safari to prevent crashes");
20         runTest();      
21 });
22
23 function synchronize(callback) {
24         _config.queue[_config.queue.length] = callback;
25         if(!_config.blocking) {
26                 process();
27         }
28 }
29
30 function process() {
31         while(_config.queue.length && !_config.blocking) {
32                 var call = _config.queue[0];
33                 _config.queue = _config.queue.slice(1);
34                 call();
35         }
36 }
37
38 function stop(allowFailure) {
39         _config.blocking = true;
40         var handler = allowFailure ? start : function() {
41                 ok( false, "Test timed out" );
42                 start();
43         };
44         _config.timeout = setTimeout(handler, _config.asyncTimeout * 1000);
45 }
46 function start() {
47         if(_config.timeout)
48                 clearTimeout(_config.timeout);
49         _config.blocking = false;
50         process();
51 }
52
53 function runTest() {
54         _config.blocking = false;
55         var time = new Date();
56         _config.fixture = document.getElementById('main').innerHTML;
57         synchronize(function() {
58                 time = new Date() - time;
59                 $("<div>").html(['<p class="result">Tests completed in ',
60                         time, ' milliseconds.<br/>',
61                         _config.stats.bad, ' tests of ', _config.stats.all, ' failed.</p>']
62                         .join(''))
63                         .appendTo("body");
64                 $("#banner").addClass(_config.stats.bad ? "fail" : "pass");
65         });
66 }
67
68 function test(name, callback, nowait) {
69         // safari seems to have some memory problems, so we need to slow it down
70         if($.browser.safari && !nowait) {
71                 test("", function() {
72                         stop();
73                         setTimeout(start, 250);
74                 }, true);
75         }
76
77         if(_config.currentModule)
78                 name = _config.currentModule + " module: " + name;
79                 
80         synchronize(function() {
81                 _config.Test = [];
82                 try {
83                         callback();
84                 } catch(e) {
85                         if( typeof console != "undefined" && console.error && console.warn ) {
86                                 console.error("Test " + name + " died, exception and test follows");
87                                 console.error(e);
88                                 console.warn(callback.toString());
89                         }
90                         _config.Test.push( [ false, "Died on test #" + (_config.Test.length+1) + ": " + e ] );
91                 }
92         });
93         synchronize(function() {
94                 reset();
95                 
96                 // don't output pause tests
97                 if(nowait) return;
98                 
99                 if(_config.expected && _config.expected != _config.Test.length) {
100                         _config.Test.push( [ false, "Expected " + _config.expected + " assertions, but " + _config.Test.length + " were run" ] );
101                 }
102                 _config.expected = null;
103                 
104                 var good = 0, bad = 0;
105                 var ol = document.createElement("ol");
106                 ol.style.display = "none";
107                 var li = "", state = "pass";
108                 for ( var i = 0; i < _config.Test.length; i++ ) {
109                         var li = document.createElement("li");
110                         li.className = _config.Test[i][0] ? "pass" : "fail";
111                         li.innerHTML = _config.Test[i][1];
112                         ol.appendChild( li );
113                         
114                         _config.stats.all++;
115                         if ( !_config.Test[i][0] ) {
116                                 state = "fail";
117                                 bad++;
118                                 _config.stats.bad++;
119                         } else good++;
120                 }
121         
122                 var li = document.createElement("li");
123                 li.className = state;
124         
125                 var b = document.createElement("b");
126                 b.innerHTML = name + " <b style='color:black;'>(<b class='fail'>" + bad + "</b>, <b class='pass'>" + good + "</b>, " + _config.Test.length + ")</b>";
127                 b.onclick = function(){
128                         var n = this.nextSibling;
129                         if ( jQuery.css( n, "display" ) == "none" )
130                                 n.style.display = "block";
131                         else
132                                 n.style.display = "none";
133                 };
134                 li.appendChild( b );
135                 li.appendChild( ol );
136         
137                 document.getElementById("tests").appendChild( li );             
138         });
139 }
140
141 // call on start of module test to prepend name to all tests
142 function module(moduleName) {
143         _config.currentModule = moduleName;
144 }
145
146 /**
147  * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
148  */
149 function expect(asserts) {
150         _config.expected = asserts;
151 }
152
153 /**
154  * Resets the test setup. Useful for tests that modify the DOM.
155  */
156 function reset() {
157         document.getElementById('main').innerHTML = _config.fixture;
158 }
159
160 /**
161  * Asserts true.
162  * @example ok( $("a").size() > 5, "There must be at least 5 anchors" );
163  */
164 function ok(a, msg) {
165         _config.Test.push( [ !!a, msg ] );
166 }
167
168 /**
169  * Asserts that two arrays are the same
170  */
171 function isSet(a, b, msg) {
172         var ret = true;
173         if ( a && b && a.length == b.length ) {
174                 for ( var i in a )
175                         if ( a[i] != b[i] )
176                                 ret = false;
177         } else
178                 ret = false;
179         if ( !ret )
180                 _config.Test.push( [ ret, msg + " expected: " + b + " result: " + a ] );
181         else 
182                 _config.Test.push( [ ret, msg ] );
183 }
184
185 /**
186  * Returns an array of elements with the given IDs, eg.
187  * @example q("main", "foo", "bar")
188  * @result [<div id="main">, <span id="foo">, <input id="bar">]
189  */
190 function q() {
191         var r = [];
192         for ( var i = 0; i < arguments.length; i++ )
193                 r.push( document.getElementById( arguments[i] ) );
194         return r;
195 }
196
197 /**
198  * Asserts that a select matches the given IDs
199  * @example t("Check for something", "//[a]", ["foo", "baar"]);
200  * @result returns true if "//[a]" return two elements with the IDs 'foo' and 'baar'
201  */
202 function t(a,b,c) {
203         var f = jQuery.find(b);
204         var s = "";
205         for ( var i = 0; i < f.length; i++ )
206                 s += (s && ",") + '"' + f[i].id + '"';
207         isSet(f, q.apply(q,c), a + " (" + b + ")");
208 }
209
210 /**
211  * Add random number to url to stop IE from caching
212  *
213  * @example url("data/test.html")
214  * @result "data/test.html?10538358428943"
215  *
216  * @example url("data/test.php?foo=bar")
217  * @result "data/test.php?foo=bar&10538358345554"
218  */
219 function url(value) {
220         return value + (/\?/.test(value) ? "&" : "?") + new Date().getTime() + "" + parseInt(Math.random()*100000);
221 }
222
223 /**
224  * Checks that the first two arguments are equal, with an optional message.
225  * Prints out both expected and actual values on failure.
226  *
227  * Prefered to ok( expected == actual, message )
228  *
229  * @example equals( "Expected 2 characters.", v.formatMessage("Expected {0} characters.", 2) );
230  *
231  * @param Object expected
232  * @param Object actual
233  * @param String message (optional)
234  */
235 function equals(expected, actual, message) {
236         var result = expected == actual;
237         message = message || result ? "okay" : "failed";
238         _config.Test.push( [ result, result ? message + ": " + expected : message + " expected: " + expected + " actual: " + actual ] );
239 }