test runner: when errors are thrown in a test, the message is successfully show on...
[jquery.git] / 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 _config.filters = location.search.length > 1 && //restrict modules/tests by get parameters
17                 $.map( location.search.slice(1).split('&'), decodeURIComponent );
18
19 var isLocal = !!(window.location.protocol == 'file:');
20
21 $(function() {
22         $('#userAgent').html(navigator.userAgent);
23         runTest();      
24 });
25
26 function synchronize(callback) {
27         _config.queue[_config.queue.length] = callback;
28         if(!_config.blocking) {
29                 process();
30         }
31 }
32
33 function process() {
34         while(_config.queue.length && !_config.blocking) {
35                 var call = _config.queue[0];
36                 _config.queue = _config.queue.slice(1);
37                 call();
38         }
39 }
40
41 function stop(allowFailure) {
42         _config.blocking = true;
43         var handler = allowFailure ? start : function() {
44                 ok( false, "Test timed out" );
45                 start();
46         };
47         // Disabled, caused too many random errors
48         //_config.timeout = setTimeout(handler, _config.asyncTimeout * 1000);
49 }
50 function start() {
51         // A slight delay, to avoid any current callbacks
52         setTimeout(function(){
53                 if(_config.timeout)
54                         clearTimeout(_config.timeout);
55                 _config.blocking = false;
56                 process();
57         }, 13);
58 }
59
60 function validTest( name ) {
61         var filters = _config.filters;
62         if( !filters )
63                 return true;
64
65         var i = filters.length,
66                 run = false;
67         while( i-- ){
68                 var filter = filters[i],
69                         not = filter.charAt(0) == '!';
70                 if( not ) 
71                         filter = filter.slice(1);
72                 if( name.indexOf(filter) != -1 )
73                         return !not;
74                 if( not )
75                         run = true;
76         }
77         return run;
78 }
79
80 function runTest() {
81         _config.blocking = false;
82         var time = new Date();
83         _config.fixture = document.getElementById('main').innerHTML;
84         _config.ajaxSettings = $.ajaxSettings;
85         synchronize(function() {
86                 time = new Date() - time;
87                 $("<div>").html(['<p class="result">Tests completed in ',
88                         time, ' milliseconds.<br/>',
89                         _config.stats.bad, ' tests of ', _config.stats.all, ' failed.</p>']
90                         .join(''))
91                         .appendTo("body");
92                 $("#banner").addClass(_config.stats.bad ? "fail" : "pass");
93         });
94 }
95
96 function test(name, callback, nowait) {
97         if(_config.currentModule)
98                 name = _config.currentModule + " module: " + name;
99                 
100         if ( !validTest(name) )
101                 return;
102                 
103         synchronize(function() {
104                 _config.Test = [];
105                 try {
106                         callback();
107                 } catch(e) {
108                         if( typeof console != "undefined" && console.error && console.warn ) {
109                                 console.error("Test " + name + " died, exception and test follows");
110                                 console.error(e);
111                                 console.warn(callback.toString());
112                         }
113                         _config.Test.push( [ false, "Died on test #" + (_config.Test.length+1) + ": " + e.message ] );
114                 }
115         });
116         synchronize(function() {
117                 reset();
118                 
119                 // don't output pause tests
120                 if(nowait) return;
121                 
122                 if(_config.expected && _config.expected != _config.Test.length) {
123                         _config.Test.push( [ false, "Expected " + _config.expected + " assertions, but " + _config.Test.length + " were run" ] );
124                 }
125                 _config.expected = null;
126                 
127                 var good = 0, bad = 0;
128                 var ol = document.createElement("ol");
129                 ol.style.display = "none";
130                 var li = "", state = "pass";
131                 for ( var i = 0; i < _config.Test.length; i++ ) {
132                         var li = document.createElement("li");
133                         li.className = _config.Test[i][0] ? "pass" : "fail";
134                         li.innerHTML = _config.Test[i][1];
135                         ol.appendChild( li );
136                         
137                         _config.stats.all++;
138                         if ( !_config.Test[i][0] ) {
139                                 state = "fail";
140                                 bad++;
141                                 _config.stats.bad++;
142                         } else good++;
143                 }
144         
145                 var li = document.createElement("li");
146                 li.className = state;
147         
148                 var b = document.createElement("strong");
149                 b.innerHTML = name + " <b style='color:black;'>(<b class='fail'>" + bad + "</b>, <b class='pass'>" + good + "</b>, " + _config.Test.length + ")</b>";
150                 b.onclick = function(){
151                         var n = this.nextSibling;
152                         if ( jQuery.css( n, "display" ) == "none" )
153                                 n.style.display = "block";
154                         else
155                                 n.style.display = "none";
156                 };
157                 $(b).dblclick(function(event) {
158                         var target = jQuery(event.target).filter("strong").clone();
159                         if ( target.length ) {
160                                 target.children().remove();
161                                 location.href = location.href.match(/^(.+?)(\?.*)?$/)[1] + "?" + encodeURIComponent($.trim(target.text()));
162                         }
163                 });
164                 li.appendChild( b );
165                 li.appendChild( ol );
166         
167                 document.getElementById("tests").appendChild( li );             
168         });
169 }
170
171 // call on start of module test to prepend name to all tests
172 function module(moduleName) {
173         _config.currentModule = moduleName;
174 }
175
176 /**
177  * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
178  */
179 function expect(asserts) {
180         _config.expected = asserts;
181 }
182
183 /**
184  * Resets the test setup. Useful for tests that modify the DOM.
185  */
186 function reset() {
187         $("#main").html( _config.fixture );
188         $.event.global = {};
189         $.ajaxSettings = $.extend({}, _config.ajaxSettings);
190 }
191
192 /**
193  * Asserts true.
194  * @example ok( $("a").size() > 5, "There must be at least 5 anchors" );
195  */
196 function ok(a, msg) {
197         _config.Test.push( [ !!a, msg ] );
198 }
199
200 /**
201  * Asserts that two arrays are the same
202  */
203 function isSet(a, b, msg) {
204         var ret = true;
205         if ( a && b && a.length != undefined && a.length == b.length ) {
206                 for ( var i = 0; i < a.length; i++ )
207                         if ( a[i] != b[i] )
208                                 ret = false;
209         } else
210                 ret = false;
211         if ( !ret )
212                 _config.Test.push( [ ret, msg + " expected: " + serialArray(b) + " result: " + serialArray(a) ] );
213         else 
214                 _config.Test.push( [ ret, msg ] );
215 }
216
217 /**
218  * Asserts that two objects are equivalent
219  */
220 function isObj(a, b, msg) {
221         var ret = true;
222         
223         if ( a && b ) {
224                 for ( var i in a )
225                         if ( a[i] != b[i] )
226                                 ret = false;
227
228                 for ( i in b )
229                         if ( a[i] != b[i] )
230                                 ret = false;
231         } else
232                 ret = false;
233
234     _config.Test.push( [ ret, msg ] );
235 }
236
237 function serialArray( a ) {
238         var r = [];
239         
240         if ( a && a.length )
241         for ( var i = 0; i < a.length; i++ ) {
242             var str = a[i].nodeName;
243             if ( str ) {
244                 str = str.toLowerCase();
245                 if ( a[i].id )
246                     str += "#" + a[i].id;
247             } else
248                 str = a[i];
249             r.push( str );
250         }
251
252         return "[ " + r.join(", ") + " ]";
253 }
254
255 /**
256  * Returns an array of elements with the given IDs, eg.
257  * @example q("main", "foo", "bar")
258  * @result [<div id="main">, <span id="foo">, <input id="bar">]
259  */
260 function q() {
261         var r = [];
262         for ( var i = 0; i < arguments.length; i++ )
263                 r.push( document.getElementById( arguments[i] ) );
264         return r;
265 }
266
267 /**
268  * Asserts that a select matches the given IDs
269  * @example t("Check for something", "//[a]", ["foo", "baar"]);
270  * @result returns true if "//[a]" return two elements with the IDs 'foo' and 'baar'
271  */
272 function t(a,b,c) {
273         var f = jQuery(b);
274         var s = "";
275         for ( var i = 0; i < f.length; i++ )
276                 s += (s && ",") + '"' + f[i].id + '"';
277         isSet(f, q.apply(q,c), a + " (" + b + ")");
278 }
279
280 /**
281  * Add random number to url to stop IE from caching
282  *
283  * @example url("data/test.html")
284  * @result "data/test.html?10538358428943"
285  *
286  * @example url("data/test.php?foo=bar")
287  * @result "data/test.php?foo=bar&10538358345554"
288  */
289 function url(value) {
290         return value + (/\?/.test(value) ? "&" : "?") + new Date().getTime() + "" + parseInt(Math.random()*100000);
291 }
292
293 /**
294  * Checks that the first two arguments are equal, with an optional message.
295  * Prints out both expected and actual values on failure.
296  *
297  * Prefered to ok( expected == actual, message )
298  *
299  * @example equals( "Expected 2 characters.", v.formatMessage("Expected {0} characters.", 2) );
300  *
301  * @param Object actual
302  * @param Object expected
303  * @param String message (optional)
304  */
305 function equals(actual, expected, message) {
306         var result = expected == actual;
307         message = message || (result ? "okay" : "failed");
308         _config.Test.push( [ result, result ? message + ": " + expected : message + " expected: " + expected + " actual: " + actual ] );
309 }
310
311 /**
312  * Trigger an event on an element.
313  *
314  * @example triggerEvent( document.body, "click" );
315  *
316  * @param DOMElement elem
317  * @param String type
318  */
319 function triggerEvent( elem, type, event ) {
320         if ( jQuery.browser.mozilla || jQuery.browser.opera ) {
321                 event = document.createEvent("MouseEvents");
322                 event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
323                         0, 0, 0, 0, 0, false, false, false, false, 0, null);
324                 elem.dispatchEvent( event );
325         } else if ( jQuery.browser.msie ) {
326                 elem.fireEvent("on"+type);
327         }
328 }