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