Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / 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 console.assert = function(condition, object)
15 {
16     if (condition)
17         return;
18     var message = "Assertion failed: " + (typeof object !== "undefined" ? object : "");
19     InspectorTest.addResult(new Error(message).stack);
20 }
21
22 InspectorTest.Output = {   // override in window.initialize_yourName
23     testComplete: function() 
24     {
25         RuntimeAgent.evaluate("didEvaluateForTestInFrontend(" + InspectorTest.completeTestCallId + ", \"\")", "test");
26     },
27
28     addResult: function(text) 
29     {
30         InspectorTest.evaluateInPage("output(unescape('" + escape(text) + "'))");
31     },
32     
33     clearResults: function() 
34     {
35         InspectorTest.evaluateInPage("clearOutput()");
36     }
37 };
38
39 InspectorTest.completeTest = function()
40 {
41     function testDispatchQueueIsEmpty() {
42         if (!WebInspector.dispatchQueueIsEmpty()) {
43             // Wait for unprocessed messages.
44             setTimeout(testDispatchQueueIsEmpty, 10);
45             return;
46         }
47         InspectorTest.Output.testComplete();
48     }
49     testDispatchQueueIsEmpty();
50 }
51
52 InspectorTest.evaluateInConsole = function(code, callback)
53 {
54     callback = InspectorTest.safeWrap(callback);
55
56     WebInspector.consoleView.visible = true;
57     WebInspector.consoleView.prompt.text = code;
58     var event = document.createEvent("KeyboardEvent");
59     event.initKeyboardEvent("keydown", true, true, null, "Enter", "");
60     WebInspector.consoleView.prompt.proxyElement.dispatchEvent(event);
61     InspectorTest.addConsoleSniffer(
62         function(commandResult) {
63             callback(commandResult.toMessageElement().textContent);
64         });
65 }
66
67 InspectorTest.evaluateInConsoleAndDump = function(code, callback)
68 {
69     callback = InspectorTest.safeWrap(callback);
70
71     function mycallback(text)
72     {
73         InspectorTest.addResult(code + " = " + text);
74         callback(text);
75     }
76     InspectorTest.evaluateInConsole(code, mycallback);
77 }
78
79 InspectorTest.evaluateInPage = function(code, callback)
80 {
81     callback = InspectorTest.safeWrap(callback);
82
83     function mycallback(error, result, wasThrown)
84     {
85         if (!error)
86             callback(WebInspector.RemoteObject.fromPayload(result), wasThrown);
87     }
88     RuntimeAgent.evaluate(code, "console", false, mycallback);
89 }
90
91 InspectorTest.evaluateInPageWithTimeout = function(code)
92 {
93     InspectorTest.evaluateInPage("setTimeout(unescape('" + escape(code) + "'))");
94 }
95
96 InspectorTest.check = function(passCondition, failureText)
97 {
98     if (!passCondition)
99         InspectorTest.addResult("FAIL: " + failureText);
100 }
101
102 InspectorTest.addResult = function(text)
103 {
104     results.push(text);
105     if (resultsSynchronized)
106         InspectorTest.Output.addResult(text);
107     else {
108         InspectorTest.Output.clearResults();
109         for (var i = 0; i < results.length; ++i)
110             InspectorTest.Output.addResult(results[i]);
111         resultsSynchronized = true;
112     }
113 }
114
115 InspectorTest.addResults = function(textArray)
116 {
117     if (!textArray)
118         return;
119     for (var i = 0, size = textArray.length; i < size; ++i)
120         InspectorTest.addResult(textArray[i]);
121 }
122
123 function onError(event)
124 {
125     window.removeEventListener("error", onError);
126     InspectorTest.addResult("Uncaught exception in inspector front-end: " + event.message + " [" + event.filename + ":" + event.lineno + "]");
127     InspectorTest.completeTest();
128 }
129
130 window.addEventListener("error", onError);
131
132 InspectorTest.formatters = {};
133
134 InspectorTest.formatters.formatAsTypeName = function(value)
135 {
136     return "<" + typeof value + ">";
137 }
138
139 InspectorTest.formatters.formatAsRecentTime = function(value)
140 {
141     if (typeof value !== "object" || !(value instanceof Date))
142         return InspectorTest.formatAsTypeName(value);
143     var delta = Date.now() - value;
144     return 0 <= delta && delta < 30 * 60 * 1000 ? "<plausible>" : value;
145 }
146
147 InspectorTest.formatters.formatAsURL = function(value)
148 {
149     if (!value)
150         return value;
151     var lastIndex = value.lastIndexOf("inspector/");
152     if (lastIndex < 0)
153         return value;
154     return ".../" + value.substr(lastIndex);
155 }
156
157 InspectorTest.addObject = function(object, customFormatters, prefix, firstLinePrefix)
158 {
159     prefix = prefix || "";
160     firstLinePrefix = firstLinePrefix || prefix;
161     InspectorTest.addResult(firstLinePrefix + "{");
162     var propertyNames = Object.keys(object);
163     propertyNames.sort();
164     for (var i = 0; i < propertyNames.length; ++i) {
165         var prop = propertyNames[i];
166         if (typeof object.hasOwnProperty === "function" && !object.hasOwnProperty(prop))
167             continue;
168         var prefixWithName = "    " + prefix + prop + " : ";
169         var propValue = object[prop];
170         if (customFormatters && customFormatters[prop]) {
171             var formatterName = customFormatters[prop];
172             if (formatterName !== "skip") {
173                 var formatter = InspectorTest.formatters[formatterName];
174                 InspectorTest.addResult(prefixWithName + formatter(propValue));
175             }
176         } else
177             InspectorTest.dump(propValue, customFormatters, "    " + prefix, prefixWithName);
178     }
179     InspectorTest.addResult(prefix + "}");
180 }
181
182 InspectorTest.addArray = function(array, customFormatters, prefix, firstLinePrefix)
183 {
184     prefix = prefix || "";
185     firstLinePrefix = firstLinePrefix || prefix;
186     InspectorTest.addResult(firstLinePrefix + "[");
187     for (var i = 0; i < array.length; ++i)
188         InspectorTest.dump(array[i], customFormatters, prefix + "    ");
189     InspectorTest.addResult(prefix + "]");
190 }
191
192 InspectorTest.dump = function(value, customFormatters, prefix, prefixWithName)
193 {
194     prefixWithName = prefixWithName || prefix;
195     if (prefixWithName && prefixWithName.length > 80) {
196         InspectorTest.addResult(prefixWithName + "was skipped due to prefix length limit");
197         return;
198     }
199     if (value === null)
200         InspectorTest.addResult(prefixWithName + "null");
201     else if (value instanceof Array)
202         InspectorTest.addArray(value, customFormatters, prefix, prefixWithName);
203     else if (typeof value === "object")
204         InspectorTest.addObject(value, customFormatters, prefix, prefixWithName);
205     else if (typeof value === "string")
206         InspectorTest.addResult(prefixWithName + "\"" + value + "\"");
207     else
208         InspectorTest.addResult(prefixWithName + value);
209 }
210
211 InspectorTest.assertGreaterOrEqual = function(a, b, message)
212 {
213     if (a < b)
214         InspectorTest.addResult("FAILED: " + (message ? message + ": " : "") + a + " < " + b);
215 }
216
217 InspectorTest.navigate = function(url, callback)
218 {
219     InspectorTest._pageLoadedCallback = InspectorTest.safeWrap(callback);
220
221     WebInspector.panel("network")._reset();
222     InspectorTest.evaluateInConsole("window.location = '" + url + "'");
223 }
224
225 InspectorTest.recordNetwork = function()
226 {
227     WebInspector.panel("network")._networkLogView._recordButton.toggled = true;
228 }
229
230 InspectorTest.hardReloadPage = function(callback, scriptToEvaluateOnLoad, scriptPreprocessor)
231 {
232     InspectorTest._innerReloadPage(true, callback, scriptToEvaluateOnLoad, scriptPreprocessor);
233 }
234
235 InspectorTest.reloadPage = function(callback, scriptToEvaluateOnLoad, scriptPreprocessor)
236 {
237     InspectorTest._innerReloadPage(false, callback, scriptToEvaluateOnLoad, scriptPreprocessor);
238 }
239
240 InspectorTest._innerReloadPage = function(hardReload, callback, scriptToEvaluateOnLoad, scriptPreprocessor)
241 {
242     InspectorTest._pageLoadedCallback = InspectorTest.safeWrap(callback);
243
244     if (WebInspector.panels.network)
245         WebInspector.panels.network._reset();
246     PageAgent.reload(hardReload, scriptToEvaluateOnLoad, scriptPreprocessor);
247 }
248
249 InspectorTest.pageLoaded = function()
250 {
251     resultsSynchronized = false;
252     InspectorTest.addResult("Page reloaded.");
253     if (InspectorTest._pageLoadedCallback) {
254         var callback = InspectorTest._pageLoadedCallback;
255         delete InspectorTest._pageLoadedCallback;
256         callback();
257     }
258 }
259
260 InspectorTest.runWhenPageLoads = function(callback)
261 {
262     var oldCallback = InspectorTest._pageLoadedCallback;
263     function chainedCallback()
264     {
265         if (oldCallback)
266             oldCallback();
267         callback();
268     }
269     InspectorTest._pageLoadedCallback = InspectorTest.safeWrap(chainedCallback);
270 }
271
272 InspectorTest.runAfterPendingDispatches = function(callback)
273 {
274     callback = InspectorTest.safeWrap(callback);
275     InspectorBackend.runAfterPendingDispatches(callback);
276 }
277
278 InspectorTest.createKeyEvent = function(keyIdentifier, ctrlKey, altKey, shiftKey, metaKey)
279 {
280     var evt = document.createEvent("KeyboardEvent");
281     evt.initKeyboardEvent("keydown", true /* can bubble */, true /* can cancel */, null /* view */, keyIdentifier, "", ctrlKey, altKey, shiftKey, metaKey);
282     return evt;
283 }
284
285 InspectorTest.runTestSuite = function(testSuite)
286 {
287     var testSuiteTests = testSuite.slice();
288
289     function runner()
290     {
291         if (!testSuiteTests.length) {
292             InspectorTest.completeTest();
293             return;
294         }
295         var nextTest = testSuiteTests.shift();
296         InspectorTest.addResult("");
297         InspectorTest.addResult("Running: " + /function\s([^(]*)/.exec(nextTest)[1]);
298         InspectorTest.safeWrap(nextTest)(runner, runner);
299     }
300     runner();
301 }
302
303 InspectorTest.assertEquals = function(expected, found, message)
304 {
305     if (expected === found)
306         return;
307
308     var error;
309     if (message)
310         error = "Failure (" + message + "):";
311     else
312         error = "Failure:";
313     throw new Error(error + " expected <" + expected + "> found <" + found + ">");
314 }
315
316 InspectorTest.assertTrue = function(found, message)
317 {
318     InspectorTest.assertEquals(true, !!found, message);
319 }
320
321 InspectorTest.safeWrap = function(func, onexception)
322 {
323     function result()
324     {
325         if (!func)
326             return;
327         var wrapThis = this;
328         try {
329             return func.apply(wrapThis, arguments);
330         } catch(e) {
331             InspectorTest.addResult("Exception while running: " + func + "\n" + (e.stack || e));
332             if (onexception)
333                 InspectorTest.safeWrap(onexception)();
334             else
335                 InspectorTest.completeTest();
336         }
337     }
338     return result;
339 }
340
341 InspectorTest.addSniffer = function(receiver, methodName, override, opt_sticky)
342 {
343     override = InspectorTest.safeWrap(override);
344
345     var original = receiver[methodName];
346     if (typeof original !== "function")
347         throw ("Cannot find method to override: " + methodName);
348
349     receiver[methodName] = function(var_args) {
350         try {
351             var result = original.apply(this, arguments);
352         } finally {
353             if (!opt_sticky)
354                 receiver[methodName] = original;
355         }
356         // In case of exception the override won't be called.
357         try {
358             Array.prototype.push.call(arguments, result);
359             override.apply(this, arguments);
360         } catch (e) {
361             throw ("Exception in overriden method '" + methodName + "': " + e);
362         }
363         return result;
364     };
365 }
366
367 InspectorTest.addConsoleSniffer = function(override, opt_sticky)
368 {
369     var sniffer = function (messageIndex) {
370         var message = WebInspector.console.messages[messageIndex];
371         override(message);
372     };
373
374     InspectorTest.addSniffer(WebInspector.ConsoleView.prototype, "_showConsoleMessage", sniffer, opt_sticky);
375 }
376
377 InspectorTest.override = function(receiver, methodName, override, opt_sticky)
378 {
379     override = InspectorTest.safeWrap(override);
380
381     var original = receiver[methodName];
382     if (typeof original !== "function")
383         throw ("Cannot find method to override: " + methodName);
384
385     receiver[methodName] = function(var_args) {
386         try {
387             try {
388                 var result = override.apply(this, arguments);
389             } catch (e) {
390                 throw ("Exception in overriden method '" + methodName + "': " + e);
391             }
392         } finally {
393             if (!opt_sticky)
394                 receiver[methodName] = original;
395         }
396         return result;
397     };
398
399     return original;
400 }
401
402 InspectorTest.textContentWithLineBreaks = function(node)
403 {
404     var buffer = "";
405     var currentNode = node;
406     while (currentNode = currentNode.traverseNextNode(node)) {
407         if (currentNode.nodeType === Node.TEXT_NODE)
408             buffer += currentNode.nodeValue;
409         else if (currentNode.nodeName === "LI")
410             buffer += "\n    ";
411         else if (currentNode.classList.contains("console-message"))
412             buffer += "\n\n";
413     }
414     return buffer;
415 }
416
417 InspectorTest.hideInspectorView = function()
418 {
419     WebInspector.inspectorView.element.setAttribute("style", "display:none !important");
420 }
421
422 InspectorTest.StringOutputStream = function(callback)
423 {
424     this._callback = callback;
425     this._buffer = "";
426 };
427
428 InspectorTest.StringOutputStream.prototype = {
429     open: function(fileName, callback)
430     {
431         callback(true);
432     },
433
434     write: function(chunk, callback)
435     {
436         this._buffer += chunk;
437         if (callback)
438             callback(this);
439     },
440
441     close: function()
442     {
443         this._callback(this._buffer);
444     }
445 };
446
447 InspectorTest.MockSetting = function(value)
448 {
449     this._value = value;
450 };
451
452 InspectorTest.MockSetting.prototype = {
453     get: function() {
454         return this._value;
455     },
456
457     set: function(value) {
458         this._value = value;
459     }
460 };
461
462
463 /**
464  * @constructor
465  * @param {!string} dirPath
466  * @param {!string} name
467  * @param {!function(?WebInspector.TempFile)} callback
468  */
469 InspectorTest.TempFileMock = function(dirPath, name, callback)
470 {
471     this._chunks = [];
472     this._name = name;
473     setTimeout(callback.bind(this, this), 0);
474 }
475
476 InspectorTest.TempFileMock.prototype = {
477     /**
478      * @param {!string} data
479      * @param {!function(boolean)} callback
480      */
481     write: function(data, callback)
482     {
483         this._chunks.push(data);
484         setTimeout(callback.bind(this, true), 0);
485     },
486
487     finishWriting: function() { },
488
489     /**
490      * @param {function(?string)} callback
491      */
492     read: function(callback)
493     {
494         callback(this._chunks.join(""));
495     },
496
497     /**
498      * @param {!WebInspector.OutputStream} outputStream
499      * @param {!WebInspector.OutputStreamDelegate} delegate
500      */
501     writeToOutputSteam: function(outputStream, delegate)
502     {
503         var name = this._name;
504         var text = this._chunks.join("");
505         var chunkedReaderMock = {
506             loadedSize: function()
507             {
508                 return text.length;
509             },
510
511             fileSize: function()
512             {
513                 return text.length;
514             },
515
516             fileName: function()
517             {
518                 return name;
519             },
520
521             cancel: function() { }
522         }
523         delegate.onTransferStarted(chunkedReaderMock);
524         outputStream.write(text);
525         delegate.onChunkTransferred(chunkedReaderMock);
526         outputStream.close();
527         delegate.onTransferFinished(chunkedReaderMock);
528     },
529
530     remove: function() { }
531 }
532
533 InspectorTest.dumpLoadedModules = function(next)
534 {
535     InspectorTest.addResult("Loaded modules:");
536     var modules = WebInspector.moduleManager._modules;
537     for (var i = 0; i < modules.length; ++i) {
538         if (modules[i]._loaded) {
539             InspectorTest.addResult("    " + modules[i]._descriptor.name);
540         }
541     }
542     if (next)
543         next();
544 }
545
546 WebInspector.TempFile = InspectorTest.TempFileMock;
547
548 };
549
550 var initializeCallId = 0;
551 var runTestCallId = 1;
552 var completeTestCallId = 2;
553 var frontendReopeningCount = 0;
554
555 function reopenFrontend()
556 {
557     closeFrontend(openFrontendAndIncrement);
558 }
559
560 function closeFrontend(callback)
561 {
562     // Do this asynchronously to allow InspectorBackendDispatcher to send response
563     // back to the frontend before it's destroyed.
564     setTimeout(function() {
565         testRunner.closeWebInspector();
566         callback();
567     }, 0);
568 }
569
570 function openFrontendAndIncrement()
571 {
572     frontendReopeningCount++;
573     testRunner.showWebInspector();
574     setTimeout(runTest, 0);
575 }
576
577 function runAfterIframeIsLoaded()
578 {
579     if (window.testRunner)
580         testRunner.waitUntilDone();
581     function step()
582     {
583         if (!window.iframeLoaded)
584             setTimeout(step, 100);
585         else
586             runTest();
587     }
588     setTimeout(step, 100);
589 }
590
591 function runTest(enableWatchDogWhileDebugging)
592 {
593     if (!window.testRunner)
594         return;
595
596     testRunner.dumpAsText();
597     testRunner.waitUntilDone();
598     testRunner.display();
599
600     function initializeFrontend(initializationFunctions)
601     {
602         if (window.InspectorTest) {
603             InspectorTest.pageLoaded();
604             return;
605         }
606
607         InspectorTest = {};
608     
609         for (var i = 0; i < initializationFunctions.length; ++i) {
610             try {
611                 initializationFunctions[i]();
612             } catch (e) {
613                 console.error("Exception in test initialization: " + e);
614                 InspectorTest.completeTest();
615             }
616         }
617     }
618
619     function runTestInFrontend(testFunction, completeTestCallId)
620     {
621         if (InspectorTest.completeTestCallId) 
622             return;
623
624         InspectorTest.completeTestCallId = completeTestCallId;
625
626         try {
627             testFunction();
628         } catch (e) {
629             console.error("Exception during test execution: " + e,  (e.stack ? e.stack : "") );
630             InspectorTest.completeTest();
631         }
632     }
633
634     var initializationFunctions = [ String(initialize_InspectorTest) ];
635     for (var name in window) {
636         if (name.indexOf("initialize_") === 0 && typeof window[name] === "function" && name !== "initialize_InspectorTest")
637             initializationFunctions.push(window[name].toString());
638     }
639     var parameters = ["[" + initializationFunctions + "]"];
640     var toEvaluate = "(" + initializeFrontend + ")(" + parameters.join(", ") + ");";
641     testRunner.evaluateInWebInspector(initializeCallId, toEvaluate);
642
643     parameters = [test, completeTestCallId];
644     toEvaluate = "(" + runTestInFrontend + ")(" + parameters.join(", ") + ");";
645     testRunner.evaluateInWebInspector(runTestCallId, toEvaluate);
646
647     if (enableWatchDogWhileDebugging) {
648         function watchDog()
649         {
650             console.log("Internal watchdog triggered at 20 seconds. Test timed out.");
651             closeInspectorAndNotifyDone();
652         }
653         window._watchDogTimer = setTimeout(watchDog, 20000);
654     }
655 }
656
657 function didEvaluateForTestInFrontend(callId)
658 {
659     if (callId !== completeTestCallId)
660         return;
661     delete window.completeTestCallId;
662     if (outputElement && window.quietUntilDone)
663         outputElementParent.appendChild(outputElement);
664     // Close inspector asynchrously to allow caller of this
665     // function send response before backend dispatcher and frontend are destroyed.
666     setTimeout(closeInspectorAndNotifyDone, 0);
667 }
668
669 function closeInspectorAndNotifyDone()
670 {
671     if (window._watchDogTimer)
672         clearTimeout(window._watchDogTimer);
673
674     testRunner.closeWebInspector();
675     setTimeout(function() {
676         testRunner.notifyDone();
677     }, 0);
678 }
679
680 var outputElement;
681 var outputElementParent;
682
683 function output(text)
684 {
685     if (!outputElement) {
686         var intermediate = document.createElement("div");
687         document.body.appendChild(intermediate);
688
689         outputElementParent = document.createElement("div");
690         intermediate.appendChild(outputElementParent);
691
692         outputElement = document.createElement("div");
693         outputElement.className = "output";
694         outputElement.id = "output";
695         outputElement.style.whiteSpace = "pre";
696         if (!window.quietUntilDone)
697             outputElementParent.appendChild(outputElement);
698     }
699     outputElement.appendChild(document.createTextNode(text));
700     outputElement.appendChild(document.createElement("br"));
701 }
702
703 function clearOutput()
704 {
705     if (outputElement) {
706         outputElement.remove();
707         outputElement = null;
708     }
709 }
710
711 function StandaloneTestRunnerStub()
712 {
713 }
714
715 StandaloneTestRunnerStub.prototype = {
716     dumpAsText: function()
717     {
718     },
719
720     waitUntilDone: function()
721     {
722     },
723
724     closeWebInspector: function()
725     {
726         window.opener.postMessage(["closeWebInspector"], "*");
727     },
728
729     notifyDone: function()
730     {
731         var actual = document.body.innerText + "\n";
732         window.opener.postMessage(["notifyDone", actual], "*");
733     },
734
735     evaluateInWebInspector: function(callId, script)
736     {
737         window.opener.postMessage(["evaluateInWebInspector", callId, script], "*");
738     },
739
740     display: function() { }
741 }
742
743 if (!window.testRunner && window.opener)
744     window.testRunner = new StandaloneTestRunnerStub();