tizen beta release
[framework/web/webkit-efl.git] / LayoutTests / http / tests / inspector / inspector-test.js
1 var initialize_InspectorTest = function() {
2
3 var results = [];
4 var resultsSynchronized = false;
5
6 function consoleOutputHook(messageType)
7 {
8     InspectorTest.addResult(messageType + ": " + Array.prototype.slice.call(arguments, 1));
9 }
10
11 console.log = consoleOutputHook.bind(InspectorTest, "log");
12 console.error = consoleOutputHook.bind(InspectorTest, "error");
13 console.info = consoleOutputHook.bind(InspectorTest, "info");
14
15 InspectorTest.completeTest = function()
16 {
17     function testDispatchQueueIsEmpty() {
18         if (!WebInspector.dispatchQueueIsEmpty()) {
19             // Wait for unprocessed messages.
20             setTimeout(testDispatchQueueIsEmpty, 10);
21             return;
22         }
23         RuntimeAgent.evaluate("didEvaluateForTestInFrontend(" + InspectorTest.completeTestCallId + ", \"\")", "test");
24     }
25     testDispatchQueueIsEmpty();
26 }
27
28 InspectorTest.evaluateInConsole = function(code, callback)
29 {
30     callback = InspectorTest.safeWrap(callback);
31
32     WebInspector.consoleView.visible = true;
33     WebInspector.consoleView.prompt.text = code;
34     var event = document.createEvent("KeyboardEvent");
35     event.initKeyboardEvent("keydown", true, true, null, "Enter", "");
36     WebInspector.consoleView.prompt.proxyElement.dispatchEvent(event);
37     InspectorTest.addConsoleSniffer(
38         function(commandResult) {
39             callback(commandResult.toMessageElement().textContent);
40         });
41 }
42
43 InspectorTest.evaluateInConsoleAndDump = function(code, callback)
44 {
45     callback = InspectorTest.safeWrap(callback);
46
47     function mycallback(text)
48     {
49         InspectorTest.addResult(code + " = " + text);
50         callback(text);
51     }
52     InspectorTest.evaluateInConsole(code, mycallback);
53 }
54
55 InspectorTest.evaluateInPage = function(code, callback)
56 {
57     callback = InspectorTest.safeWrap(callback);
58
59     function mycallback(error, result, wasThrown)
60     {
61         if (!error)
62             callback(WebInspector.RemoteObject.fromPayload(result), wasThrown);
63     }
64     RuntimeAgent.evaluate(code, "console", false, mycallback);
65 }
66
67 InspectorTest.evaluateInPageWithTimeout = function(code)
68 {
69     InspectorTest.evaluateInPage("setTimeout(unescape('" + escape(code) + "'))");
70 }
71
72 InspectorTest.addResult = function(text)
73 {
74     results.push(text);
75     if (resultsSynchronized)
76         addResultToPage(text);
77     else {
78         clearResults();
79         for (var i = 0; i < results.length; ++i)
80             addResultToPage(results[i]);
81         resultsSynchronized = true;
82     }
83
84     function clearResults()
85     {
86         InspectorTest.evaluateInPage("clearOutput()");
87     }
88
89     function addResultToPage(text)
90     {
91         InspectorTest.evaluateInPage("output(unescape('" + escape(text) + "'))");
92     }
93 }
94
95 InspectorTest.addResults = function(textArray)
96 {
97     if (!textArray)
98         return;
99     for (var i = 0, size = textArray.length; i < size; ++i)
100         InspectorTest.addResult(textArray[i]);
101 }
102
103 function onError(event)
104 {
105     window.removeEventListener("error", onError);
106     InspectorTest.addResult("Uncaught exception in inspector front-end: " + event.message + " [" + event.filename + ":" + event.lineno + "]");
107     InspectorTest.completeTest();
108 }
109
110 window.addEventListener("error", onError);
111
112 InspectorTest.addObject = function(object, nondeterministicProps, prefix, firstLinePrefix)
113 {
114     prefix = prefix || "";
115     firstLinePrefix = firstLinePrefix || prefix;
116     InspectorTest.addResult(firstLinePrefix + "{");
117     for (var prop in object) {
118         if (typeof object.hasOwnProperty === "function" && !object.hasOwnProperty(prop))
119             continue;
120         var prefixWithName = "    " + prefix + prop + " : ";
121         var propValue = object[prop];
122         if (nondeterministicProps && prop in nondeterministicProps)
123             InspectorTest.addResult(prefixWithName + "<" + typeof propValue + ">");
124         else
125             InspectorTest.dump(propValue, nondeterministicProps, "    " + prefix, prefixWithName);
126     }
127     InspectorTest.addResult(prefix + "}");
128 }
129
130 InspectorTest.addArray = function(array, nondeterministicProps, prefix, firstLinePrefix)
131 {
132     prefix = prefix || "";
133     firstLinePrefix = firstLinePrefix || prefix;
134     InspectorTest.addResult(firstLinePrefix + "[");
135     for (var i = 0; i < array.length; ++i)
136         InspectorTest.dump(array[i], nondeterministicProps, prefix + "    ");
137     InspectorTest.addResult(prefix + "]");
138 }
139
140 InspectorTest.dump = function(value, nondeterministicProps, prefix, prefixWithName)
141 {
142     prefixWithName = prefixWithName || prefix;
143     if (prefixWithName && prefixWithName.length > 80) {
144         InspectorTest.addResult(prefixWithName + "was skipped due to prefix length limit");
145         return;
146     }
147     if (value === null)
148         InspectorTest.addResult(prefixWithName + "null");
149     else if (value instanceof Array)
150         InspectorTest.addArray(value, nondeterministicProps, prefix, prefixWithName);
151     else if (typeof value === "object")
152         InspectorTest.addObject(value, nondeterministicProps, prefix, prefixWithName);
153     else if (typeof value === "string")
154         InspectorTest.addResult(prefixWithName + "\"" + value + "\"");
155     else
156         InspectorTest.addResult(prefixWithName + value);
157 }
158
159 InspectorTest.assertGreaterOrEqual = function(expected, actual, message)
160 {
161     if (actual < expected)
162         InspectorTest.addResult("FAILED: " + (message ? message + ": " : "") + actual + " < " + expected);
163 }
164
165 InspectorTest.navigate = function(url, callback)
166 {
167     InspectorTest._pageLoadedCallback = InspectorTest.safeWrap(callback);
168
169     if (WebInspector.panels.network)
170         WebInspector.panels.network._reset();
171     InspectorTest.evaluateInConsole("window.location = '" + url + "'");
172 }
173
174 InspectorTest.reloadPage = function(callback)
175 {
176     InspectorTest._pageLoadedCallback = InspectorTest.safeWrap(callback);
177
178     if (WebInspector.panels.network)
179         WebInspector.panels.network._reset();
180     PageAgent.reload(false);
181 }
182
183 InspectorTest.pageLoaded = function()
184 {
185     resultsSynchronized = false;
186     InspectorTest.addResult("Page reloaded.");
187     if (InspectorTest._pageLoadedCallback) {
188         var callback = InspectorTest._pageLoadedCallback;
189         delete InspectorTest._pageLoadedCallback;
190         callback();
191     }
192 }
193
194 InspectorTest.runWhenPageLoads = function(callback)
195 {
196     var oldCallback = InspectorTest._pageLoadedCallback;
197     function chainedCallback()
198     {
199         if (oldCallback)
200             oldCallback();
201         callback();
202     }
203     InspectorTest._pageLoadedCallback = InspectorTest.safeWrap(chainedCallback);
204 }
205
206 InspectorTest.runAfterPendingDispatches = function(callback)
207 {
208     callback = InspectorTest.safeWrap(callback);
209     InspectorBackend.runAfterPendingDispatches(callback);
210 }
211
212 InspectorTest.createKeyEvent = function(keyIdentifier, ctrlKey, altKey, shiftKey, metaKey)
213 {
214     var evt = document.createEvent("KeyboardEvent");
215     evt.initKeyboardEvent("keydown", true /* can bubble */, true /* can cancel */, null /* view */, keyIdentifier, "", ctrlKey, altKey, shiftKey, metaKey);
216     return evt;
217 }
218
219 InspectorTest.runTestSuite = function(testSuite)
220 {
221     var testSuiteTests = testSuite.slice();
222
223     function runner()
224     {
225         if (!testSuiteTests.length) {
226             InspectorTest.completeTest();
227             return;
228         }
229         var nextTest = testSuiteTests.shift();
230         InspectorTest.addResult("");
231         InspectorTest.addResult("Running: " + /function\s([^(]*)/.exec(nextTest)[1]);
232         InspectorTest.safeWrap(nextTest)(runner, runner);
233     }
234     runner();
235 }
236
237 InspectorTest.assertEquals = function(expected, found, message)
238 {
239     if (expected === found)
240         return;
241
242     var error;
243     if (message)
244         error = "Failure (" + message + "):";
245     else
246         error = "Failure:";
247     throw new Error(error + " expected <" + expected + "> found <" + found + ">");
248 }
249
250 InspectorTest.assertTrue = function(found, message)
251 {
252     InspectorTest.assertEquals(true, !!found, message);
253 }
254
255 InspectorTest.safeWrap = function(func, onexception)
256 {
257     function result()
258     {
259         if (!func)
260             return;
261         var wrapThis = this;
262         try {
263             return func.apply(wrapThis, arguments);
264         } catch(e) {
265             InspectorTest.addResult("Exception while running: " + func + "\n" + (e.stack || e));
266             if (onexception)
267                 InspectorTest.safeWrap(onexception)();
268             else
269                 InspectorTest.completeTest();
270         }
271     }
272     return result;
273 }
274
275 InspectorTest.addSniffer = function(receiver, methodName, override, opt_sticky)
276 {
277     override = InspectorTest.safeWrap(override);
278
279     var original = receiver[methodName];
280     if (typeof original !== "function")
281         throw ("Cannot find method to override: " + methodName);
282
283     receiver[methodName] = function(var_args) {
284         try {
285             var result = original.apply(this, arguments);
286         } finally {
287             if (!opt_sticky)
288                 receiver[methodName] = original;
289         }
290         // In case of exception the override won't be called.
291         try {
292             override.apply(this, arguments);
293         } catch (e) {
294             throw ("Exception in overriden method '" + methodName + "': " + e);
295         }
296         return result;
297     };
298 }
299
300 InspectorTest.addConsoleSniffer = function(override, opt_sticky)
301 {
302     InspectorTest.addSniffer(WebInspector.ConsoleView.prototype, "_appendConsoleMessage", override, opt_sticky);
303 }
304
305 InspectorTest.override = function(receiver, methodName, override, opt_sticky)
306 {
307     override = InspectorTest.safeWrap(override);
308
309     var original = receiver[methodName];
310     if (typeof original !== "function")
311         throw ("Cannot find method to override: " + methodName);
312
313     receiver[methodName] = function(var_args) {
314         try {
315             try {
316                 var result = override.apply(this, arguments);
317             } catch (e) {
318                 throw ("Exception in overriden method '" + methodName + "': " + e);
319             }
320         } finally {
321             if (!opt_sticky)
322                 receiver[methodName] = original;
323         }
324         return result;
325     };
326
327     return original;
328 }
329
330 InspectorTest.textContentWithLineBreaks = function(node)
331 {
332     var buffer = "";
333     var currentNode = node;
334     while (currentNode = currentNode.traverseNextNode(node)) {
335         if (currentNode.nodeType === Node.TEXT_NODE)
336             buffer += currentNode.nodeValue;
337         else if (currentNode.nodeName === "LI")
338             buffer += "\n    ";
339         else if (currentNode.classList.contains("console-message"))
340             buffer += "\n\n";
341     }
342     return buffer;
343 }
344
345 };
346
347 var runTestCallId = 0;
348 var completeTestCallId = 1;
349 var frontendReopeningCount = 0;
350
351 function reopenFrontend()
352 {
353     closeFrontend(openFrontendAndIncrement);
354 }
355
356 function closeFrontend(callback)
357 {
358     // Do this asynchronously to allow InspectorBackendDispatcher to send response
359     // back to the frontend before it's destroyed.
360     setTimeout(function() {
361         layoutTestController.closeWebInspector();
362         callback();
363     }, 0);
364 }
365
366 function openFrontendAndIncrement()
367 {
368     frontendReopeningCount++;
369     layoutTestController.showWebInspector();
370     runTest();
371 }
372
373 function runAfterIframeIsLoaded()
374 {
375     if (window.layoutTestController)
376         layoutTestController.waitUntilDone();
377     function step()
378     {
379         if (!window.iframeLoaded)
380             setTimeout(step, 100);
381         else
382             runTest();
383     }
384     setTimeout(step, 100);
385 }
386
387 function runTest(enableWatchDogWhileDebugging)
388 {
389     if (!window.layoutTestController)
390         return;
391
392     layoutTestController.dumpAsText();
393     layoutTestController.waitUntilDone();
394
395     function runTestInFrontend(initializationFunctions, testFunction, completeTestCallId)
396     {
397         if (window.InspectorTest) {
398             InspectorTest.pageLoaded();
399             return;
400         }
401
402         InspectorTest = {};
403         InspectorTest.completeTestCallId = completeTestCallId;
404
405         for (var i = 0; i < initializationFunctions.length; ++i) {
406             try {
407                 initializationFunctions[i]();
408             } catch (e) {
409                 console.error("Exception in test initialization: " + e);
410                 InspectorTest.completeTest();
411             }
412         }
413
414         WebInspector.showPanel("audits");
415         try {
416             testFunction();
417         } catch (e) {
418             console.error("Exception during test execution: " + e);
419             InspectorTest.completeTest();
420         }
421     }
422
423     var initializationFunctions = [ String(initialize_InspectorTest) ];
424     for (var name in window) {
425         if (name.indexOf("initialize_") === 0 && typeof window[name] === "function" && name !== "initialize_InspectorTest")
426             initializationFunctions.push(window[name].toString());
427     }
428     var parameters = ["[" + initializationFunctions + "]", test, completeTestCallId];
429     var toEvaluate = "(" + runTestInFrontend + ")(" + parameters.join(", ") + ");";
430     layoutTestController.evaluateInWebInspector(runTestCallId, toEvaluate);
431
432     if (enableWatchDogWhileDebugging) {
433         function watchDog()
434         {
435             console.log("Internal watchdog triggered at 20 seconds. Test timed out.");
436             closeInspectorAndNotifyDone();
437         }
438         window._watchDogTimer = setTimeout(watchDog, 20000);
439     }
440 }
441
442 function didEvaluateForTestInFrontend(callId)
443 {
444     if (callId !== completeTestCallId)
445         return;
446     delete window.completeTestCallId;
447     // Close inspector asynchrously to allow caller of this
448     // function send response before backend dispatcher and frontend are destroyed.
449     setTimeout(closeInspectorAndNotifyDone, 0);
450 }
451
452 function closeInspectorAndNotifyDone()
453 {
454     if (window._watchDogTimer)
455         clearTimeout(window._watchDogTimer);
456
457     layoutTestController.closeWebInspector();
458     setTimeout(function() {
459         layoutTestController.notifyDone();
460     }, 0);
461 }
462
463 var outputElement;
464
465 function output(text)
466 {
467     if (!outputElement) {
468         var intermediate = document.createElement("div");
469         document.body.appendChild(intermediate);
470
471         var intermediate2 = document.createElement("div");
472         intermediate.appendChild(intermediate2);
473
474         outputElement = document.createElement("div");
475         outputElement.className = "output";
476         outputElement.style.whiteSpace = "pre";
477         intermediate2.appendChild(outputElement);
478     }
479     outputElement.appendChild(document.createTextNode(text));
480     outputElement.appendChild(document.createElement("br"));
481 }
482
483 function clearOutput()
484 {
485     if (outputElement) {
486         outputElement.parentNode.removeChild(outputElement);
487         outputElement = null;
488     }
489 }