304f938452dc1748978a7a81bbf9685be69e553e
[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(" - Disabled for Safari");
20         else
21                 runTest();      
22 });
23
24 function synchronize(callback) {
25         _config.queue[_config.queue.length] = callback;
26         if(!_config.blocking) {
27                 process();
28         }
29 }
30
31 function process() {
32         while(_config.queue.length && !_config.blocking) {
33                 var call = _config.queue[0];
34                 _config.queue = _config.queue.slice(1);
35                 call();
36         }
37 }
38
39 function stop(allowFailure) {
40         _config.blocking = true;
41         var handler = allowFailure ? start : function() {
42                 ok( false, "Test timed out" );
43                 start();
44         };
45         _config.timeout = setTimeout(handler, _config.asyncTimeout * 1000);
46 }
47 function start() {
48         if(_config.timeout)
49                 clearTimeout(_config.timeout);
50         _config.blocking = false;
51         process();
52 }
53
54 function runTest() {
55         _config.blocking = false;
56         var time = new Date();
57         _config.fixture = document.getElementById('main').innerHTML;
58         synchronize(function() {
59                 time = new Date() - time;
60                 $("<div>").html(['<p class="result">Tests completed in ',
61                         time, ' milliseconds.<br/>',
62                         _config.stats.bad, ' tests of ', _config.stats.all, ' failed.</p>']
63                         .join(''))
64                         .appendTo("body");
65                 $("#banner").addClass(_config.stats.bad ? "fail" : "pass");
66         });
67 }
68
69 function test(name, callback, nowait) {
70         // safari seems to have some memory problems, so we need to slow it down
71         if($.browser.safari && !nowait) {
72                 test("", function() {
73                         stop();
74                         setTimeout(start, 250);
75                 }, true);
76         }
77
78         if(_config.currentModule)
79                 name = _config.currentModule + " module: " + name;
80                 
81         synchronize(function() {
82                 _config.Test = [];
83                 try {
84                         callback();
85                 } catch(e) {
86                         if( typeof console != "undefined" && console.error && console.warn ) {
87                                 console.error("Test " + name + " died, exception and test follows");
88                                 console.error(e);
89                                 console.warn(callback.toString());
90                         }
91                         _config.Test.push( [ false, "Died on test #" + (_config.Test.length+1) + ": " + e ] );
92                 }
93         });
94         synchronize(function() {
95                 reset();
96                 
97                 // don't output pause tests
98                 if(nowait) return;
99                 
100                 if(_config.expected && _config.expected != _config.Test.length) {
101                         _config.Test.push( [ false, "Expected " + _config.expected + " assertions, but " + _config.Test.length + " were run" ] );
102                 }
103                 _config.expected = null;
104                 
105                 var good = 0, bad = 0;
106                 var ol = document.createElement("ol");
107                 ol.style.display = "none";
108                 var li = "", state = "pass";
109                 for ( var i = 0; i < _config.Test.length; i++ ) {
110                         var li = document.createElement("li");
111                         li.className = _config.Test[i][0] ? "pass" : "fail";
112                         li.innerHTML = _config.Test[i][1];
113                         ol.appendChild( li );
114                         
115                         _config.stats.all++;
116                         if ( !_config.Test[i][0] ) {
117                                 state = "fail";
118                                 bad++;
119                                 _config.stats.bad++;
120                         } else good++;
121                 }
122         
123                 var li = document.createElement("li");
124                 li.className = state;
125         
126                 var b = document.createElement("b");
127                 b.innerHTML = name + " <b style='color:black;'>(<b class='fail'>" + bad + "</b>, <b class='pass'>" + good + "</b>, " + _config.Test.length + ")</b>";
128                 b.onclick = function(){
129                         var n = this.nextSibling;
130                         if ( jQuery.css( n, "display" ) == "none" )
131                                 n.style.display = "block";
132                         else
133                                 n.style.display = "none";
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 == 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 function serialArray( a ) {
187         var r = [];
188         for ( var i = 0; i < a.length; i++ ) {
189                 var str = a[i].nodeName;
190                 if ( str ) {
191                         str = str.toLowerCase();
192                         if ( a[i].id )
193                                 str += "#" + a[i].id;
194                 } else
195                         str = a[i];
196                 r.push( str );
197         }
198
199         return "[ " + r.join(", ") + " ]"
200 }
201
202 /**
203  * Returns an array of elements with the given IDs, eg.
204  * @example q("main", "foo", "bar")
205  * @result [<div id="main">, <span id="foo">, <input id="bar">]
206  */
207 function q() {
208         var r = [];
209         for ( var i = 0; i < arguments.length; i++ )
210                 r.push( document.getElementById( arguments[i] ) );
211         return r;
212 }
213
214 /**
215  * Asserts that a select matches the given IDs
216  * @example t("Check for something", "//[a]", ["foo", "baar"]);
217  * @result returns true if "//[a]" return two elements with the IDs 'foo' and 'baar'
218  */
219 function t(a,b,c) {
220         var f = jQuery(b);
221         var s = "";
222         for ( var i = 0; i < f.length; i++ )
223                 s += (s && ",") + '"' + f[i].id + '"';
224         isSet(f, q.apply(q,c), a + " (" + b + ")");
225 }
226
227 /**
228  * Add random number to url to stop IE from caching
229  *
230  * @example url("data/test.html")
231  * @result "data/test.html?10538358428943"
232  *
233  * @example url("data/test.php?foo=bar")
234  * @result "data/test.php?foo=bar&10538358345554"
235  */
236 function url(value) {
237         return value + (/\?/.test(value) ? "&" : "?") + new Date().getTime() + "" + parseInt(Math.random()*100000);
238 }
239
240 /**
241  * Checks that the first two arguments are equal, with an optional message.
242  * Prints out both expected and actual values on failure.
243  *
244  * Prefered to ok( expected == actual, message )
245  *
246  * @example equals( "Expected 2 characters.", v.formatMessage("Expected {0} characters.", 2) );
247  *
248  * @param Object expected
249  * @param Object actual
250  * @param String message (optional)
251  */
252 function equals(expected, actual, message) {
253         var result = expected == actual;
254         message = message || (result ? "okay" : "failed");
255         _config.Test.push( [ result, result ? message + ": " + expected : message + " expected: " + expected + " actual: " + actual ] );
256 }
257
258 /**
259  * Trigger an event on an element.
260  *
261  * @example triggerEvent( document.body, "click" );
262  *
263  * @param DOMElement elem
264  * @param String type
265  */
266 function triggerEvent( elem, type, event ) {
267         if ( jQuery.browser.mozilla ) {
268                 event = document.createEvent("MouseEvents");
269                 event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
270                         0, 0, 0, 0, 0, false, false, false, false, 0, null);
271                 elem.dispatchEvent( event );
272         } else if ( jQuery.browser.msie || jQuery.browser.opera ) {
273                 event = document.createEventObject();
274                 elem.fireEvent("on"+type, event);
275         }
276 }