Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / third_party / WebKit / LayoutTests / http / tests / inspector / inspector-test.js
blob45891d6447327141b63c2358d17ab0075a1fa81e
1 var initialize_InspectorTest = function() {
3 var results = [];
5 function consoleOutputHook(messageType)
7 InspectorTest.addResult(messageType + ": " + Array.prototype.slice.call(arguments, 1));
10 window._originalConsoleLog = console.log.bind(console);
12 console.log = consoleOutputHook.bind(InspectorTest, "log");
13 console.error = consoleOutputHook.bind(InspectorTest, "error");
14 console.info = consoleOutputHook.bind(InspectorTest, "info");
15 console.assert = function(condition, object)
17 if (condition)
18 return;
19 var message = "Assertion failed: " + (typeof object !== "undefined" ? object : "");
20 InspectorTest.addResult(new Error(message).stack);
23 InspectorTest.startDumpingProtocolMessages = function()
25 InspectorBackendClass.Connection.prototype._dumpProtocolMessage = testRunner.logToStderr.bind(testRunner);
26 InspectorBackendClass.Options.dumpInspectorProtocolMessages = 1;
29 InspectorTest.completeTest = function()
31 InspectorTest.RuntimeAgent.evaluate("completeTest(\"" + escape(JSON.stringify(results)) + "\")", "test");
34 InspectorTest.flushResults = function()
36 InspectorTest.RuntimeAgent.evaluate("flushResults(\"" + escape(JSON.stringify(results)) + "\")", "test");
37 results = [];
40 InspectorTest.evaluateInPage = function(code, callback)
42 callback = InspectorTest.safeWrap(callback);
44 function mycallback(error, result, wasThrown)
46 if (!error)
47 callback(InspectorTest.runtimeModel.createRemoteObject(result), wasThrown);
49 InspectorTest.RuntimeAgent.evaluate(code, "console", false, mycallback);
52 InspectorTest.evaluateInPageWithTimeout = function(code)
54 // FIXME: we need a better way of waiting for chromium events to happen
55 InspectorTest.evaluateInPage("setTimeout(unescape('" + escape(code) + "'), 1)");
58 var lastEvalId = 0;
59 var pendingEvalRequests = {};
61 var lastPromiseEvalId = 0;
62 var pendingPromiseEvalRequests = {};
64 /**
65 * The given function should take two callback paraters before the arguments:
66 * * resolve - called when successful (with optional result)
67 * * reject - called when there was a failure (with optional error)
69 InspectorTest.invokePageFunctionPromise = function(functionName, parameters)
71 return new Promise(function(resolve, reject) {
72 var id = ++lastPromiseEvalId;
73 pendingPromiseEvalRequests[id] = { resolve: InspectorTest.safeWrap(resolve), reject: InspectorTest.safeWrap(reject) };
75 var jsonParameters = [];
76 for (var i = 0; i < parameters.length; ++i)
77 jsonParameters.push(JSON.stringify(parameters[i]));
78 var asyncEvalWrapper = function(callId, functionName, argumentsArray)
80 function evalCallbackResolve(result)
82 testRunner.evaluateInWebInspector(evalCallbackCallId, "InspectorTest.didInvokePageFunctionPromise(" + callId + ", " + JSON.stringify(result) + ", true);");
85 function evalCallbackReject(result)
87 testRunner.evaluateInWebInspector(evalCallbackCallId, "InspectorTest.didInvokePageFunctionPromise(" + callId + ", " + JSON.stringify(result) + ", false);");
90 var args = [evalCallbackResolve, evalCallbackReject].concat(argumentsArray.map(JSON.stringify));
91 var functionCall = functionName + ".call(null, " + args.join(", ") + ")";
92 try {
93 eval(functionCall);
94 } catch(e) {
95 InspectorTest.addResult("Error: " + e);
96 evalCallbackReject(e);
99 var pageRequest = "(" + asyncEvalWrapper.toString() + ")(" + id + ", unescape('" + escape(functionName) + "'), [" + jsonParameters.join(", ") + "])";
100 InspectorTest.evaluateInPage(pageRequest);
105 InspectorTest.didInvokePageFunctionPromise = function(callId, value, didResolve)
107 var callbacks = pendingPromiseEvalRequests[callId];
108 if (!callbacks) {
109 InspectorTest.addResult("Missing callback for async eval " + callId + ", perhaps callback invoked twice?");
110 return;
112 var callback = didResolve ? callbacks.resolve : callbacks.reject;
113 delete pendingPromiseEvalRequests[callId];
114 callback(value);
118 * @param {string} functionName
119 * @param {...} varArgs
120 * @param {function()} callback
122 InspectorTest.invokePageFunctionAsync = function(functionName, varArgs)
124 var id = ++lastEvalId;
125 var args = Array.prototype.slice.call(arguments, 1);
126 var callback = args.pop();
127 pendingEvalRequests[id] = InspectorTest.safeWrap(callback);
128 var asyncEvalWrapper = function(callId, functionName, argsString)
130 function evalCallback(result)
132 testRunner.evaluateInWebInspector(evalCallbackCallId, "InspectorTest.didInvokePageFunctionAsync(" + callId + ", " + JSON.stringify(result) + ");");
134 var argsArray = argsString.replace(/^\[(.*)\]$/, "$1");
135 if (argsArray.length)
136 argsArray += ",";
137 try {
138 eval(functionName + "(" + argsArray + evalCallback + ")");
139 } catch(e) {
140 InspectorTest.addResult("Error: " + e);
141 evalCallback(String(e));
144 var escapedJSONArgs = JSON.stringify(JSON.stringify(args));
145 InspectorTest.evaluateInPage("(" + asyncEvalWrapper.toString() + ")(" + id + ", unescape('" + escape(functionName) + "')," + escapedJSONArgs + ")");
148 InspectorTest.didInvokePageFunctionAsync = function(callId, value)
150 var callback = pendingEvalRequests[callId];
151 if (!callback) {
152 InspectorTest.addResult("Missing callback for async eval " + callId + ", perhaps callback invoked twice?");
153 return;
155 delete pendingEvalRequests[callId];
156 callback(value);
159 InspectorTest.check = function(passCondition, failureText)
161 if (!passCondition)
162 InspectorTest.addResult("FAIL: " + failureText);
165 InspectorTest.addResult = function(text)
167 results.push(String(text));
170 InspectorTest.addResults = function(textArray)
172 if (!textArray)
173 return;
174 for (var i = 0, size = textArray.length; i < size; ++i)
175 InspectorTest.addResult(textArray[i]);
178 window.onerror = function (message, filename, lineno, colno, error)
180 InspectorTest.addResult("Uncaught exception in inspector front-end: " + message + " [" + error.stack + "]");
181 InspectorTest.completeTest();
184 InspectorTest.formatters = {};
186 InspectorTest.formatters.formatAsTypeName = function(value)
188 return "<" + typeof value + ">";
191 InspectorTest.formatters.formatAsRecentTime = function(value)
193 if (typeof value !== "object" || !(value instanceof Date))
194 return InspectorTest.formatAsTypeName(value);
195 var delta = Date.now() - value;
196 return 0 <= delta && delta < 30 * 60 * 1000 ? "<plausible>" : value;
199 InspectorTest.formatters.formatAsURL = function(value)
201 if (!value)
202 return value;
203 var lastIndex = value.lastIndexOf("inspector/");
204 if (lastIndex < 0)
205 return value;
206 return ".../" + value.substr(lastIndex);
209 InspectorTest.addObject = function(object, customFormatters, prefix, firstLinePrefix)
211 prefix = prefix || "";
212 firstLinePrefix = firstLinePrefix || prefix;
213 InspectorTest.addResult(firstLinePrefix + "{");
214 var propertyNames = Object.keys(object);
215 propertyNames.sort();
216 for (var i = 0; i < propertyNames.length; ++i) {
217 var prop = propertyNames[i];
218 if (!object.hasOwnProperty(prop))
219 continue;
220 var prefixWithName = " " + prefix + prop + " : ";
221 var propValue = object[prop];
222 if (customFormatters && customFormatters[prop]) {
223 var formatterName = customFormatters[prop];
224 if (formatterName !== "skip") {
225 var formatter = InspectorTest.formatters[formatterName];
226 InspectorTest.addResult(prefixWithName + formatter(propValue));
228 } else
229 InspectorTest.dump(propValue, customFormatters, " " + prefix, prefixWithName);
231 InspectorTest.addResult(prefix + "}");
234 InspectorTest.addArray = function(array, customFormatters, prefix, firstLinePrefix)
236 prefix = prefix || "";
237 firstLinePrefix = firstLinePrefix || prefix;
238 InspectorTest.addResult(firstLinePrefix + "[");
239 for (var i = 0; i < array.length; ++i)
240 InspectorTest.dump(array[i], customFormatters, prefix + " ");
241 InspectorTest.addResult(prefix + "]");
244 InspectorTest.dumpDeepInnerHTML = function(element)
246 function innerHTML(prefix, element)
248 var openTag = [];
249 if (element.nodeType === Node.TEXT_NODE) {
250 if (!element.parentElement || element.parentElement.nodeName !== "STYLE")
251 InspectorTest.addResult(element.nodeValue);
252 return;
254 openTag.push("<" + element.nodeName);
255 var attrs = element.attributes;
256 for (var i = 0; attrs && i < attrs.length; ++i) {
257 openTag.push(attrs[i].name + "=" + attrs[i].value);
259 openTag.push(">");
260 InspectorTest.addResult(prefix + openTag.join(" "));
261 for (var child = element.firstChild; child; child = child.nextSibling)
262 innerHTML(prefix + " ", child);
263 if (element.shadowRoot)
264 innerHTML(prefix + " ", element.shadowRoot);
265 InspectorTest.addResult(prefix + "</" + element.nodeName + ">");
267 innerHTML("", element)
270 InspectorTest.dump = function(value, customFormatters, prefix, prefixWithName)
272 prefixWithName = prefixWithName || prefix;
273 if (prefixWithName && prefixWithName.length > 80) {
274 InspectorTest.addResult(prefixWithName + "was skipped due to prefix length limit");
275 return;
277 if (value === null)
278 InspectorTest.addResult(prefixWithName + "null");
279 else if (value && value.constructor && value.constructor.name === "Array")
280 InspectorTest.addArray(value, customFormatters, prefix, prefixWithName);
281 else if (typeof value === "object")
282 InspectorTest.addObject(value, customFormatters, prefix, prefixWithName);
283 else if (typeof value === "string")
284 InspectorTest.addResult(prefixWithName + "\"" + value + "\"");
285 else
286 InspectorTest.addResult(prefixWithName + value);
289 InspectorTest.dumpDataGrid = function(dataGrid)
291 InspectorTest.addResult(InspectorTest.dumpDataGridIntoString(dataGrid));
294 InspectorTest.dumpDataGridIntoString = function(dataGrid)
296 var tableElement = dataGrid.element;
297 var textRows = [];
298 var textWidths = [];
299 var rows = tableElement.getElementsByTagName("tr");
300 for (var i = 0, row; row = rows[i]; ++i) {
301 if (!row.offsetHeight || !row.textContent)
302 continue;
303 var textCols = [];
304 var cols = row.getElementsByTagName("td");
305 for (var j = 0, col; col = cols[j]; ++j) {
306 if (!col.offsetHeight)
307 continue;
308 var index = textCols.length;
309 var content = col.textContent || (col.firstChild && col.firstChild.title) || "";
310 var text = padding(col) + content;
311 textWidths[index] = Math.max(textWidths[index] || 0, text.length);
312 textCols[index] = text;
314 if (textCols.length)
315 textRows.push(textCols);
318 function padding(target)
320 var cell = target.enclosingNodeOrSelfWithNodeName("td");
321 if (!cell.classList.contains("disclosure"))
322 return "";
323 var node = dataGrid.dataGridNodeFromNode(target);
324 var spaces = (node ? node.depth : 0) * 2;
325 return Array(spaces + 1).join(" ");
328 function alignText(text, width)
330 var spaces = width - text.length;
331 return text + Array(spaces + 1).join(" ");;
334 var output = [];
335 for (var i = 0; i < textRows.length; ++i) {
336 var line = "";
337 for (var j = 0; j < textRows[i].length; ++j) {
338 if (j)
339 line += " | ";
340 line += alignText(textRows[i][j], textWidths[j]);
342 line += "|";
343 output.push(line);
345 return output.join("\n");
348 InspectorTest.assertGreaterOrEqual = function(a, b, message)
350 if (a < b)
351 InspectorTest.addResult("FAILED: " + (message ? message + ": " : "") + a + " < " + b);
354 InspectorTest.navigate = function(url, callback)
356 InspectorTest._pageLoadedCallback = InspectorTest.safeWrap(callback);
357 InspectorTest.evaluateInPage("window.location.replace('" + url + "')");
360 InspectorTest.hardReloadPage = function(callback, scriptToEvaluateOnLoad, scriptPreprocessor)
362 InspectorTest._innerReloadPage(true, callback, scriptToEvaluateOnLoad, scriptPreprocessor);
365 InspectorTest.reloadPage = function(callback, scriptToEvaluateOnLoad, scriptPreprocessor)
367 InspectorTest._innerReloadPage(false, callback, scriptToEvaluateOnLoad, scriptPreprocessor);
370 InspectorTest._innerReloadPage = function(hardReload, callback, scriptToEvaluateOnLoad, scriptPreprocessor)
372 InspectorTest._pageLoadedCallback = InspectorTest.safeWrap(callback);
374 if (WebInspector.panels.network)
375 WebInspector.panels.network._networkLogView.reset();
376 InspectorTest.PageAgent.reload(hardReload, scriptToEvaluateOnLoad, scriptPreprocessor);
379 InspectorTest.pageLoaded = function()
381 InspectorTest.addResult("Page reloaded.");
382 if (InspectorTest._pageLoadedCallback) {
383 var callback = InspectorTest._pageLoadedCallback;
384 delete InspectorTest._pageLoadedCallback;
385 callback();
389 InspectorTest.runWhenPageLoads = function(callback)
391 var oldCallback = InspectorTest._pageLoadedCallback;
392 function chainedCallback()
394 if (oldCallback)
395 oldCallback();
396 callback();
398 InspectorTest._pageLoadedCallback = InspectorTest.safeWrap(chainedCallback);
401 InspectorTest.runAfterPendingDispatches = function(callback)
403 var barrier = new CallbackBarrier();
404 var targets = WebInspector.targetManager.targets();
405 for (var i = 0; i < targets.length; ++i)
406 targets[i]._connection.runAfterPendingDispatches(barrier.createCallback());
407 barrier.callWhenDone(InspectorTest.safeWrap(callback));
410 InspectorTest.createKeyEvent = function(keyIdentifier, ctrlKey, altKey, shiftKey, metaKey)
412 var evt = document.createEvent("KeyboardEvent");
413 evt.initKeyboardEvent("keydown", true /* can bubble */, true /* can cancel */, null /* view */, keyIdentifier, "", ctrlKey, altKey, shiftKey, metaKey);
414 return evt;
417 InspectorTest.runTestSuite = function(testSuite)
419 var testSuiteTests = testSuite.slice();
421 function runner()
423 if (!testSuiteTests.length) {
424 InspectorTest.completeTest();
425 return;
427 var nextTest = testSuiteTests.shift();
428 InspectorTest.addResult("");
429 InspectorTest.addResult("Running: " + /function\s([^(]*)/.exec(nextTest)[1]);
430 InspectorTest.safeWrap(nextTest)(runner);
432 runner();
435 InspectorTest.assertEquals = function(expected, found, message)
437 if (expected === found)
438 return;
440 var error;
441 if (message)
442 error = "Failure (" + message + "):";
443 else
444 error = "Failure:";
445 throw new Error(error + " expected <" + expected + "> found <" + found + ">");
448 InspectorTest.assertTrue = function(found, message)
450 InspectorTest.assertEquals(true, !!found, message);
453 InspectorTest.safeWrap = function(func, onexception)
455 function result()
457 if (!func)
458 return;
459 var wrapThis = this;
460 try {
461 return func.apply(wrapThis, arguments);
462 } catch(e) {
463 InspectorTest.addResult("Exception while running: " + func + "\n" + (e.stack || e));
464 if (onexception)
465 InspectorTest.safeWrap(onexception)();
466 else
467 InspectorTest.completeTest();
470 return result;
473 InspectorTest.addSniffer = function(receiver, methodName, override, opt_sticky)
475 override = InspectorTest.safeWrap(override);
477 var original = receiver[methodName];
478 if (typeof original !== "function")
479 throw ("Cannot find method to override: " + methodName);
481 receiver[methodName] = function(var_args) {
482 try {
483 var result = original.apply(this, arguments);
484 } finally {
485 if (!opt_sticky)
486 receiver[methodName] = original;
488 // In case of exception the override won't be called.
489 try {
490 Array.prototype.push.call(arguments, result);
491 override.apply(this, arguments);
492 } catch (e) {
493 throw ("Exception in overriden method '" + methodName + "': " + e);
495 return result;
499 InspectorTest.addSnifferPromise = function(receiver, methodName)
501 return new Promise(function (resolve, reject) {
502 var original = receiver[methodName];
503 if (typeof original !== "function") {
504 reject("Cannot find method to override: " + methodName);
505 return;
508 receiver[methodName] = function(var_args) {
509 try {
510 var result = original.apply(this, arguments);
511 } finally {
512 receiver[methodName] = original;
514 // In case of exception the override won't be called.
515 try {
516 Array.prototype.push.call(arguments, result);
517 resolve.apply(this, arguments);
518 } catch (e) {
519 reject("Exception in overriden method '" + methodName + "': " + e);
521 return result;
526 InspectorTest.addConsoleSniffer = function(override, opt_sticky)
528 InspectorTest.addSniffer(WebInspector.ConsoleModel.prototype, "addMessage", override, opt_sticky);
531 InspectorTest.override = function(receiver, methodName, override, opt_sticky)
533 override = InspectorTest.safeWrap(override);
535 var original = receiver[methodName];
536 if (typeof original !== "function")
537 throw ("Cannot find method to override: " + methodName);
539 receiver[methodName] = function(var_args) {
540 try {
541 try {
542 var result = override.apply(this, arguments);
543 } catch (e) {
544 throw ("Exception in overriden method '" + methodName + "': " + e);
546 } finally {
547 if (!opt_sticky)
548 receiver[methodName] = original;
550 return result;
553 return original;
556 InspectorTest.textContentWithLineBreaks = function(node)
558 function padding(currentNode)
560 var result = 0;
561 while (currentNode && currentNode !== node) {
562 if (currentNode.nodeName === "OL" && !(currentNode.classList && currentNode.classList.contains("object-properties-section")))
563 ++result;
564 currentNode = currentNode.parentNode;
566 return Array(result * 4 + 1).join(" ");
569 var buffer = "";
570 var currentNode = node;
571 var ignoreFirst = false;
572 while (currentNode = currentNode.traverseNextNode(node)) {
573 if (currentNode.nodeType === Node.TEXT_NODE) {
574 buffer += currentNode.nodeValue;
575 } else if (currentNode.nodeName === "LI" || currentNode.nodeName === "TR") {
576 if (!ignoreFirst)
577 buffer += "\n" + padding(currentNode);
578 else
579 ignoreFirst = false;
580 } else if (currentNode.nodeName === "STYLE") {
581 currentNode = currentNode.traverseNextNode(node);
582 continue;
583 } else if (currentNode.classList && currentNode.classList.contains("console-message")) {
584 buffer += "\n\n";
585 } else if (currentNode.classList && currentNode.classList.contains("object-properties-section")) {
586 ignoreFirst = true;
589 return buffer;
592 InspectorTest.textContentWithoutStyles = function(node)
594 var buffer = "";
595 var currentNode = node;
596 while (currentNode = currentNode.traverseNextNode(node)) {
597 if (currentNode.nodeType === Node.TEXT_NODE)
598 buffer += currentNode.nodeValue;
599 else if (currentNode.nodeName === "STYLE")
600 currentNode = currentNode.traverseNextNode(node);
602 return buffer;
605 InspectorTest.clearSpecificInfoFromStackFrames = function(text)
607 var buffer = text.replace(/\(file:\/\/\/(?:[^)]+\)|[\w\/:-]+)/g, "(...)");
608 buffer = buffer.replace(/\(<anonymous>:[^)]+\)/g, "(...)");
609 buffer = buffer.replace(/VM\d+/g, "VM");
610 buffer = buffer.replace(/\s*at[^()]+\(native\)/g, "");
611 return buffer.replace(/\s*at Object.InjectedScript.[^)]+\)/g, "");
614 InspectorTest.hideInspectorView = function()
616 WebInspector.inspectorView.element.setAttribute("style", "display:none !important");
619 InspectorTest.StringOutputStream = function(callback)
621 this._callback = callback;
622 this._buffer = "";
625 InspectorTest.StringOutputStream.prototype = {
626 open: function(fileName, callback)
628 callback(true);
631 write: function(chunk, callback)
633 this._buffer += chunk;
634 if (callback)
635 callback(this);
638 close: function()
640 this._callback(this._buffer);
644 InspectorTest.MockSetting = function(value)
646 this._value = value;
649 InspectorTest.MockSetting.prototype = {
650 get: function() {
651 return this._value;
654 set: function(value) {
655 this._value = value;
661 * @constructor
662 * @param {!string} dirPath
663 * @param {!string} name
664 * @param {!function(?WebInspector.TempFile)} callback
666 InspectorTest.TempFileMock = function(dirPath, name)
668 this._chunks = [];
669 this._name = name;
670 this._size = 0;
673 InspectorTest.TempFileMock.prototype = {
675 * @param {!Array.<string>} chunks
676 * @param {!function(boolean)} callback
678 write: function(chunks, callback)
680 for (var i = 0; i < chunks.length; ++i)
681 this._size += chunks[i].length;
682 this._chunks.push.apply(this._chunks, chunks);
683 setTimeout(callback.bind(this, this._size), 1);
686 finishWriting: function() { },
689 * @param {function(?string)} callback
691 read: function(callback)
693 this.readRange(undefined, undefined, callback);
697 * @param {number|undefined} startOffset
698 * @param {number|undefined} endOffset
699 * @param {function(?string)} callback
701 readRange: function(startOffset, endOffset, callback)
703 var blob = new Blob(this._chunks);
704 blob = blob.slice(startOffset || 0, endOffset || blob.size);
705 reader = new FileReader();
706 var self = this;
707 reader.onloadend = function()
709 callback(reader.result);
711 reader.readAsText(blob);
715 * @param {!WebInspector.OutputStream} outputStream
716 * @param {!WebInspector.OutputStreamDelegate} delegate
718 writeToOutputSteam: function(outputStream, delegate)
720 var name = this._name;
721 var text = this._chunks.join("");
722 var chunkedReaderMock = {
723 loadedSize: function()
725 return text.length;
728 fileSize: function()
730 return text.length;
733 fileName: function()
735 return name;
738 cancel: function() { }
740 delegate.onTransferStarted(chunkedReaderMock);
741 outputStream.write(text);
742 delegate.onChunkTransferred(chunkedReaderMock);
743 outputStream.close();
744 delegate.onTransferFinished(chunkedReaderMock);
747 remove: function() { }
750 InspectorTest.TempFileMock.create = function(dirPath, name)
752 var tempFile = new InspectorTest.TempFileMock(dirPath, name);
753 return Promise.resolve(tempFile);
756 InspectorTest.dumpLoadedModules = function(next)
758 function moduleSorter(left, right)
760 return String.naturalOrderComparator(left._descriptor.name, right._descriptor.name);
763 InspectorTest.addResult("Loaded modules:");
764 var modules = self.runtime._modules;
765 modules.sort(moduleSorter);
766 for (var i = 0; i < modules.length; ++i) {
767 if (modules[i]._loaded)
768 InspectorTest.addResult(" " + modules[i]._descriptor.name);
770 if (next)
771 next();
774 InspectorTest.TimeoutMock = function()
776 this._timeoutId = 0;
777 this._timeoutIdToProcess = {};
778 this._timeoutIdToMillis = {};
779 this.setTimeout = this.setTimeout.bind(this);
780 this.clearTimeout = this.clearTimeout.bind(this);
782 InspectorTest.TimeoutMock.prototype = {
783 setTimeout: function(operation, timeout)
785 this._timeoutIdToProcess[++this._timeoutId] = operation;
786 this._timeoutIdToMillis[this._timeoutId] = timeout;
787 return this._timeoutId;
790 clearTimeout: function(timeoutId)
792 delete this._timeoutIdToProcess[timeoutId];
793 delete this._timeoutIdToMillis[timeoutId];
796 activeTimersTimeouts: function()
798 return Object.values(this._timeoutIdToMillis);
801 fireAllTimers: function()
803 for (var timeoutId in this._timeoutIdToProcess)
804 this._timeoutIdToProcess[timeoutId].call(window);
805 this._timeoutIdToProcess = {};
806 this._timeoutIdToMillis = {};
810 WebInspector.targetManager.observeTargets({
811 targetAdded: function(target)
813 if (InspectorTest.CSSAgent)
814 return;
815 InspectorTest.CSSAgent = target.cssAgent();
816 InspectorTest.ConsoleAgent = target.consoleAgent();
817 InspectorTest.DeviceOrientationAgent = target.deviceOrientationAgent();
818 InspectorTest.DOMAgent = target.domAgent();
819 InspectorTest.DOMDebuggerAgent = target.domdebuggerAgent();
820 InspectorTest.DebuggerAgent = target.debuggerAgent();
821 InspectorTest.EmulationAgent = target.emulationAgent();
822 InspectorTest.HeapProfilerAgent = target.heapProfilerAgent();
823 InspectorTest.InspectorAgent = target.inspectorAgent();
824 InspectorTest.LayerTreeAgent = target.layerTreeAgent();
825 InspectorTest.NetworkAgent = target.networkAgent();
826 InspectorTest.PageAgent = target.pageAgent();
827 InspectorTest.ProfilerAgent = target.profilerAgent();
828 InspectorTest.RuntimeAgent = target.runtimeAgent();
829 InspectorTest.ScreenOrientationAgent = target.screenOrientationAgent();
830 InspectorTest.WorkerAgent = target.workerAgent();
832 InspectorTest.consoleModel = target.consoleModel;
833 InspectorTest.networkManager = target.networkManager;
834 InspectorTest.resourceTreeModel = target.resourceTreeModel;
835 InspectorTest.networkLog = target.networkLog;
836 InspectorTest.debuggerModel = WebInspector.DebuggerModel.fromTarget(target);
837 InspectorTest.runtimeModel = target.runtimeModel;
838 InspectorTest.domModel = WebInspector.DOMModel.fromTarget(target);
839 InspectorTest.cssModel = WebInspector.CSSStyleModel.fromTarget(target);
840 InspectorTest.workerManager = target.workerManager;
841 InspectorTest.powerProfiler = target.powerProfiler;
842 InspectorTest.cpuProfilerModel = target.cpuProfilerModel;
843 InspectorTest.heapProfilerModel = target.heapProfilerModel;
844 InspectorTest.layerTreeModel = target.layerTreeModel;
845 InspectorTest.animationModel = target.animationModel;
846 InspectorTest.serviceWorkerCacheModel = target.serviceWorkerCacheModel;
847 InspectorTest.serviceWorkerManager = target.serviceWorkerManager;
848 InspectorTest.tracingManager = target.tracingManager;
849 InspectorTest.mainTarget = target;
852 targetRemoved: function(target) { }
855 InspectorTest._panelsToPreload = [];
857 InspectorTest.preloadPanel = function(panelName)
859 InspectorTest._panelsToPreload.push(panelName);
862 InspectorTest._modulesToPreload = [];
864 InspectorTest.preloadModule = function(moduleName)
866 InspectorTest._modulesToPreload.push(moduleName);
869 }; // initialize_InspectorTest
871 var initializeCallId = 0;
872 var runTestCallId = 1;
873 var evalCallbackCallId = 2;
874 var frontendReopeningCount = 0;
876 function reopenFrontend()
878 closeFrontend(openFrontendAndIncrement);
881 function closeFrontend(callback)
883 // Do this asynchronously to allow InspectorBackendDispatcher to send response
884 // back to the frontend before it's destroyed.
885 // FIXME: we need a better way of waiting for chromium events to happen
886 setTimeout(function() {
887 testRunner.closeWebInspector();
888 callback();
889 }, 1);
892 function openFrontendAndIncrement()
894 frontendReopeningCount++;
895 testRunner.showWebInspector(JSON.stringify({testPath: '"' + location.href + '"'}).replace(/\"/g,"%22"));
896 setTimeout(runTest, 1);
899 function runAfterIframeIsLoaded()
901 if (window.testRunner)
902 testRunner.waitUntilDone();
903 function step()
905 if (!window.iframeLoaded)
906 setTimeout(step, 100);
907 else
908 runTest();
910 setTimeout(step, 100);
913 function runTest(enableWatchDogWhileDebugging)
915 if (!window.testRunner)
916 return;
918 testRunner.dumpAsText();
919 testRunner.waitUntilDone();
921 function initializeFrontend(initializationFunctions)
923 if (window.InspectorTest) {
924 InspectorTest.pageLoaded();
925 return;
928 InspectorTest = {};
930 for (var i = 0; i < initializationFunctions.length; ++i) {
931 try {
932 initializationFunctions[i]();
933 } catch (e) {
934 console.error("Exception in test initialization: " + e + " " + e.stack);
935 InspectorTest.completeTest();
940 function runTestInFrontend(testFunction)
942 if (InspectorTest.wasAlreadyExecuted)
943 return;
945 InspectorTest.wasAlreadyExecuted = true;
947 // 1. Preload panels.
948 var lastLoadedPanel;
950 var promises = [];
951 for (var moduleName of InspectorTest._modulesToPreload)
952 promises.push(self.runtime.loadModulePromise(moduleName));
954 for (var i = 0; i < InspectorTest._panelsToPreload.length; ++i) {
955 lastLoadedPanel = InspectorTest._panelsToPreload[i];
956 promises.push(WebInspector.inspectorView.panel(lastLoadedPanel));
959 var testPath = WebInspector.settings.createSetting("testPath", "").get();
961 // 2. Show initial panel based on test path.
962 var initialPanelByFolder = {
963 "audits": "audits",
964 "console": "console",
965 "elements": "elements",
966 "editor": "sources",
967 "layers": "layers",
968 "network": "network",
969 "profiler": "profiles",
970 "resource-tree": "resources",
971 "search": "sources",
972 "security": "security",
973 "service-workers": "resources",
974 "sources": "sources",
975 "timeline": "timeline",
976 "tracing": "timeline",
978 var initialPanelShown = false;
979 for (var folder in initialPanelByFolder) {
980 if (testPath.indexOf(folder + "/") !== -1) {
981 lastLoadedPanel = initialPanelByFolder[folder];
982 promises.push(WebInspector.inspectorView.panel(lastLoadedPanel));
983 break;
987 // 3. Run test function.
988 Promise.all(promises).then(function() {
989 if (lastLoadedPanel)
990 WebInspector.inspectorView.showInitialPanelForTest(lastLoadedPanel);
991 testFunction();
992 }).catch(function(e) {
993 console.error(e);
994 InspectorTest.completeTest();
998 var initializationFunctions = [ String(initialize_InspectorTest) ];
999 for (var name in window) {
1000 if (name.indexOf("initialize_") === 0 && typeof window[name] === "function" && name !== "initialize_InspectorTest")
1001 initializationFunctions.push(window[name].toString());
1003 var toEvaluate = "(" + initializeFrontend + ")(" + "[" + initializationFunctions + "]" + ");";
1004 testRunner.evaluateInWebInspector(initializeCallId, toEvaluate);
1006 if (window.debugTest)
1007 test = "function() { " + test.toString() + "; window.test = test; InspectorTest.addResult = window._originalConsoleLog; InspectorTest.completeTest = function() {}; InspectorTest.debugTest = true; }";
1008 toEvaluate = "(" + runTestInFrontend + ")(" + test + ");";
1009 testRunner.evaluateInWebInspector(runTestCallId, toEvaluate);
1011 if (enableWatchDogWhileDebugging) {
1012 function watchDog()
1014 console.log("Internal watchdog triggered at 20 seconds. Test timed out.");
1015 closeInspectorAndNotifyDone();
1017 window._watchDogTimer = setTimeout(watchDog, 20000);
1021 function runTestAfterDisplay(enableWatchDogWhileDebugging)
1023 if (!window.testRunner)
1024 return;
1026 testRunner.waitUntilDone();
1027 requestAnimationFrame(runTest.bind(this, enableWatchDogWhileDebugging));
1030 function completeTest(results)
1032 flushResults(results);
1033 closeInspectorAndNotifyDone();
1036 function flushResults(results)
1038 results = (JSON && JSON.parse ? JSON.parse : eval)(unescape(results));
1039 for (var i = 0; i < results.length; ++i)
1040 _output(results[i]);
1043 function closeInspectorAndNotifyDone()
1045 if (window._watchDogTimer)
1046 clearTimeout(window._watchDogTimer);
1048 testRunner.closeWebInspector();
1049 setTimeout(function() {
1050 testRunner.notifyDone();
1051 }, 0);
1054 var outputElement;
1056 function createOutputElement()
1058 outputElement = document.createElement("div");
1059 // Support for svg - add to document, not body, check for style.
1060 if (outputElement.style) {
1061 outputElement.style.whiteSpace = "pre";
1062 outputElement.style.height = "10px";
1063 outputElement.style.overflow = "hidden";
1065 document.documentElement.appendChild(outputElement);
1068 function output(text)
1070 _output("[page] " + text);
1073 function _output(result)
1075 if (!outputElement)
1076 createOutputElement();
1077 outputElement.appendChild(document.createTextNode(result));
1078 outputElement.appendChild(document.createElement("br"));