1 var initialize_InspectorTest = function() {
4 var resultsSynchronized = false;
6 function consoleOutputHook(messageType)
8 InspectorTest.addResult(messageType + ": " + Array.prototype.slice.call(arguments, 1));
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)
18 var message = "Assertion failed: " + (typeof object !== "undefined" ? object : "");
19 InspectorTest.addResult(new Error(message).stack);
22 InspectorTest.Output = { // override in window.initialize_yourName
23 testComplete: function()
25 RuntimeAgent.evaluate("didEvaluateForTestInFrontend(" + InspectorTest.completeTestCallId + ", \"\")", "test");
28 addResult: function(text)
30 InspectorTest.evaluateInPage("output(unescape('" + escape(text) + "'))");
33 clearResults: function()
35 InspectorTest.evaluateInPage("clearOutput()");
39 InspectorTest.completeTest = function()
41 function testDispatchQueueIsEmpty() {
42 if (!WebInspector.dispatchQueueIsEmpty()) {
43 // Wait for unprocessed messages.
44 setTimeout(testDispatchQueueIsEmpty, 10);
47 InspectorTest.Output.testComplete();
49 testDispatchQueueIsEmpty();
52 InspectorTest.evaluateInConsole = function(code, callback)
54 callback = InspectorTest.safeWrap(callback);
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);
67 InspectorTest.evaluateInConsoleAndDump = function(code, callback)
69 callback = InspectorTest.safeWrap(callback);
71 function mycallback(text)
73 InspectorTest.addResult(code + " = " + text);
76 InspectorTest.evaluateInConsole(code, mycallback);
79 InspectorTest.evaluateInPage = function(code, callback)
81 callback = InspectorTest.safeWrap(callback);
83 function mycallback(error, result, wasThrown)
86 callback(WebInspector.RemoteObject.fromPayload(result), wasThrown);
88 RuntimeAgent.evaluate(code, "console", false, mycallback);
91 InspectorTest.evaluateInPageWithTimeout = function(code)
93 InspectorTest.evaluateInPage("setTimeout(unescape('" + escape(code) + "'))");
96 InspectorTest.check = function(passCondition, failureText)
99 InspectorTest.addResult("FAIL: " + failureText);
102 InspectorTest.addResult = function(text)
105 if (resultsSynchronized)
106 InspectorTest.Output.addResult(text);
108 InspectorTest.Output.clearResults();
109 for (var i = 0; i < results.length; ++i)
110 InspectorTest.Output.addResult(results[i]);
111 resultsSynchronized = true;
115 InspectorTest.addResults = function(textArray)
119 for (var i = 0, size = textArray.length; i < size; ++i)
120 InspectorTest.addResult(textArray[i]);
123 function onError(event)
125 window.removeEventListener("error", onError);
126 InspectorTest.addResult("Uncaught exception in inspector front-end: " + event.message + " [" + event.filename + ":" + event.lineno + "]");
127 InspectorTest.completeTest();
130 window.addEventListener("error", onError);
132 InspectorTest.formatters = {};
134 InspectorTest.formatters.formatAsTypeName = function(value)
136 return "<" + typeof value + ">";
139 InspectorTest.formatters.formatAsRecentTime = function(value)
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;
147 InspectorTest.formatters.formatAsURL = function(value)
151 var lastIndex = value.lastIndexOf("inspector/");
154 return ".../" + value.substr(lastIndex);
157 InspectorTest.addObject = function(object, customFormatters, prefix, firstLinePrefix)
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))
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));
177 InspectorTest.dump(propValue, customFormatters, " " + prefix, prefixWithName);
179 InspectorTest.addResult(prefix + "}");
182 InspectorTest.addArray = function(array, customFormatters, prefix, firstLinePrefix)
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 + "]");
192 InspectorTest.dump = function(value, customFormatters, prefix, prefixWithName)
194 prefixWithName = prefixWithName || prefix;
195 if (prefixWithName && prefixWithName.length > 80) {
196 InspectorTest.addResult(prefixWithName + "was skipped due to prefix length limit");
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 + "\"");
208 InspectorTest.addResult(prefixWithName + value);
211 InspectorTest.assertGreaterOrEqual = function(a, b, message)
214 InspectorTest.addResult("FAILED: " + (message ? message + ": " : "") + a + " < " + b);
217 InspectorTest.navigate = function(url, callback)
219 InspectorTest._pageLoadedCallback = InspectorTest.safeWrap(callback);
221 WebInspector.panel("network")._reset();
222 InspectorTest.evaluateInConsole("window.location = '" + url + "'");
225 InspectorTest.recordNetwork = function()
227 WebInspector.panel("network")._networkLogView._recordButton.toggled = true;
230 InspectorTest.hardReloadPage = function(callback, scriptToEvaluateOnLoad, scriptPreprocessor)
232 InspectorTest._innerReloadPage(true, callback, scriptToEvaluateOnLoad, scriptPreprocessor);
235 InspectorTest.reloadPage = function(callback, scriptToEvaluateOnLoad, scriptPreprocessor)
237 InspectorTest._innerReloadPage(false, callback, scriptToEvaluateOnLoad, scriptPreprocessor);
240 InspectorTest._innerReloadPage = function(hardReload, callback, scriptToEvaluateOnLoad, scriptPreprocessor)
242 InspectorTest._pageLoadedCallback = InspectorTest.safeWrap(callback);
244 if (WebInspector.panels.network)
245 WebInspector.panels.network._reset();
246 PageAgent.reload(hardReload, scriptToEvaluateOnLoad, scriptPreprocessor);
249 InspectorTest.pageLoaded = function()
251 resultsSynchronized = false;
252 InspectorTest.addResult("Page reloaded.");
253 if (InspectorTest._pageLoadedCallback) {
254 var callback = InspectorTest._pageLoadedCallback;
255 delete InspectorTest._pageLoadedCallback;
260 InspectorTest.runWhenPageLoads = function(callback)
262 var oldCallback = InspectorTest._pageLoadedCallback;
263 function chainedCallback()
269 InspectorTest._pageLoadedCallback = InspectorTest.safeWrap(chainedCallback);
272 InspectorTest.runAfterPendingDispatches = function(callback)
274 callback = InspectorTest.safeWrap(callback);
275 InspectorBackend.runAfterPendingDispatches(callback);
278 InspectorTest.createKeyEvent = function(keyIdentifier, ctrlKey, altKey, shiftKey, metaKey)
280 var evt = document.createEvent("KeyboardEvent");
281 evt.initKeyboardEvent("keydown", true /* can bubble */, true /* can cancel */, null /* view */, keyIdentifier, "", ctrlKey, altKey, shiftKey, metaKey);
285 InspectorTest.runTestSuite = function(testSuite)
287 var testSuiteTests = testSuite.slice();
291 if (!testSuiteTests.length) {
292 InspectorTest.completeTest();
295 var nextTest = testSuiteTests.shift();
296 InspectorTest.addResult("");
297 InspectorTest.addResult("Running: " + /function\s([^(]*)/.exec(nextTest)[1]);
298 InspectorTest.safeWrap(nextTest)(runner, runner);
303 InspectorTest.assertEquals = function(expected, found, message)
305 if (expected === found)
310 error = "Failure (" + message + "):";
313 throw new Error(error + " expected <" + expected + "> found <" + found + ">");
316 InspectorTest.assertTrue = function(found, message)
318 InspectorTest.assertEquals(true, !!found, message);
321 InspectorTest.safeWrap = function(func, onexception)
329 return func.apply(wrapThis, arguments);
331 InspectorTest.addResult("Exception while running: " + func + "\n" + (e.stack || e));
333 InspectorTest.safeWrap(onexception)();
335 InspectorTest.completeTest();
341 InspectorTest.addSniffer = function(receiver, methodName, override, opt_sticky)
343 override = InspectorTest.safeWrap(override);
345 var original = receiver[methodName];
346 if (typeof original !== "function")
347 throw ("Cannot find method to override: " + methodName);
349 receiver[methodName] = function(var_args) {
351 var result = original.apply(this, arguments);
354 receiver[methodName] = original;
356 // In case of exception the override won't be called.
358 Array.prototype.push.call(arguments, result);
359 override.apply(this, arguments);
361 throw ("Exception in overriden method '" + methodName + "': " + e);
367 InspectorTest.addConsoleSniffer = function(override, opt_sticky)
369 var sniffer = function (messageIndex) {
370 var message = WebInspector.console.messages[messageIndex];
374 InspectorTest.addSniffer(WebInspector.ConsoleView.prototype, "_showConsoleMessage", sniffer, opt_sticky);
377 InspectorTest.override = function(receiver, methodName, override, opt_sticky)
379 override = InspectorTest.safeWrap(override);
381 var original = receiver[methodName];
382 if (typeof original !== "function")
383 throw ("Cannot find method to override: " + methodName);
385 receiver[methodName] = function(var_args) {
388 var result = override.apply(this, arguments);
390 throw ("Exception in overriden method '" + methodName + "': " + e);
394 receiver[methodName] = original;
402 InspectorTest.textContentWithLineBreaks = function(node)
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")
411 else if (currentNode.classList.contains("console-message"))
417 InspectorTest.hideInspectorView = function()
419 WebInspector.inspectorView.element.setAttribute("style", "display:none !important");
422 InspectorTest.StringOutputStream = function(callback)
424 this._callback = callback;
428 InspectorTest.StringOutputStream.prototype = {
429 open: function(fileName, callback)
434 write: function(chunk, callback)
436 this._buffer += chunk;
443 this._callback(this._buffer);
447 InspectorTest.MockSetting = function(value)
452 InspectorTest.MockSetting.prototype = {
457 set: function(value) {
465 * @param {!string} dirPath
466 * @param {!string} name
467 * @param {!function(?WebInspector.TempFile)} callback
469 InspectorTest.TempFileMock = function(dirPath, name, callback)
473 setTimeout(callback.bind(this, this), 0);
476 InspectorTest.TempFileMock.prototype = {
478 * @param {!string} data
479 * @param {!function(boolean)} callback
481 write: function(data, callback)
483 this._chunks.push(data);
484 setTimeout(callback.bind(this, true), 0);
487 finishWriting: function() { },
490 * @param {function(?string)} callback
492 read: function(callback)
494 callback(this._chunks.join(""));
498 * @param {!WebInspector.OutputStream} outputStream
499 * @param {!WebInspector.OutputStreamDelegate} delegate
501 writeToOutputSteam: function(outputStream, delegate)
503 var name = this._name;
504 var text = this._chunks.join("");
505 var chunkedReaderMock = {
506 loadedSize: function()
521 cancel: function() { }
523 delegate.onTransferStarted(chunkedReaderMock);
524 outputStream.write(text);
525 delegate.onChunkTransferred(chunkedReaderMock);
526 outputStream.close();
527 delegate.onTransferFinished(chunkedReaderMock);
530 remove: function() { }
533 InspectorTest.dumpLoadedModules = function(next)
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);
546 WebInspector.TempFile = InspectorTest.TempFileMock;
550 var initializeCallId = 0;
551 var runTestCallId = 1;
552 var completeTestCallId = 2;
553 var frontendReopeningCount = 0;
555 function reopenFrontend()
557 closeFrontend(openFrontendAndIncrement);
560 function closeFrontend(callback)
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();
570 function openFrontendAndIncrement()
572 frontendReopeningCount++;
573 testRunner.showWebInspector();
574 setTimeout(runTest, 0);
577 function runAfterIframeIsLoaded()
579 if (window.testRunner)
580 testRunner.waitUntilDone();
583 if (!window.iframeLoaded)
584 setTimeout(step, 100);
588 setTimeout(step, 100);
591 function runTest(enableWatchDogWhileDebugging)
593 if (!window.testRunner)
596 testRunner.dumpAsText();
597 testRunner.waitUntilDone();
598 testRunner.display();
600 function initializeFrontend(initializationFunctions)
602 if (window.InspectorTest) {
603 InspectorTest.pageLoaded();
609 for (var i = 0; i < initializationFunctions.length; ++i) {
611 initializationFunctions[i]();
613 console.error("Exception in test initialization: " + e);
614 InspectorTest.completeTest();
619 function runTestInFrontend(testFunction, completeTestCallId)
621 if (InspectorTest.completeTestCallId)
624 InspectorTest.completeTestCallId = completeTestCallId;
629 console.error("Exception during test execution: " + e, (e.stack ? e.stack : "") );
630 InspectorTest.completeTest();
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());
639 var parameters = ["[" + initializationFunctions + "]"];
640 var toEvaluate = "(" + initializeFrontend + ")(" + parameters.join(", ") + ");";
641 testRunner.evaluateInWebInspector(initializeCallId, toEvaluate);
643 parameters = [test, completeTestCallId];
644 toEvaluate = "(" + runTestInFrontend + ")(" + parameters.join(", ") + ");";
645 testRunner.evaluateInWebInspector(runTestCallId, toEvaluate);
647 if (enableWatchDogWhileDebugging) {
650 console.log("Internal watchdog triggered at 20 seconds. Test timed out.");
651 closeInspectorAndNotifyDone();
653 window._watchDogTimer = setTimeout(watchDog, 20000);
657 function didEvaluateForTestInFrontend(callId)
659 if (callId !== completeTestCallId)
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);
669 function closeInspectorAndNotifyDone()
671 if (window._watchDogTimer)
672 clearTimeout(window._watchDogTimer);
674 testRunner.closeWebInspector();
675 setTimeout(function() {
676 testRunner.notifyDone();
681 var outputElementParent;
683 function output(text)
685 if (!outputElement) {
686 var intermediate = document.createElement("div");
687 document.body.appendChild(intermediate);
689 outputElementParent = document.createElement("div");
690 intermediate.appendChild(outputElementParent);
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);
699 outputElement.appendChild(document.createTextNode(text));
700 outputElement.appendChild(document.createElement("br"));
703 function clearOutput()
706 outputElement.remove();
707 outputElement = null;
711 function StandaloneTestRunnerStub()
715 StandaloneTestRunnerStub.prototype = {
716 dumpAsText: function()
720 waitUntilDone: function()
724 closeWebInspector: function()
726 window.opener.postMessage(["closeWebInspector"], "*");
729 notifyDone: function()
731 var actual = document.body.innerText + "\n";
732 window.opener.postMessage(["notifyDone", actual], "*");
735 evaluateInWebInspector: function(callId, script)
737 window.opener.postMessage(["evaluateInWebInspector", callId, script], "*");
740 display: function() { }
743 if (!window.testRunner && window.opener)
744 window.testRunner = new StandaloneTestRunnerStub();