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