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