Commit 98852aa9 authored by Will Chen's avatar Will Chen Committed by Commit Bot

DevTools: re-use new test runner modules in legacy test helpers (part 2)

This eliminates a lot of the code duplication between the new and legacy
integration test frameworks by making the legacy test helper files small
wrappers to load the new *test_runner modules.

* Fixes data_grid_test_runner because the legacy test helpers had two
data grid implementations, one of which was not actually used anymore.

Bug: 667560
Change-Id: I2ad21ec7b50be89a44f643858cec3b9348d8d857
Reviewed-on: https://chromium-review.googlesource.com/722112
Commit-Queue: Will Chen <chenwilliam@chromium.org>
Reviewed-by: default avatarDmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#509319}
parent 60697288
...@@ -38,17 +38,17 @@ Running: testDeleteNextJumpLocations ...@@ -38,17 +38,17 @@ Running: testDeleteNextJumpLocations
<Rolled over> line: 9 column: 4 [example-fileset-for-test.js] <Rolled over> line: 9 column: 4 [example-fileset-for-test.js]
Running: testCrossFileJump Running: testCrossFileJump
<Opened editor-test.js> line: 0 column: 0 [editor-test.js] <Opened jump-text.js> line: 0 column: 0 [jump-text.js]
<Mouse click (10, 1)> line: 10 column: 1 [editor-test.js] <Mouse click (10, 1)> line: 10 column: 1 [jump-text.js]
<Mouse click (11, 1)> line: 11 column: 1 [editor-test.js] <Mouse click (11, 1)> line: 11 column: 1 [jump-text.js]
<Rolled back> line: 10 column: 1 [editor-test.js] <Rolled back> line: 10 column: 1 [jump-text.js]
<Rolled back> line: 0 column: 0 [editor-test.js] <Rolled back> line: 0 column: 0 [jump-text.js]
<Rolled back> line: 9 column: 4 [example-fileset-for-test.js] <Rolled back> line: 9 column: 4 [example-fileset-for-test.js]
<Rolled back> line: 9 column: 0 [example-fileset-for-test.js] <Rolled back> line: 9 column: 0 [example-fileset-for-test.js]
<Rolled over> line: 9 column: 4 [example-fileset-for-test.js] <Rolled over> line: 9 column: 4 [example-fileset-for-test.js]
<Rolled over> line: 0 column: 0 [editor-test.js] <Rolled over> line: 0 column: 0 [jump-text.js]
<Rolled over> line: 10 column: 1 [editor-test.js] <Rolled over> line: 10 column: 1 [jump-text.js]
<Rolled over> line: 11 column: 1 [editor-test.js] <Rolled over> line: 11 column: 1 [jump-text.js]
Running: testCloseCrossFile Running: testCloseCrossFile
<Close active tab> line: 9 column: 4 [example-fileset-for-test.js] <Close active tab> line: 9 column: 4 [example-fileset-for-test.js]
...@@ -108,12 +108,12 @@ Running: testInFileSearch ...@@ -108,12 +108,12 @@ Running: testInFileSearch
Running: testShowAnchorLocation Running: testShowAnchorLocation
<Before switching to other panel> line: 581 column: 44 [example-fileset-for-test.js] <Before switching to other panel> line: 581 column: 44 [example-fileset-for-test.js]
Selection: {"startLine":10,"startColumn":1,"endLine":10,"endColumn":1} Selection: {"startLine":10,"startColumn":1,"endLine":10,"endColumn":1}
<Showed anchor in editor-test.js with line 333 column 3> line: 10 column: 1 [editor-test.js] <Showed anchor in jump-text.js with line 333 column 3> line: 10 column: 1 [jump-text.js]
<Rolled back> line: 581 column: 44 [example-fileset-for-test.js] <Rolled back> line: 581 column: 44 [example-fileset-for-test.js]
<Rolled over> line: 10 column: 1 [editor-test.js] <Rolled over> line: 10 column: 1 [jump-text.js]
Running: testShowUISourceCode Running: testShowUISourceCode
<Initial state> line: 10 column: 1 [editor-test.js] <Initial state> line: 10 column: 1 [jump-text.js]
<jump to line 20> line: 20 column: 0 [example-fileset-for-test.js] <jump to line 20> line: 20 column: 0 [example-fileset-for-test.js]
<jump to line 10> line: 10 column: 0 [example-fileset-for-test.js] <jump to line 10> line: 10 column: 0 [example-fileset-for-test.js]
<jump to line 30> line: 30 column: 0 [example-fileset-for-test.js] <jump to line 30> line: 30 column: 0 [example-fileset-for-test.js]
...@@ -121,5 +121,5 @@ Running: testShowUISourceCode ...@@ -121,5 +121,5 @@ Running: testShowUISourceCode
<rollback> line: 30 column: 0 [example-fileset-for-test.js] <rollback> line: 30 column: 0 [example-fileset-for-test.js]
<rollback> line: 10 column: 0 [example-fileset-for-test.js] <rollback> line: 10 column: 0 [example-fileset-for-test.js]
<rollback> line: 20 column: 0 [example-fileset-for-test.js] <rollback> line: 20 column: 0 [example-fileset-for-test.js]
<rollback> line: 10 column: 1 [editor-test.js] <rollback> line: 10 column: 1 [jump-text.js]
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
<script src="../inspector/debugger-test.js"></script> <script src="../inspector/debugger-test.js"></script>
<script src="resources/example-fileset-for-test.js"></script> <script src="resources/example-fileset-for-test.js"></script>
<script src="resources/editor-test.js"></script> <script src="resources/editor-test.js"></script>
<script src="resources/jump-text.js"></script>
<script> <script>
function test() { function test() {
var panel = UI.panels.sources; var panel = UI.panels.sources;
...@@ -128,10 +129,10 @@ function test() { ...@@ -128,10 +129,10 @@ function test() {
}, },
function testCrossFileJump(next) { function testCrossFileJump(next) {
SourcesTestRunner.showScriptSource('editor-test.js', onContentLoaded); SourcesTestRunner.showScriptSource('jump-text.js', onContentLoaded);
function onContentLoaded() { function onContentLoaded() {
var editor = panel.visibleView.textEditor; var editor = panel.visibleView.textEditor;
dumpSelection('Opened editor-test.js'); dumpSelection('Opened jump-text.js');
clickAndDump(editor, [10, 11], [1, 1]); clickAndDump(editor, [10, 11], [1, 1]);
for (var i = 0; i < 4; ++i) { for (var i = 0; i < 4; ++i) {
rollback(); rollback();
...@@ -199,7 +200,7 @@ function test() { ...@@ -199,7 +200,7 @@ function test() {
function testShowAnchorLocation(next) { function testShowAnchorLocation(next) {
dumpSelection('Before switching to other panel'); dumpSelection('Before switching to other panel');
SourcesTestRunner.waitForScriptSource('editor-test.js', onScriptSource); SourcesTestRunner.waitForScriptSource('jump-text.js', onScriptSource);
function onScriptSource(uiSourceCode) { function onScriptSource(uiSourceCode) {
var linkifier = new Components.Linkifier(); var linkifier = new Components.Linkifier();
var anchorURI = uiSourceCode.url(); var anchorURI = uiSourceCode.url();
......
var initialize_AccessibilityTest = function() { var initialize_AccessibilityTest = function() {
InspectorTest.preloadModule('accessibility_test_runner');
InspectorTest.accessibilitySidebarPane = function()
{
return self.runtime.sharedInstance(Accessibility.AccessibilitySidebarView);
}
/**
* @param {string} idValue
* @return {Promise}
*/
InspectorTest.selectNodeAndWaitForAccessibility = function(idValue)
{
return new Promise((resolve) => {
InspectorTest.selectNodeWithId(idValue, function() {
self.runtime.sharedInstance(Accessibility.AccessibilitySidebarView).doUpdate().then(resolve);
});
});
}
InspectorTest.dumpSelectedElementAccessibilityNode = function()
{
var sidebarPane = InspectorTest.accessibilitySidebarPane();
if (!sidebarPane) {
InspectorTest.addResult("No sidebarPane in dumpSelectedElementAccessibilityNode");
InspectorTest.completeTest();
return;
}
InspectorTest.dumpAccessibilityNode(sidebarPane._axNodeSubPane._axNode);
}
/**
* @param {!Accessibility.AccessibilityNode} accessibilityNode
*/
InspectorTest.dumpAccessibilityNode = function(accessibilityNode)
{
if (!accessibilityNode) {
InspectorTest.addResult("<null>");
InspectorTest.completeTest();
return;
}
var builder = [];
builder.push(accessibilityNode.role().value);
builder.push(accessibilityNode.name() ? '"' + accessibilityNode.name().value + '"'
: "<undefined>");
if (accessibilityNode.properties()) {
for (var property of accessibilityNode.properties()) {
if ("value" in property)
builder.push(property.name + '="' + property.value.value + '"');
}
}
InspectorTest.addResult(builder.join(" "));
}
/**
* @param {string} attribute
* @return {?Accessibility.ARIAAttributesTreeElement}
*/
InspectorTest.findARIAAttributeTreeElement = function(attribute)
{
var sidebarPane = InspectorTest.accessibilitySidebarPane();
if (!sidebarPane) {
InspectorTest.addResult("Could not get Accessibility sidebar pane.");
InspectorTest.completeTest();
return;
}
var ariaSubPane = sidebarPane._ariaSubPane;
var treeOutline = ariaSubPane._treeOutline;
var childNodes = treeOutline._rootElement._children;
for (var treeElement of childNodes) {
if (treeElement._attribute.name === attribute)
return treeElement;
}
return null;
}
}; };
function initialize_AutocompleteTest()
{
InspectorTest.dumpSuggestions = function(textEditor, lines)
{
var resolve;
var promise = new Promise(fulfill => resolve = fulfill);
var lineNumber = -1, columnNumber;
for (var i = 0; i < lines.length; ++i) {
var columnNumber = lines[i].indexOf("|");
if (columnNumber !== -1) {
lineNumber = i;
break;
}
}
if (lineNumber === -1)
throw new Error("Test case is invalid: cursor position is not marked with '|' symbol.");
textEditor.setText(lines.join("\n").replace("|", ""));
textEditor.setSelection(TextUtils.TextRange.createFromLocation(lineNumber, columnNumber));
InspectorTest.addSniffer(TextEditor.TextEditorAutocompleteController.prototype, "_onSuggestionsShownForTest", suggestionsShown);
textEditor._autocompleteController.autocomplete();
function suggestionsShown(words)
{
InspectorTest.addResult("========= Selection In Editor =========");
InspectorTest.dumpTextWithSelection(textEditor);
InspectorTest.addResult("======= Autocomplete Suggestions =======");
InspectorTest.addResult("[" + words.map(item => item.text).join(", ") + "]");
resolve();
}
return promise;
}
}
function initialize_CoverageTests() { function initialize_CoverageTests() {
InspectorTest.preloadModule("coverage_test_runner");
InspectorTest.preloadModule("coverage");
InspectorTest.startCoverage = function()
{
UI.viewManager.showView("coverage");
var coverageView = self.runtime.sharedInstance(Coverage.CoverageView);
coverageView._startRecording(false);
}
InspectorTest.stopCoverage = function()
{
var coverageView = self.runtime.sharedInstance(Coverage.CoverageView);
return coverageView._stopRecording();
}
InspectorTest.pollCoverage = function()
{
var coverageView = self.runtime.sharedInstance(Coverage.CoverageView);
return coverageView._poll();
}
InspectorTest.sourceDecorated = async function(source)
{
await UI.inspectorView.showPanel("sources");
var decoratePromise = InspectorTest.addSnifferPromise(Coverage.CoverageView.LineDecorator.prototype, "_innerDecorate");
var sourceFrame = await new Promise(fulfill => InspectorTest.showScriptSource(source, fulfill));
await decoratePromise;
return sourceFrame;
}
InspectorTest.dumpDecorations = async function(source)
{
var sourceFrame = await InspectorTest.sourceDecorated(source);
InspectorTest.dumpDecorationsInSourceFrame(sourceFrame);
}
InspectorTest.findCoverageNodeForURL = function(url)
{
var coverageListView = self.runtime.sharedInstance(Coverage.CoverageView)._listView;
var rootNode = coverageListView._dataGrid.rootNode();
for (var child of rootNode.children) {
if (child._coverageInfo.url().endsWith(url))
return child;
}
return null;
}
InspectorTest.dumpDecorationsInSourceFrame = function(sourceFrame)
{
var markerMap = new Map([['used', '+'], ['unused', '-']]);
var codeMirror = sourceFrame.textEditor.codeMirror();
for (var line = 0; line < codeMirror.lineCount(); ++line) {
var text = codeMirror.getLine(line);
var markerType = ' ';
var lineInfo = codeMirror.lineInfo(line);
if (!lineInfo)
continue;
var gutterElement = lineInfo.gutterMarkers && lineInfo.gutterMarkers['CodeMirror-gutter-coverage'];
if (gutterElement) {
var markerClass = /^text-editor-coverage-(\w*)-marker$/.exec(gutterElement.classList)[1];
markerType = markerMap.get(markerClass) || gutterElement.classList;
}
InspectorTest.addResult(`${line}: ${markerType} ${text}`);
}
}
InspectorTest.dumpCoverageListView = function()
{
var coverageListView = self.runtime.sharedInstance(Coverage.CoverageView)._listView;
var dataGrid = coverageListView._dataGrid;
dataGrid.updateInstantly();
for (var child of dataGrid.rootNode().children) {
var data = child._coverageInfo;
var url = InspectorTest.formatters.formatAsURL(data.url());
if (url.endsWith("-test.js") || url.endsWith(".html"))
continue;
var type = Coverage.CoverageListView._typeToString(data.type());
InspectorTest.addResult(`${url} ${type} used: ${data.usedSize()} unused: ${data.unusedSize()} total: ${data.size()}`);
}
}
} }
function initialize_DataGridTest() function initialize_DataGridTest() {
{ InspectorTest.preloadModule("data_grid_test_runner");
InspectorTest.preloadModule("data_grid");
InspectorTest.dumpDataGrid = function(root, descentIntoCollapsed, prefix)
{
if (!prefix)
prefix = "";
var suffix = root.selected ? " <- selected" : "";
var columnKeys = root.dataGrid._columnsArray.map(column => column.id);
var outputColumns = [];
for (var key of columnKeys) {
if (key in root.data)
outputColumns.push(root.data[key]);
}
if (outputColumns.length)
InspectorTest.addResult(prefix + outputColumns.join(" | ") + suffix);
if (!descentIntoCollapsed && !root.expanded)
return;
for (var child of root.children)
InspectorTest.dumpDataGrid(child, descentIntoCollapsed, prefix + " ");
}
InspectorTest.validateDataGrid = function(root)
{
var children = root.children;
for (var i = 0; i < children.length; ++i) {
var child = children[i];
if (child.parent !== root)
throw "Wrong parent for child " + child.data.id + " of " + root.data.id;
if (child.nextSibling !== (i + 1 === children.length ? null : children[i + 1]))
throw "Wrong child.nextSibling for " + child.data.id + " (" + i + " of " + children.length + ") ";
if (child.previousSibling !== (i ? children[i - 1] : null))
throw "Wrong child.previousSibling for " + child.data.id + " (" + i + " of " + children.length + ") ";
if (child.parent && !child.parent._isRoot && child.depth !== root.depth + 1)
throw "Wrong depth for " + child.data.id + " expected " + (root.depth + 1) + " but got " + child.depth;
InspectorTest.validateDataGrid(child);
}
var selectedNode = root.dataGrid.selectedNode;
if (!root.parent && selectedNode) {
if (!selectedNode.selectable)
throw "Selected node is not selectable";
for (var node = selectedNode; node && node !== root; node = node.parent) { }
if (!node)
throw "Selected node (" + selectedNode.data.id + ") is not within the DataGrid";
}
}
InspectorTest.dumpAndValidateDataGrid = function(root)
{
InspectorTest.dumpDataGrid(root);
InspectorTest.validateDataGrid(root);
}
} }
var initialize_DeviceMode = function() var initialize_DeviceMode = function() {
{ InspectorTest.preloadModule('device_mode_test_runner');
InspectorTest.buildFakePhone = function(overrides)
{
var StandardPhoneJSON = {
"show-by-default": false,
"title": "Fake Phone 1",
"screen": {
"horizontal": { "width": 480, "height": 320 },
"device-pixel-ratio": 2,
"vertical": { "width": 320, "height": 480 }
},
"capabilities": ["touch", "mobile"],
"user-agent": "fakeUserAgent",
"type": "phone",
"modes": [
{
"title": "default",
"orientation": "vertical",
"insets": { "left": 0, "top": 0, "right": 0, "bottom": 0 }
},
{
"title": "default",
"orientation": "horizontal",
"insets": { "left": 0, "top": 0, "right": 0, "bottom": 0 }
}
]
};
var json = Object.assign(StandardPhoneJSON, overrides || {});
return Emulation.EmulatedDevice.fromJSONV1(json);
}
} }
function initialize_EditDOMTests() function initialize_EditDOMTests() {
{ InspectorTest.preloadModule("elements_test_runner");
// Preload codemirror which is used for "Edit as HTML".
InspectorTest.preloadPanel("sources");
InspectorTest.doAddAttribute = function(testName, dataNodeId, attributeText, next)
{
InspectorTest.domActionTestForNodeId(testName, dataNodeId, testBody, next);
function testBody(node, done)
{
var editorElement = InspectorTest.editNodePart(node, "webkit-html-attribute");
eventSender.keyDown("Tab");
InspectorTest.deprecatedRunAfterPendingDispatches(testContinuation);
function testContinuation()
{
var editorElement = UI.panels.elements._treeOutlines[0]._shadowRoot.getSelection().anchorNode.parentElement;
editorElement.textContent = attributeText;
editorElement.dispatchEvent(InspectorTest.createKeyEvent("Enter"));
InspectorTest.addSniffer(Elements.ElementsTreeOutline.prototype, "_updateModifiedNodes", done);
}
}
}
InspectorTest.domActionTestForNodeId = function(testName, dataNodeId, testBody, next)
{
function callback(testNode, continuation)
{
InspectorTest.selectNodeWithId(dataNodeId, continuation);
}
InspectorTest.domActionTest(testName, callback, testBody, next);
}
InspectorTest.domActionTest = function(testName, dataNodeSelectionCallback, testBody, next)
{
var testNode = InspectorTest.expandedNodeWithId(testName);
InspectorTest.addResult("==== before ====");
InspectorTest.dumpElementsTree(testNode);
dataNodeSelectionCallback(testNode, step0);
function step0(node)
{
InspectorTest.deprecatedRunAfterPendingDispatches(step1.bind(null, node));
}
function step1(node)
{
testBody(node, step2);
}
function step2()
{
InspectorTest.addResult("==== after ====");
InspectorTest.dumpElementsTree(testNode);
next();
}
}
InspectorTest.editNodePart = function(node, className)
{
var treeElement = InspectorTest.firstElementsTreeOutline().findTreeElement(node);
var textElement = treeElement.listItemElement.getElementsByClassName(className)[0];
if (!textElement && treeElement.childrenListElement)
textElement = treeElement.childrenListElement.getElementsByClassName(className)[0];
treeElement._startEditingTarget(textElement);
return textElement;
}
InspectorTest.editNodePartAndRun = function(node, className, newValue, step2, useSniffer)
{
var editorElement = InspectorTest.editNodePart(node, className);
editorElement.textContent = newValue;
editorElement.dispatchEvent(InspectorTest.createKeyEvent("Enter"));
if (useSniffer)
InspectorTest.addSniffer(Elements.ElementsTreeOutline.prototype, "_updateModifiedNodes", step2);
else
InspectorTest.deprecatedRunAfterPendingDispatches(step2);
}
// Preload codemirror which is used for "Edit as HTML".
InspectorTest.preloadModule("text_editor");
} }
var initialize_SassEditingTest = function() { var initialize_SassEditingTest = function() {
TestRunner.loadModule('sass_test_runner');
InspectorTest.runEditingTests = function(cssAST)
{
InspectorTest.runTestSuite([
function testSetPropertyName(next)
{
var clone = cssAST.clone();
for (var property of clone.rules[0].properties)
property.name.setText("NEW-NAME");
InspectorTest.addResult(clone.document.newText().value());
next();
},
function testSetPropertyValue(next)
{
var clone = cssAST.clone();
for (var property of clone.rules[0].properties)
property.value.setText("NEW-VALUE");
InspectorTest.addResult(clone.document.newText().value());
next();
},
function testDisableProperties(next)
{
var clone = cssAST.clone();
for (var property of clone.rules[0].properties)
property.setDisabled(true);
InspectorTest.addResult(clone.document.newText().value());
next();
},
function testEnableProperties(next)
{
var clone = cssAST.clone();
for (var property of clone.rules[0].properties)
property.setDisabled(false);
InspectorTest.addResult(clone.document.newText().value());
next();
},
function testRemoveFirstProperty(next)
{
var clone = cssAST.clone();
clone.rules[0].properties[0].remove();
InspectorTest.addResult(clone.document.newText().value());
next();
},
function testRemoveAllProperties(next)
{
var clone = cssAST.clone();
var properties = clone.rules[0].properties;
while (properties.length)
properties[0].remove();
InspectorTest.addResult(clone.document.newText().value());
next();
},
function testInsertFirstProperty(next)
{
var clone = cssAST.clone();
var rule = clone.rules[0];
rule.insertProperties(null, ["NEW-NAME"], ["NEW-VALUE"], [false]);
InspectorTest.addResult(clone.document.newText().value());
next();
},
function testInsertLastProperty(next)
{
var clone = cssAST.clone();
var rule = clone.rules[0];
var anchor = rule.properties[rule.properties.length - 1];
rule.insertProperties(anchor, ["NEW-NAME"], ["NEW-VALUE"], [false]);
InspectorTest.addResult(clone.document.newText().value());
next();
},
function testInsertDisabledProperty(next)
{
var clone = cssAST.clone();
var rule = clone.rules[0];
var anchor = rule.properties[0];
rule.insertProperties(anchor, ["NEW-NAME"], ["NEW-VALUE"], [true]);
InspectorTest.addResult(clone.document.newText().value());
next();
},
function testInsertMultipleProperties(next)
{
var clone = cssAST.clone();
var rule = clone.rules[0];
var anchor = rule.properties[rule.properties.length - 1];
rule.insertProperties(anchor, ["TRAILING-4", "TRAILING-3", "TRAILING-2", "TRAILING-1"],
["VALUE", "VALUE", "VALUE", "VALUE"],
[false, false, false, false]);
InspectorTest.addResult(clone.document.newText().value());
next();
},
function testPrependMultipleProperties(next)
{
var clone = cssAST.clone();
var rule = clone.rules[0];
rule.insertProperties(null, ["TRAILING-1", "TRAILING-2", "TRAILING-3", "TRAILING-4"],
["VALUE", "VALUE", "VALUE", "VALUE"],
[false, false, false, false]);
InspectorTest.addResult(clone.document.newText().value());
next();
},
function testAppendAndRemoveLastProperty(next)
{
var clone = cssAST.clone();
var rule = clone.rules[0];
var anchor = rule.properties[rule.properties.length - 1];
rule.insertProperties(anchor, ["NEW-NAME"], ["NEW-VALUE"], [false]);
anchor.remove();
InspectorTest.addResult(clone.document.newText().value());
next();
},
function testComplexChange(next)
{
var clone = cssAST.clone();
var rule = clone.rules[0];
var lastProperty = rule.properties[rule.properties.length - 1];
rule.insertProperties(lastProperty, ["NEW-NAME"], ["NEW-VALUE"], [false]);
lastProperty.name.setText("CHANGED");
rule.properties[0].value.setText("CHANGED");
rule.properties[1].setDisabled(true);
InspectorTest.addResult(clone.document.newText().value());
next();
},
]);
}
} }
function initialize_EditorTests() function initialize_EditorTests() {
{ InspectorTest.preloadModule("sources_test_runner");
InspectorTest.createTestEditor = function(clientHeight, textEditorDelegate)
{
var textEditor = new SourceFrame.SourcesTextEditor(textEditorDelegate || new SourceFrame.SourcesTextEditorDelegate());
clientHeight = clientHeight || 100;
textEditor.element.style.height = clientHeight + "px";
textEditor.element.style.flex = "none";
textEditor.show(UI.inspectorView.element);
return textEditor;
};
function textWithSelection(text, selections)
{
if (!selections.length)
return text;
function lineWithCursor(line, column, cursorChar)
{
return line.substring(0, column) + cursorChar + line.substring(column);
}
var lines = text.split("\n");
selections.sort(TextUtils.TextRange.comparator);
for (var i = selections.length - 1; i >= 0; --i) {
var selection = selections[i];
selection = selection.normalize();
var endCursorChar = selection.isEmpty() ? "|" : "<";
lines[selection.endLine] = lineWithCursor(lines[selection.endLine], selection.endColumn, endCursorChar);
if (!selection.isEmpty()) {
lines[selection.startLine] = lineWithCursor(lines[selection.startLine], selection.startColumn, ">");
}
}
return lines.join("\n");
}
InspectorTest.dumpTextWithSelection = function(textEditor, dumpWhiteSpaces)
{
var text = textWithSelection(textEditor.text(), textEditor.selections());
if (dumpWhiteSpaces)
text = text.replace(/ /g, ".");
InspectorTest.addResult(text);
}
InspectorTest.setLineSelections = function(editor, selections)
{
var coords = [];
for (var i = 0; i < selections.length; ++i) {
var selection = selections[i];
if (typeof selection.column === "number") {
selection.from = selection.column;
selection.to = selection.column;
}
coords.push(new TextUtils.TextRange(selection.line, selection.from, selection.line, selection.to));
}
editor.setSelections(coords);
}
InspectorTest.typeIn = function(editor, typeText, callback)
{
callback = callback || new Function();
var noop = new Function();
for(var charIndex = 0; charIndex < typeText.length; ++charIndex) {
// As soon as the last key event was processed, the whole text was processed.
var iterationCallback = charIndex + 1 === typeText.length ? callback : noop;
switch (typeText[charIndex]) {
case "\n":
InspectorTest.fakeKeyEvent(editor, "Enter", null, iterationCallback);
break;
case "L":
InspectorTest.fakeKeyEvent(editor, "ArrowLeft", null, iterationCallback);
break;
case "R":
InspectorTest.fakeKeyEvent(editor, "ArrowRight", null, iterationCallback);
break;
case "U":
InspectorTest.fakeKeyEvent(editor, "ArrowUp", null, iterationCallback);
break;
case "D":
InspectorTest.fakeKeyEvent(editor, "ArrowDown", null, iterationCallback);
break;
default:
InspectorTest.fakeKeyEvent(editor, typeText[charIndex], null, iterationCallback);
}
}
}
var eventCodes = {
Enter: 13,
Home: 36,
ArrowLeft: 37,
ArrowUp: 38,
ArrowRight: 39,
ArrowDown: 40
};
function createCodeMirrorFakeEvent(editor, eventType, code, charCode, modifiers)
{
function eventPreventDefault()
{
this._handled = true;
}
var event = {
_handled: false,
type: eventType,
keyCode: code,
charCode: charCode,
preventDefault: eventPreventDefault,
stopPropagation: function(){},
target: editor._codeMirror.display.input.textarea
};
if (modifiers) {
for (var i = 0; i < modifiers.length; ++i)
event[modifiers[i]] = true;
}
return event;
}
function fakeCodeMirrorKeyEvent(editor, eventType, code, charCode, modifiers)
{
var event = createCodeMirrorFakeEvent(editor, eventType, code, charCode, modifiers);
switch(eventType) {
case "keydown":
editor._codeMirror.triggerOnKeyDown(event);
break;
case "keypress":
editor._codeMirror.triggerOnKeyPress(event);
break;
case "keyup":
editor._codeMirror.triggerOnKeyUp(event);
break;
default:
throw new Error("Unknown KeyEvent type");
}
return event._handled;
}
function fakeCodeMirrorInputEvent(editor, character)
{
if (typeof character === "string")
editor._codeMirror.display.input.textarea.value += character;
}
InspectorTest.fakeKeyEvent = function(editor, originalCode, modifiers, callback)
{
modifiers = modifiers || [];
var code;
var charCode;
if (originalCode === "'") {
code = 222;
charCode = 0;
} else if (originalCode === "\"") {
code = 222;
modifiers.push("shiftKey");
charCode = 34;
} else if (originalCode === "(") {
code = "9".charCodeAt(0);
modifiers.push("shiftKey");
charCode = originalCode.charCodeAt(0);
}
var code = code || eventCodes[originalCode] || originalCode;
if (typeof code === "string")
code = code.charCodeAt(0);
if (fakeCodeMirrorKeyEvent(editor, "keydown", code, charCode, modifiers)) {
callback();
return;
}
if (fakeCodeMirrorKeyEvent(editor, "keypress", code, charCode, modifiers)) {
callback();
return;
}
fakeCodeMirrorInputEvent(editor, originalCode);
fakeCodeMirrorKeyEvent(editor, "keyup", code, charCode, modifiers);
function callbackWrapper()
{
editor._codeMirror.off("inputRead", callbackWrapper);
callback();
}
editor._codeMirror.on("inputRead", callbackWrapper);
}
InspectorTest.dumpSelectionStats = function(textEditor)
{
var listHashMap = {};
var sortedKeys = [];
var selections = textEditor.selections();
for (var i = 0; i < selections.length; ++i) {
var selection = selections[i];
var text = textEditor.text(selection);
if (!listHashMap[text]) {
listHashMap[text] = 1;
sortedKeys.push(text);
} else {
++listHashMap[text];
}
}
for (var i = 0; i < sortedKeys.length; ++i) {
var keyName = sortedKeys[i];
if (!keyName.length)
keyName = "<Empty string>";
else
keyName = "'" + keyName + "'";
InspectorTest.addResult(keyName + ": " + listHashMap[sortedKeys[i]]);
}
}
} }
var initialize_ElementPanelShadowSelection = function() { var initialize_ElementPanelShadowSelection = function() {
InspectorTest.preloadModule("elements_test_runner");
InspectorTest.selectReloadAndDump = function(next, node) };
{
InspectorTest.selectNode(node).then(onSelected);
var reloaded = false;
var selected = false;
function onSelected()
{
InspectorTest.reloadPage(onReloaded);
InspectorTest.addSniffer(Elements.ElementsPanel.prototype, "_lastSelectedNodeSelectedForTest", onReSelected);
}
function onReloaded()
{
reloaded = true;
maybeDumpSelectedNode();
}
function onReSelected()
{
selected = true;
maybeDumpSelectedNode();
}
function maybeDumpSelectedNode()
{
if (!reloaded || !selected)
return;
var selectedElement = InspectorTest.firstElementsTreeOutline().selectedTreeElement;
var nodeName = selectedElement ? selectedElement.node().nodeNameInCorrectCase() : "null";
InspectorTest.addResult("Selected node: '" + nodeName + "'");
next();
}
}
}
function foo() {
bar();
}
// Example text
// Example text 2
// Preserve lines for test
var initialize_SetOuterHTMLTest = function() { var initialize_SetOuterHTMLTest = function() {
InspectorTest.preloadModule("elements_test_runner");
InspectorTest.events = [];
InspectorTest.containerId;
InspectorTest.setUpTestSuite = function(next)
{
InspectorTest.expandElementsTree(step1);
function step1()
{
InspectorTest.selectNodeWithId("container", step2);
}
function step2(node)
{
InspectorTest.containerId = node.id;
InspectorTest.DOMAgent.getOuterHTML(InspectorTest.containerId).then(step3);
}
function step3(text)
{
InspectorTest.containerText = text;
for (var key in SDK.DOMModel.Events) {
var eventName = SDK.DOMModel.Events[key];
if (eventName === SDK.DOMModel.Events.MarkersChanged || eventName === SDK.DOMModel.Events.DOMMutated)
continue;
InspectorTest.domModel.addEventListener(eventName, InspectorTest.recordEvent.bind(InspectorTest, eventName));
}
next();
}
}
InspectorTest.recordEvent = function(eventName, event)
{
if (!event.data)
return;
var node = event.data.node || event.data;
var parent = event.data.parent;
for (var currentNode = parent || node; currentNode; currentNode = currentNode.parentNode) {
if (currentNode.getAttribute("id") === "output")
return;
}
InspectorTest.events.push("Event " + eventName.toString() + ": " + node.nodeName());
}
InspectorTest.patchOuterHTML = function(pattern, replacement, next)
{
InspectorTest.addResult("Replacing '" + pattern + "' with '" + replacement + "'\n");
InspectorTest.setOuterHTML(InspectorTest.containerText.replace(pattern, replacement), next);
}
InspectorTest.patchOuterHTMLUseUndo = function(pattern, replacement, next)
{
InspectorTest.addResult("Replacing '" + pattern + "' with '" + replacement + "'\n");
InspectorTest.setOuterHTMLUseUndo(InspectorTest.containerText.replace(pattern, replacement), next);
}
InspectorTest.setOuterHTML = function(newText, next)
{
InspectorTest.innerSetOuterHTML(newText, false, bringBack);
function bringBack()
{
InspectorTest.addResult("\nBringing things back\n");
InspectorTest.innerSetOuterHTML(InspectorTest.containerText, true, next);
}
}
InspectorTest.setOuterHTMLUseUndo = function(newText, next)
{
InspectorTest.innerSetOuterHTML(newText, false, bringBack);
async function bringBack()
{
InspectorTest.addResult("\nBringing things back\n");
await InspectorTest.domModel.undo();
InspectorTest._dumpOuterHTML(true, next);
}
}
InspectorTest.innerSetOuterHTML = async function(newText, last, next)
{
await InspectorTest.DOMAgent.setOuterHTML(InspectorTest.containerId, newText);
InspectorTest._dumpOuterHTML(last, next);
}
InspectorTest._dumpOuterHTML = async function(last, next)
{
var result = await InspectorTest.RuntimeAgent.evaluate("document.getElementById(\"identity\").wrapperIdentity");
InspectorTest.addResult("Wrapper identity: " + result.value);
InspectorTest.events.sort();
for (var i = 0; i < InspectorTest.events.length; ++i)
InspectorTest.addResult(InspectorTest.events[i]);
InspectorTest.events = [];
var text = await InspectorTest.DOMAgent.getOuterHTML(InspectorTest.containerId);
InspectorTest.addResult("==========8<==========");
InspectorTest.addResult(text);
InspectorTest.addResult("==========>8==========");
if (last)
InspectorTest.addResult("\n\n\n");
next();
}
}; };
...@@ -7,8 +7,6 @@ ...@@ -7,8 +7,6 @@
await TestRunner.loadModule('sources_test_runner'); await TestRunner.loadModule('sources_test_runner');
await TestRunner.showPanel('sources'); await TestRunner.showPanel('sources');
await TestRunner.addStylesheetTag('./resources/empty.css'); await TestRunner.addStylesheetTag('./resources/empty.css');
await TestRunner.addScriptTag('../resources/autocomplete-test.js');
await TestRunner.addScriptTag('../resources/editor-test.js');
SourcesTestRunner.showScriptSource('empty.css', onSourceFrame); SourcesTestRunner.showScriptSource('empty.css', onSourceFrame);
......
...@@ -7,8 +7,6 @@ ...@@ -7,8 +7,6 @@
await TestRunner.loadModule('sources_test_runner'); await TestRunner.loadModule('sources_test_runner');
await TestRunner.showPanel('sources'); await TestRunner.showPanel('sources');
await TestRunner.addStylesheetTag('./resources/empty.css'); await TestRunner.addStylesheetTag('./resources/empty.css');
await TestRunner.addScriptTag('../resources/autocomplete-test.js');
await TestRunner.addScriptTag('../resources/editor-test.js');
SourcesTestRunner.showScriptSource('empty.scss', onSourceFrame); SourcesTestRunner.showScriptSource('empty.scss', onSourceFrame);
......
var initialize_SourcesTest = function() { var initialize_SourcesTest = function() {
InspectorTest.preloadModule('sources_test_runner');
InspectorTest.preloadPanel("sources"); InspectorTest.preloadPanel("sources");
function testSourceMapping(text1, text2, mapping, testToken)
{
var originalPosition = text1.indexOf(testToken);
InspectorTest.assertTrue(originalPosition !== -1);
var originalLocation = Formatter.Formatter.positionToLocation(text1.computeLineEndings(), originalPosition);
var formattedLocation = mapping.originalToFormatted(originalLocation[0], originalLocation[1]);
var formattedPosition = Formatter.Formatter.locationToPosition(text2.computeLineEndings(), formattedLocation[0], formattedLocation[1]);
var expectedFormattedPosition = text2.indexOf(testToken);
if (expectedFormattedPosition === formattedPosition)
InspectorTest.addResult(String.sprintf("Correct mapping for <%s>", testToken));
else
InspectorTest.addResult(String.sprintf("ERROR: Wrong mapping for <%s>", testToken));
};
InspectorTest.testPrettyPrint = function(mimeType, text, mappingQueries, next)
{
new Formatter.ScriptFormatter(mimeType, text, didFormatContent);
function didFormatContent(formattedSource, mapping)
{
InspectorTest.addResult("====== 8< ------");
InspectorTest.addResult(formattedSource);
InspectorTest.addResult("------ >8 ======");
while (mappingQueries && mappingQueries.length)
testSourceMapping(text, formattedSource, mapping, mappingQueries.shift());
next();
}
}
InspectorTest.testJavascriptOutline = function(text) {
var fulfill;
var promise = new Promise(x => fulfill = x);
Formatter.formatterWorkerPool().javaScriptOutline(text, onChunk);
var items = [];
return promise;
function onChunk(isLastChunk, outlineItems) {
items.pushAll(outlineItems);
if (!isLastChunk)
return;
InspectorTest.addResult('Text:');
InspectorTest.addResult(text.split('\n').map(line => ' ' + line).join('\n'));
InspectorTest.addResult('Outline:');
for (var item of items)
InspectorTest.addResult(' ' + item.name + (item.arguments || '') + ':' + item.line + ':' + item.column);
fulfill();
}
}
InspectorTest.dumpSwatchPositions = function(sourceFrame, bookmarkType)
{
var textEditor = sourceFrame.textEditor;
var markers = textEditor.bookmarks(textEditor.fullRange(), bookmarkType);
for (var i = 0; i < markers.length; i++) {
var position = markers[i].position();
var text = markers[i]._marker.widgetNode.firstChild.textContent;
InspectorTest.addResult("Line " + position.startLine + ", Column " + position.startColumn + ": " + text);
}
}
}; };
...@@ -7,76 +7,23 @@ ...@@ -7,76 +7,23 @@
* @suppress {accessControls} * @suppress {accessControls}
*/ */
/** DataGridTestRunner.dumpDataGrid = function(root, descentIntoCollapsed, prefix) {
* @param {!DataGrid.DataGrid} dataGrid if (!prefix)
*/ prefix = '';
DataGridTestRunner.dumpDataGrid = function(dataGrid) { var suffix = root.selected ? ' <- selected' : '';
TestRunner.addResult(DataGridTestRunner.dumpDataGridIntoString(dataGrid)); var columnKeys = root.dataGrid._columnsArray.map(column => column.id);
}; var outputColumns = [];
for (var key of columnKeys) {
/** if (key in root.data)
* @param {!DataGrid.DataGrid} dataGrid outputColumns.push(root.data[key]);
* @return {string}
*/
DataGridTestRunner.dumpDataGridIntoString = function(dataGrid) {
var tableElement = dataGrid.element;
var textRows = [];
var textWidths = [];
var rows = tableElement.getElementsByTagName('tr');
for (var i = 0; i < rows.length; ++i) {
var row = rows[i];
if (!row.offsetHeight || !row.textContent)
continue;
var textCols = [];
var cols = row.getElementsByTagName('td');
for (var j = 0; j < cols.length; ++j) {
var col = cols[j];
if (!col.offsetHeight)
continue;
var index = textCols.length;
var content = col.textContent || (col.firstChild && col.firstChild.title) || '';
var text = padding(col) + content;
textWidths[index] = Math.max(textWidths[index] || 0, text.length);
textCols[index] = text;
}
if (textCols.length)
textRows.push(textCols);
} }
if (outputColumns.length)
TestRunner.addResult(prefix + outputColumns.join(' | ') + suffix);
/** if (!descentIntoCollapsed && !root.expanded)
* @param {!Node} target return;
* @return {string} for (var child of root.children)
*/ DataGridTestRunner.dumpDataGrid(child, descentIntoCollapsed, prefix + ' ');
function padding(target) {
var cell = target.enclosingNodeOrSelfWithNodeName('td');
if (!cell.classList.contains('disclosure'))
return '';
var node = dataGrid.dataGridNodeFromNode(target);
var spaces = (node ? node.depth : 0) * 2;
return Array(spaces + 1).join(' ');
}
/**
* @param {string} text
* @param {number} width
*/
function alignText(text, width) {
var spaces = width - text.length;
return text + Array(spaces + 1).join(' ');
}
var output = [];
for (var i = 0; i < textRows.length; ++i) {
var line = '';
for (var j = 0; j < textRows[i].length; ++j) {
if (j)
line += ' | ';
line += alignText(textRows[i][j], textWidths[j]);
}
line += '|';
output.push(line);
}
return output.join('\n');
}; };
DataGridTestRunner.validateDataGrid = function(root) { DataGridTestRunner.validateDataGrid = function(root) {
......
...@@ -372,7 +372,7 @@ PerformanceTestRunner.loadTimeline = function(timelineData) { ...@@ -372,7 +372,7 @@ PerformanceTestRunner.loadTimeline = function(timelineData) {
TestRunner.initAsync(` TestRunner.initAsync(`
function wrapCallFunctionForTimeline(f) { function wrapCallFunctionForTimeline(f) {
var script = document.createElement('script'); var script = document.createElement('script');
script.textContent = '(' + f.toString() + ')()\n//# sourceURL=wrapCallFunctionForTimeline.js'; script.textContent = '(' + f.toString() + ')()\\n//# sourceURL=wrapCallFunctionForTimeline.js';
document.body.appendChild(script); document.body.appendChild(script);
} }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment