diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 17:32:43 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 17:32:43 +0000 |
commit | 6bf0a5cb5034a7e684dcc3500e841785237ce2dd (patch) | |
tree | a68f146d7fa01f0134297619fbe7e33db084e0aa /devtools/shared/webconsole/test | |
parent | Initial commit. (diff) | |
download | thunderbird-6bf0a5cb5034a7e684dcc3500e841785237ce2dd.tar.xz thunderbird-6bf0a5cb5034a7e684dcc3500e841785237ce2dd.zip |
Adding upstream version 1:115.7.0.upstream/1%115.7.0upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to '')
41 files changed, 4992 insertions, 0 deletions
diff --git a/devtools/shared/webconsole/test/browser/browser.ini b/devtools/shared/webconsole/test/browser/browser.ini new file mode 100644 index 0000000000..1b66699410 --- /dev/null +++ b/devtools/shared/webconsole/test/browser/browser.ini @@ -0,0 +1,13 @@ +[DEFAULT] +tags = devtools +subsuite = devtools +support-files = + head.js + data.json + data.json^headers^ + network_requests_iframe.html + !/devtools/client/shared/test/shared-head.js + !/devtools/client/shared/test/telemetry-test-helpers.js + +[browser_commands_registration.js] +[browser_network_longstring.js] diff --git a/devtools/shared/webconsole/test/browser/browser_commands_registration.js b/devtools/shared/webconsole/test/browser/browser_commands_registration.js new file mode 100644 index 0000000000..5ab2c848c4 --- /dev/null +++ b/devtools/shared/webconsole/test/browser/browser_commands_registration.js @@ -0,0 +1,78 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +// Test for Web Console commands registration. + +add_task(async function () { + const tab = await addTab("data:text/html,<div id=quack></div>"); + + const commands = await CommandsFactory.forTab(tab); + await commands.targetCommand.startListening(); + + // Fetch WebConsoleCommandsManager so that it is available for next Content Tasks + await ContentTask.spawn(gBrowser.selectedBrowser, null, function () { + const { require } = ChromeUtils.importESModule( + "resource://devtools/shared/loader/Loader.sys.mjs" + ); + const { + WebConsoleCommandsManager, + } = require("resource://devtools/server/actors/webconsole/commands/manager.js"); + + // Bind the symbol on this in order to make it available for next tasks + this.WebConsoleCommandsManager = WebConsoleCommandsManager; + }); + + await registerNewCommand(commands); + await registerAccessor(commands); +}); + +async function evaluateJSAndCheckResult(commands, input, expected) { + const response = await commands.scriptCommand.execute(input); + checkObject(response, expected); +} + +async function registerNewCommand(commands) { + await ContentTask.spawn(gBrowser.selectedBrowser, null, function () { + this.WebConsoleCommandsManager.register("setFoo", (owner, value) => { + owner.window.foo = value; + return "ok"; + }); + }); + + const command = "setFoo('bar')"; + await evaluateJSAndCheckResult(commands, command, { + input: command, + result: "ok", + }); + + await ContentTask.spawn(gBrowser.selectedBrowser, null, function () { + is(content.top.foo, "bar", "top.foo should equal to 'bar'"); + }); +} + +async function registerAccessor(commands) { + await ContentTask.spawn(gBrowser.selectedBrowser, null, function () { + this.WebConsoleCommandsManager.register("$foo", { + get(owner) { + const foo = owner.window.document.getElementById("quack"); + return owner.makeDebuggeeValue(foo); + }, + }); + }); + + const command = "$foo.textContent = '>o_/'"; + await evaluateJSAndCheckResult(commands, command, { + input: command, + result: ">o_/", + }); + + await ContentTask.spawn(gBrowser.selectedBrowser, null, function () { + is( + content.document.getElementById("quack").textContent, + ">o_/", + '#foo textContent should equal to ">o_/"' + ); + }); +} diff --git a/devtools/shared/webconsole/test/browser/browser_network_longstring.js b/devtools/shared/webconsole/test/browser/browser_network_longstring.js new file mode 100644 index 0000000000..782e5c5fc1 --- /dev/null +++ b/devtools/shared/webconsole/test/browser/browser_network_longstring.js @@ -0,0 +1,183 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +// Test that the network actor uses the LongStringActor + +const { + DevToolsServer, +} = require("resource://devtools/server/devtools-server.js"); +const LONG_STRING_LENGTH = 400; +const LONG_STRING_INITIAL_LENGTH = 400; +let ORIGINAL_LONG_STRING_LENGTH, ORIGINAL_LONG_STRING_INITIAL_LENGTH; + +add_task(async function () { + const tab = await addTab(URL_ROOT + "network_requests_iframe.html"); + + const commands = await CommandsFactory.forTab(tab); + await commands.targetCommand.startListening(); + const target = commands.targetCommand.targetFront; + + // Override the default long string settings to lower values. + // This is done from the parent process's DevToolsServer as the LongString + // actor is being created from the parent process as network requests are + // watched from the parent process. + ORIGINAL_LONG_STRING_LENGTH = DevToolsServer.LONG_STRING_LENGTH; + ORIGINAL_LONG_STRING_INITIAL_LENGTH = + DevToolsServer.LONG_STRING_INITIAL_LENGTH; + + DevToolsServer.LONG_STRING_LENGTH = LONG_STRING_LENGTH; + DevToolsServer.LONG_STRING_INITIAL_LENGTH = LONG_STRING_INITIAL_LENGTH; + + info("test network POST request"); + const networkResource = await new Promise(resolve => { + commands.resourceCommand + .watchResources([commands.resourceCommand.TYPES.NETWORK_EVENT], { + onAvailable: () => {}, + onUpdated: resourceUpdate => { + resolve(resourceUpdate[0].resource); + }, + }) + .then(() => { + // Spawn the network request after we started watching + SpecialPowers.spawn(gBrowser.selectedBrowser, [], async function () { + content.wrappedJSObject.testXhrPost(); + }); + }); + }); + + const netActor = networkResource.actor; + ok(netActor, "We have a netActor:" + netActor); + + const webConsoleFront = await target.getFront("console"); + const requestHeaders = await webConsoleFront.getRequestHeaders(netActor); + assertRequestHeaders(requestHeaders); + const requestCookies = await webConsoleFront.getRequestCookies(netActor); + assertRequestCookies(requestCookies); + const requestPostData = await webConsoleFront.getRequestPostData(netActor); + assertRequestPostData(requestPostData); + const responseHeaders = await webConsoleFront.getResponseHeaders(netActor); + assertResponseHeaders(responseHeaders); + const responseCookies = await webConsoleFront.getResponseCookies(netActor); + assertResponseCookies(responseCookies); + const responseContent = await webConsoleFront.getResponseContent(netActor); + assertResponseContent(responseContent); + const eventTimings = await webConsoleFront.getEventTimings(netActor); + assertEventTimings(eventTimings); + + await commands.destroy(); + + DevToolsServer.LONG_STRING_LENGTH = ORIGINAL_LONG_STRING_LENGTH; + DevToolsServer.LONG_STRING_INITIAL_LENGTH = + ORIGINAL_LONG_STRING_INITIAL_LENGTH; +}); + +function assertRequestHeaders(response) { + info("checking request headers"); + + ok(!!response.headers.length, "request headers > 0"); + ok(response.headersSize > 0, "request headersSize > 0"); + + checkHeadersOrCookies(response.headers, { + Referer: /network_requests_iframe\.html/, + Cookie: /bug768096/, + }); +} + +function assertRequestCookies(response) { + info("checking request cookies"); + + is(response.cookies.length, 3, "request cookies length"); + + checkHeadersOrCookies(response.cookies, { + foobar: "fooval", + omgfoo: "bug768096", + badcookie: "bug826798=st3fan", + }); +} + +function assertRequestPostData(response) { + info("checking request POST data"); + + checkObject(response, { + postData: { + text: { + type: "longString", + initial: /^Hello world! foobaz barr.+foobaz barrfo$/, + length: 563, + actor: /[a-z]/, + }, + }, + postDataDiscarded: false, + }); + + is( + response.postData.text.initial.length, + LONG_STRING_INITIAL_LENGTH, + "postData text initial length" + ); +} + +function assertResponseHeaders(response) { + info("checking response headers"); + + ok(!!response.headers.length, "response headers > 0"); + ok(response.headersSize > 0, "response headersSize > 0"); + + checkHeadersOrCookies(response.headers, { + "content-type": /^application\/(json|octet-stream)$/, + "content-length": /^\d+$/, + "x-very-short": "hello world", + "x-very-long": { + type: "longString", + length: 521, + initial: /^Lorem ipsum.+\. Donec vitae d$/, + actor: /[a-z]/, + }, + }); +} + +function assertResponseCookies(response) { + info("checking response cookies"); + + is(response.cookies.length, 0, "response cookies length"); +} + +function assertResponseContent(response) { + info("checking response content"); + + checkObject(response, { + content: { + text: { + type: "longString", + initial: /^\{ id: "test JSON data"(.|\r|\n)+ barfoo ba$/g, + length: 1070, + actor: /[a-z]/, + }, + }, + contentDiscarded: false, + }); + + is( + response.content.text.initial.length, + LONG_STRING_INITIAL_LENGTH, + "content initial length" + ); +} + +function assertEventTimings(response) { + info("checking event timings"); + + checkObject(response, { + timings: { + blocked: /^-1|\d+$/, + dns: /^-1|\d+$/, + connect: /^-1|\d+$/, + send: /^-1|\d+$/, + wait: /^-1|\d+$/, + receive: /^-1|\d+$/, + }, + totalTime: /^\d+$/, + }); +} diff --git a/devtools/shared/webconsole/test/browser/data.json b/devtools/shared/webconsole/test/browser/data.json new file mode 100644 index 0000000000..d46085c124 --- /dev/null +++ b/devtools/shared/webconsole/test/browser/data.json @@ -0,0 +1,3 @@ +{ id: "test JSON data", myArray: [ "foo", "bar", "baz", "biff" ], + veryLong: "foo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo bar" +} diff --git a/devtools/shared/webconsole/test/browser/data.json^headers^ b/devtools/shared/webconsole/test/browser/data.json^headers^ new file mode 100644 index 0000000000..bb6b45500f --- /dev/null +++ b/devtools/shared/webconsole/test/browser/data.json^headers^ @@ -0,0 +1,3 @@ +Content-Type: application/json +x-very-long: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse a ipsum massa. Phasellus at elit dictum libero laoreet sagittis. Phasellus condimentum ultricies imperdiet. Nam eu ligula justo, ut tincidunt quam. Etiam sollicitudin, tortor sed egestas blandit, sapien sem tincidunt nulla, eu luctus libero odio quis leo. Nam elit massa, mattis quis blandit ac, facilisis vitae arcu. Donec vitae dictum neque. Proin ornare nisl at lectus commodo iaculis eget eget est. Quisque scelerisque vestibulum quam sed interdum. +x-very-short: hello world diff --git a/devtools/shared/webconsole/test/browser/head.js b/devtools/shared/webconsole/test/browser/head.js new file mode 100644 index 0000000000..cdfc7ab59a --- /dev/null +++ b/devtools/shared/webconsole/test/browser/head.js @@ -0,0 +1,61 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +Services.scriptloader.loadSubScript( + "chrome://mochitests/content/browser/devtools/client/shared/test/shared-head.js", + this +); + +function checkObject(object, expected) { + for (const name of Object.keys(expected)) { + const expectedValue = expected[name]; + const value = object[name]; + checkValue(name, value, expectedValue); + } +} + +function checkValue(name, value, expected) { + if (expected === null) { + is(value, null, "'" + name + "' is null"); + } else if (value === null) { + ok(false, "'" + name + "' is null"); + } else if (value === undefined) { + ok(false, "'" + name + "' is undefined"); + } else if ( + typeof expected == "string" || + typeof expected == "number" || + typeof expected == "boolean" + ) { + is(value, expected, "property '" + name + "'"); + } else if (expected instanceof RegExp) { + ok(expected.test(value), name + ": " + expected + " matched " + value); + } else if (Array.isArray(expected)) { + info("checking array for property '" + name + "'"); + checkObject(value, expected); + } else if (typeof expected == "object") { + info("checking object for property '" + name + "'"); + checkObject(value, expected); + } +} + +function checkHeadersOrCookies(array, expected) { + const foundHeaders = {}; + + for (const elem of array) { + if (!(elem.name in expected)) { + continue; + } + foundHeaders[elem.name] = true; + info("checking value of header " + elem.name); + checkValue(elem.name, elem.value, expected[elem.name]); + } + + for (const header in expected) { + if (!(header in foundHeaders)) { + ok(false, header + " was not found"); + } + } +} diff --git a/devtools/shared/webconsole/test/browser/network_requests_iframe.html b/devtools/shared/webconsole/test/browser/network_requests_iframe.html new file mode 100644 index 0000000000..4e96364b06 --- /dev/null +++ b/devtools/shared/webconsole/test/browser/network_requests_iframe.html @@ -0,0 +1,66 @@ +<!DOCTYPE HTML> +<html> + <head> + <meta charset="utf-8"> + <title>Console HTTP test page</title> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> + <script type="text/javascript"><!-- + "use strict"; + let setAllowAllCookies = false; + + function makeXhr(method, url, requestBody, callback) { + // On the first call, allow all cookies and set cookies, then resume the actual test + if (!setAllowAllCookies) { + SpecialPowers.pushPrefEnv({"set": [["network.cookie.cookieBehavior", 0]]}, + function() { + setAllowAllCookies = true; + setCookies(); + makeXhrCallback(method, url, requestBody, callback); + }); + } else { + makeXhrCallback(method, url, requestBody, callback); + } + } + + function makeXhrCallback(method, url, requestBody, callback) { + const xmlhttp = new XMLHttpRequest(); + xmlhttp.open(method, url, true); + if (callback) { + xmlhttp.onreadystatechange = function() { + if (xmlhttp.readyState == 4) { + callback(); + } + }; + } + xmlhttp.send(requestBody); + } + + /* exported testXhrGet */ + function testXhrGet(callback) { + makeXhr("get", "data.json", null, callback); + } + + /* exported testXhrPost */ + function testXhrPost(callback) { + const body = "Hello world! " + "foobaz barr".repeat(50); + makeXhr("post", "data.json", body, callback); + } + + function setCookies() { + document.cookie = "foobar=fooval"; + document.cookie = "omgfoo=bug768096"; + document.cookie = "badcookie=bug826798=st3fan"; + } + </script> + </head> + <body> + <h1>Web Console HTTP Logging Testpage</h1> + <h2>This page is used to test the HTTP logging.</h2> + + <form action="?" method="post"> + <input name="name" type="text" value="foo bar"><br> + <input name="age" type="text" value="144"><br> + </form> + </body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/chrome.ini b/devtools/shared/webconsole/test/chrome/chrome.ini new file mode 100644 index 0000000000..ee903ac727 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/chrome.ini @@ -0,0 +1,34 @@ +[DEFAULT] +tags = devtools +support-files = + common.js + data.json + data.json^headers^ + helper_serviceworker.js + network_requests_iframe.html + sandboxed_iframe.html + console-test-worker.js + !/browser/base/content/test/general/browser_star_hsts.sjs + +[test_basics.html] +[test_cached_messages.html] +[test_consoleapi.html] +[test_consoleapi_innerID.html] +[test_console_assert.html] +[test_console_group_styling.html] +[test_console_serviceworker.html] +[test_console_serviceworker_cached.html] +[test_console_styling.html] +[test_console_timestamp.html] +[test_console_worker.html] +[test_file_uri.html] +[test_jsterm_autocomplete.html] +[test_network_get.html] +skip-if = verify +[test_network_post.html] +[test_network_security-hsts.html] +[test_nsiconsolemessage.html] +[test_object_actor.html] +[test_object_actor_native_getters.html] +[test_object_actor_native_getters_lenient_this.html] +[test_page_errors.html] diff --git a/devtools/shared/webconsole/test/chrome/common.js b/devtools/shared/webconsole/test/chrome/common.js new file mode 100644 index 0000000000..62878d7e60 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/common.js @@ -0,0 +1,274 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +/* exported attachConsole, attachConsoleToTab, attachConsoleToWorker, + closeDebugger, checkConsoleAPICalls, checkRawHeaders, runTests, nextTest, Ci, Cc, + withActiveServiceWorker, Services, consoleAPICall, createCommandsForTab, FRACTIONAL_NUMBER_REGEX, DevToolsServer */ + +const { require } = ChromeUtils.importESModule( + "resource://devtools/shared/loader/Loader.sys.mjs" +); +const { + DevToolsServer, +} = require("resource://devtools/server/devtools-server.js"); +const { + CommandsFactory, +} = require("resource://devtools/shared/commands/commands-factory.js"); + +// timeStamp are the result of a number in microsecond divided by 1000. +// so we can't expect a precise number of decimals, or even if there would +// be decimals at all. +const FRACTIONAL_NUMBER_REGEX = /^\d+(\.\d{1,3})?$/; + +function attachConsole(listeners) { + return _attachConsole(listeners); +} +function attachConsoleToTab(listeners) { + return _attachConsole(listeners, true); +} +function attachConsoleToWorker(listeners) { + return _attachConsole(listeners, true, true); +} + +var _attachConsole = async function (listeners, attachToTab, attachToWorker) { + try { + function waitForMessage(target) { + return new Promise(resolve => { + target.addEventListener("message", resolve, { once: true }); + }); + } + + // Fetch the console actor out of the expected target + // ParentProcessTarget / WorkerTarget / FrameTarget + let commands, target, worker; + if (!attachToTab) { + commands = await CommandsFactory.forMainProcess(); + target = await commands.descriptorFront.getTarget(); + } else { + commands = await CommandsFactory.forCurrentTabInChromeMochitest(); + // Descriptor's getTarget will only work if the TargetCommand watches for the first top target + await commands.targetCommand.startListening(); + target = await commands.descriptorFront.getTarget(); + if (attachToWorker) { + const workerName = "console-test-worker.js#" + new Date().getTime(); + worker = new Worker(workerName); + await waitForMessage(worker); + + const { workers } = await target.listWorkers(); + target = workers.filter(w => w.url == workerName)[0]; + if (!target) { + console.error( + "listWorkers failed. Unable to find the worker actor\n" + ); + return null; + } + // This is still important to attach workers as target is still a descriptor front + // which "becomes" a target when calling this method: + await target.morphWorkerDescriptorIntoWorkerTarget(); + } + } + + // Attach the Target and the target thread in order to instantiate the console client. + await target.attachThread(); + + const webConsoleFront = await target.getFront("console"); + + // By default the console isn't listening for anything, + // request listeners from here + const response = await webConsoleFront.startListeners(listeners); + return { + state: { + dbgClient: commands.client, + webConsoleFront, + actor: webConsoleFront.actor, + // Keep a strong reference to the Worker to avoid it being + // GCd during the test (bug 1237492). + // eslint-disable-next-line camelcase + _worker_ref: worker, + }, + response, + }; + } catch (error) { + console.error( + `attachConsole failed: ${error.error} ${error.message} - ` + error.stack + ); + } + return null; +}; + +async function createCommandsForTab() { + const commands = await CommandsFactory.forMainProcess(); + await commands.targetCommand.startListening(); + return commands; +} + +function closeDebugger(state, callback) { + const onClose = state.dbgClient.close(); + + state.dbgClient = null; + state.client = null; + + if (typeof callback === "function") { + onClose.then(callback); + } + return onClose; +} + +function checkConsoleAPICalls(consoleCalls, expectedConsoleCalls) { + is( + consoleCalls.length, + expectedConsoleCalls.length, + "received correct number of console calls" + ); + expectedConsoleCalls.forEach(function (message, index) { + info("checking received console call #" + index); + checkConsoleAPICall(consoleCalls[index], expectedConsoleCalls[index]); + }); +} + +function checkConsoleAPICall(call, expected) { + is( + call.arguments?.length || 0, + expected.arguments?.length || 0, + "number of arguments" + ); + + checkObject(call, expected); +} + +function checkObject(object, expected) { + if (object && object.getGrip) { + object = object.getGrip(); + } + + for (const name of Object.keys(expected)) { + const expectedValue = expected[name]; + const value = object[name]; + checkValue(name, value, expectedValue); + } +} + +function checkValue(name, value, expected) { + if (expected === null) { + ok(!value, "'" + name + "' is null"); + } else if (value === undefined) { + ok(false, "'" + name + "' is undefined"); + } else if (value === null) { + ok(false, "'" + name + "' is null"); + } else if ( + typeof expected == "string" || + typeof expected == "number" || + typeof expected == "boolean" + ) { + is(value, expected, "property '" + name + "'"); + } else if (expected instanceof RegExp) { + ok(expected.test(value), name + ": " + expected + " matched " + value); + } else if (Array.isArray(expected)) { + info("checking array for property '" + name + "'"); + checkObject(value, expected); + } else if (typeof expected == "object") { + info("checking object for property '" + name + "'"); + checkObject(value, expected); + } +} + +function checkHeadersOrCookies(array, expected) { + const foundHeaders = {}; + + for (const elem of array) { + if (!(elem.name in expected)) { + continue; + } + foundHeaders[elem.name] = true; + info("checking value of header " + elem.name); + checkValue(elem.name, elem.value, expected[elem.name]); + } + + for (const header in expected) { + if (!(header in foundHeaders)) { + ok(false, header + " was not found"); + } + } +} + +function checkRawHeaders(text, expected) { + const headers = text.split(/\r\n|\n|\r/); + const arr = []; + for (const header of headers) { + const index = header.indexOf(": "); + if (index < 0) { + continue; + } + arr.push({ + name: header.substr(0, index), + value: header.substr(index + 2), + }); + } + + checkHeadersOrCookies(arr, expected); +} + +var gTestState = {}; + +function runTests(tests, endCallback) { + function* driver() { + let lastResult, sendToNext; + for (let i = 0; i < tests.length; i++) { + gTestState.index = i; + const fn = tests[i]; + info("will run test #" + i + ": " + fn.name); + lastResult = fn(sendToNext, lastResult); + sendToNext = yield lastResult; + } + yield endCallback(sendToNext, lastResult); + } + gTestState.driver = driver(); + return gTestState.driver.next(); +} + +function nextTest(message) { + return gTestState.driver.next(message); +} + +function withActiveServiceWorker(win, url, scope) { + const opts = {}; + if (scope) { + opts.scope = scope; + } + return win.navigator.serviceWorker.register(url, opts).then(swr => { + if (swr.active) { + return swr; + } + + // Unfortunately we can't just use navigator.serviceWorker.ready promise + // here. If the service worker is for a scope that does not cover the window + // then the ready promise will never resolve. Instead monitor the service + // workers state change events to determine when its activated. + return new Promise(resolve => { + const sw = swr.waiting || swr.installing; + sw.addEventListener("statechange", function stateHandler(evt) { + if (sw.state === "activated") { + sw.removeEventListener("statechange", stateHandler); + resolve(swr); + } + }); + }); + }); +} + +/** + * + * @param {Front} consoleFront + * @param {Function} consoleCall: A function which calls the consoleAPI, e.g. : + * `() => top.console.log("test")`. + * @returns {Promise} A promise that will be resolved with the packet sent by the server + * in response to the consoleAPI call. + */ +function consoleAPICall(consoleFront, consoleCall) { + const onConsoleAPICall = consoleFront.once("consoleAPICall"); + consoleCall(); + return onConsoleAPICall; +} diff --git a/devtools/shared/webconsole/test/chrome/console-test-worker.js b/devtools/shared/webconsole/test/chrome/console-test-worker.js new file mode 100644 index 0000000000..9e92f6af65 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/console-test-worker.js @@ -0,0 +1,21 @@ +"use strict"; + +console.log("Log from worker init"); + +function f() { + const a = 1; + const b = 2; + const c = 3; + return { a, b, c }; +} + +self.onmessage = function (event) { + if (event.data == "ping") { + f(); + postMessage("pong"); + } else if (event.data?.type == "log") { + console.log(event.data.message); + } +}; + +postMessage("load"); diff --git a/devtools/shared/webconsole/test/chrome/data.json b/devtools/shared/webconsole/test/chrome/data.json new file mode 100644 index 0000000000..eca9d0e796 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/data.json @@ -0,0 +1,5 @@ +{ + "id": "test JSON data", + "myArray": ["foo", "bar", "baz", "biff"], + "veryLong": "foo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo bar" +} diff --git a/devtools/shared/webconsole/test/chrome/data.json^headers^ b/devtools/shared/webconsole/test/chrome/data.json^headers^ new file mode 100644 index 0000000000..bb6b45500f --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/data.json^headers^ @@ -0,0 +1,3 @@ +Content-Type: application/json +x-very-long: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse a ipsum massa. Phasellus at elit dictum libero laoreet sagittis. Phasellus condimentum ultricies imperdiet. Nam eu ligula justo, ut tincidunt quam. Etiam sollicitudin, tortor sed egestas blandit, sapien sem tincidunt nulla, eu luctus libero odio quis leo. Nam elit massa, mattis quis blandit ac, facilisis vitae arcu. Donec vitae dictum neque. Proin ornare nisl at lectus commodo iaculis eget eget est. Quisque scelerisque vestibulum quam sed interdum. +x-very-short: hello world diff --git a/devtools/shared/webconsole/test/chrome/helper_serviceworker.js b/devtools/shared/webconsole/test/chrome/helper_serviceworker.js new file mode 100644 index 0000000000..74092183e2 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/helper_serviceworker.js @@ -0,0 +1,21 @@ +"use strict"; + +console.log("script evaluation"); + +addEventListener("install", function (evt) { + console.log("install event"); +}); + +addEventListener("activate", function (evt) { + console.log("activate event"); +}); + +addEventListener("fetch", function (evt) { + console.log("fetch event: " + evt.request.url); + evt.respondWith(new Response("Hello world")); +}); + +addEventListener("message", function (evt) { + console.log("message event: " + evt.data.message); + evt.source.postMessage({ type: "PONG" }); +}); diff --git a/devtools/shared/webconsole/test/chrome/network_requests_iframe.html b/devtools/shared/webconsole/test/chrome/network_requests_iframe.html new file mode 100644 index 0000000000..6bb806b904 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/network_requests_iframe.html @@ -0,0 +1,66 @@ +<!DOCTYPE HTML> +<html> + <head> + <meta charset="utf-8"> + <title>Console HTTP test page</title> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> + <script type="text/javascript"><!-- + "use strict"; + let setAllowAllCookies = false; + + function makeXhr(method, url, requestBody, callback) { + // On the first call, allow all cookies and set cookies, then resume the actual test + if (!setAllowAllCookies) { + SpecialPowers.pushPrefEnv({"set": [["network.cookie.cookieBehavior", 0]]}, + function() { + setAllowAllCookies = true; + setCookies(); + makeXhrCallback(method, url, requestBody, callback); + }); + } else { + makeXhrCallback(method, url, requestBody, callback); + } + } + + function makeXhrCallback(method, url, requestBody, callback) { + const xmlhttp = new XMLHttpRequest(); + xmlhttp.open(method, url, true); + if (callback) { + xmlhttp.onreadystatechange = function() { + if (xmlhttp.readyState == 4) { + callback(); + } + }; + } + xmlhttp.send(requestBody); + } + + /* exported testXhrGet */ + function testXhrGet(callback, url = "data.json") { + makeXhr("get", url, null, callback); + } + + /* exported testXhrPost */ + function testXhrPost(callback) { + const body = "Hello world! " + (new Array(50)).join("foobaz barr"); + makeXhr("post", "data.json", body, callback); + } + + function setCookies() { + document.cookie = "foobar=fooval"; + document.cookie = "omgfoo=bug768096"; + document.cookie = "badcookie=bug826798=st3fan"; + } + </script> + </head> + <body> + <h1>Web Console HTTP Logging Testpage</h1> + <h2>This page is used to test the HTTP logging.</h2> + + <form action="?" method="post"> + <input name="name" type="text" value="foo bar"><br> + <input name="age" type="text" value="144"><br> + </form> + </body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/sandboxed_iframe.html b/devtools/shared/webconsole/test/chrome/sandboxed_iframe.html new file mode 100644 index 0000000000..55a6224b50 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/sandboxed_iframe.html @@ -0,0 +1,8 @@ +<html> +<head><title>Sandboxed iframe</title></head> +<body> + <iframe id="sandboxed-iframe" + sandbox="allow-scripts" + srcdoc="<script>var foobarObject = {bug1051224: 'sandboxed'};</script>"></iframe> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_basics.html b/devtools/shared/webconsole/test/chrome/test_basics.html new file mode 100644 index 0000000000..761a97bc8d --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_basics.html @@ -0,0 +1,61 @@ +<!DOCTYPE HTML> +<html lang="en"> +<head> + <meta charset="utf8"> + <title>Basic Web Console Actor tests</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> +</head> +<body> +<p>Basic Web Console Actor tests</p> + +<script class="testbody" type="text/javascript"> +"use strict"; + +SimpleTest.waitForExplicitFinish(); + +async function startTest() +{ + removeEventListener("load", startTest); + + let {state, response} = await attachConsoleToTab(["PageError"]); + is(response.startedListeners.length, 1, "startedListeners.length"); + is(response.startedListeners[0], "PageError", "startedListeners: PageError"); + + await closeDebugger(state); + top.console_ = top.console; + top.console = { lolz: "foo" }; + ({state, response} = await attachConsoleToTab(["PageError", "ConsoleAPI", "foo"])); + + const startedListeners = response.startedListeners; + is(startedListeners.length, 2, "startedListeners.length"); + isnot(startedListeners.indexOf("PageError"), -1, "startedListeners: PageError"); + isnot(startedListeners.indexOf("ConsoleAPI"), -1, + "startedListeners: ConsoleAPI"); + is(startedListeners.indexOf("foo"), -1, "startedListeners: no foo"); + + top.console = top.console_; + response = await state.webConsoleFront.stopListeners(["ConsoleAPI", "foo"]); + + is(response.stoppedListeners.length, 1, "stoppedListeners.length"); + is(response.stoppedListeners[0], "ConsoleAPI", "stoppedListeners: ConsoleAPI"); + await closeDebugger(state); + ({state, response} = await attachConsoleToTab(["ConsoleAPI"])); + + is(response.startedListeners.length, 1, "startedListeners.length"); + is(response.startedListeners[0], "ConsoleAPI", "startedListeners: ConsoleAPI"); + + top.console = top.console_; + delete top.console_; + + closeDebugger(state, function() { + SimpleTest.finish(); + }); +} + +addEventListener("load", startTest); +</script> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_cached_messages.html b/devtools/shared/webconsole/test/chrome/test_cached_messages.html new file mode 100644 index 0000000000..12d5069c7d --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_cached_messages.html @@ -0,0 +1,217 @@ +<!DOCTYPE HTML> +<html lang="en"> +<head> + <meta charset="utf8"> + <title>Test for cached messages</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> +</head> +<body> +<p>Test for cached messages</p> + +<script class="testbody" type="application/javascript"> +"use strict"; + +const { MESSAGE_CATEGORY } = require("devtools/shared/constants"); + +const previousEnabled = window.docShell.cssErrorReportingEnabled; +window.docShell.cssErrorReportingEnabled = true; + +SimpleTest.registerCleanupFunction(() => { + window.docShell.cssErrorReportingEnabled = previousEnabled; +}); + +var ConsoleAPIStorage = Cc["@mozilla.org/consoleAPI-storage;1"] + .getService(Ci.nsIConsoleAPIStorage); +let expectedConsoleCalls = []; +let expectedPageErrors = []; + +function doPageErrors() { + Services.console.reset(); + + expectedPageErrors = [ + { + errorMessage: /fooColor/, + sourceName: /.+/, + category: MESSAGE_CATEGORY.CSS_PARSER, + timeStamp: FRACTIONAL_NUMBER_REGEX, + error: false, + warning: true, + }, + { + errorMessage: /doTheImpossible/, + sourceName: /.+/, + category: "chrome javascript", + timeStamp: FRACTIONAL_NUMBER_REGEX, + error: true, + warning: false, + }, + ]; + + let container = document.createElement("script"); + document.body.appendChild(container); + container.textContent = "document.body.style.color = 'fooColor';"; + document.body.removeChild(container); + + SimpleTest.expectUncaughtException(); + + container = document.createElement("script"); + document.body.appendChild(container); + container.textContent = "document.doTheImpossible();"; + document.body.removeChild(container); +} + +function doConsoleCalls() { + ConsoleAPIStorage.clearEvents(); + + top.console.log("foobarBaz-log", undefined); + top.console.info("foobarBaz-info", null); + top.console.warn("foobarBaz-warn", document.body); + + expectedConsoleCalls = [ + { + level: "log", + filename: /test_cached_messages/, + timeStamp: FRACTIONAL_NUMBER_REGEX, + arguments: ["foobarBaz-log", { type: "undefined" }], + }, + { + level: "info", + filename: /test_cached_messages/, + timeStamp: FRACTIONAL_NUMBER_REGEX, + arguments: ["foobarBaz-info", { type: "null" }], + }, + { + level: "warn", + filename: /test_cached_messages/, + timeStamp: FRACTIONAL_NUMBER_REGEX, + arguments: ["foobarBaz-warn", { type: "object", actor: /[a-z]/ }], + }, + ]; +} +</script> + +<script class="testbody" type="text/javascript"> +"use strict"; + +SimpleTest.waitForExplicitFinish(); +var {ConsoleServiceListener} = + require("devtools/server/actors/webconsole/listeners/console-service"); +var {ConsoleAPIListener} = + require("devtools/server/actors/webconsole/listeners/console-api"); + +let consoleAPIListener, consoleServiceListener; +let consoleAPICalls = 0; +let pageErrors = 0; + +async function onConsoleAPICall(message) { + for (const msg of expectedConsoleCalls) { + if (msg.functionName == message.functionName && + msg.filename.test(message.filename)) { + consoleAPICalls++; + break; + } + } + if (consoleAPICalls == expectedConsoleCalls.length) { + await checkConsoleAPICache(); + } +} + +async function onConsoleServiceMessage(message) { + if (!(message instanceof Ci.nsIScriptError)) { + return; + } + for (const msg of expectedPageErrors) { + if (msg.category == message.category && + msg.errorMessage.test(message.errorMessage)) { + pageErrors++; + break; + } + } + if (pageErrors == expectedPageErrors.length) { + await testPageErrors(); + } +} + +function startTest() { + removeEventListener("load", startTest); + + consoleAPIListener = new ConsoleAPIListener(top, onConsoleAPICall); + consoleAPIListener.init(); + + doConsoleCalls(); +} + +async function checkConsoleAPICache() { + consoleAPIListener.destroy(); + consoleAPIListener = null; + const {state} = await attachConsole(["ConsoleAPI"]); + const response = await state.webConsoleFront.getCachedMessages(["ConsoleAPI"]); + onCachedConsoleAPI(state, response); +} + +function onCachedConsoleAPI(state, response) { + const msgs = response.messages; + info("cached console messages: " + msgs.length); + + ok(msgs.length >= expectedConsoleCalls.length, + "number of cached console messages"); + + for (const {message} of msgs) { + for (const expected of expectedConsoleCalls) { + if (expected.filename.test(message.filename)) { + expectedConsoleCalls.splice(expectedConsoleCalls.indexOf(expected)); + checkConsoleAPICall(message, expected); + break; + } + } + } + + is(expectedConsoleCalls.length, 0, "all expected messages have been found"); + + closeDebugger(state, function() { + consoleServiceListener = new ConsoleServiceListener(null, onConsoleServiceMessage); + consoleServiceListener.init(); + doPageErrors(); + }); +} + +async function testPageErrors() { + consoleServiceListener.destroy(); + consoleServiceListener = null; + const {state} = await attachConsole(["PageError"]); + const response = await state.webConsoleFront.getCachedMessages(["PageError"]); + onCachedPageErrors(state, response); +} + +function onCachedPageErrors(state, response) { + const msgs = response.messages; + info("cached page errors: " + msgs.length); + + ok(msgs.length >= expectedPageErrors.length, + "number of cached page errors"); + + for (const {pageError} of msgs) { + for (const expected of expectedPageErrors) { + if (expected.category == pageError.category && + expected.errorMessage.test(pageError.errorMessage)) { + expectedPageErrors.splice(expectedPageErrors.indexOf(expected)); + checkObject(pageError, expected); + break; + } + } + } + + is(expectedPageErrors.length, 0, "all expected messages have been found"); + + closeDebugger(state, function() { + SimpleTest.finish(); + }); +} + +addEventListener("load", startTest); +</script> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_console_assert.html b/devtools/shared/webconsole/test/chrome/test_console_assert.html new file mode 100644 index 0000000000..f847d5f5d8 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_console_assert.html @@ -0,0 +1,106 @@ +<!DOCTYPE HTML> +<html> +<head> + <meta charset="utf-8"> + <title>Test for console.group styling with %c</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> + <script> +"use strict"; + +window.onload = async function () { + SimpleTest.waitForExplicitFinish(); + let state; + try { + state = (await attachConsole(["ConsoleAPI"])).state; + const {webConsoleFront} = state; + + await testFalseAssert(webConsoleFront); + await testFalsyAssert(webConsoleFront); + await testUndefinedAssert(webConsoleFront); + await testNullAssert(webConsoleFront); + await testTrueAssert(webConsoleFront); + + } catch (e) { + ok(false, `Error thrown: ${e.message}`); + } + + await closeDebugger(state); + SimpleTest.finish(); +}; + +async function testFalseAssert(consoleFront) { + info(`Testing console.assert(false)`); + const packet = await consoleAPICall( + consoleFront, + () => top.console.assert(false, "assertion is false") + ); + + checkConsoleAPICall(packet.message, { + arguments: ["assertion is false"] + }); +} + +async function testFalsyAssert(consoleFront) { + info(`Testing console.assert(0")`); + const packet = await consoleAPICall( + consoleFront, + () => top.console.assert(0, "assertion is false") + ); + + checkConsoleAPICall(packet.message, { + arguments: ["assertion is false"] + }); +} + +async function testUndefinedAssert(consoleFront) { + info(`Testing console.assert(undefined)`); + const packet = await consoleAPICall( + consoleFront, + () => top.console.assert(undefined, "assertion is false") + ); + + checkConsoleAPICall(packet.message, { + arguments: ["assertion is false"] + }); +} + +async function testNullAssert(consoleFront) { + info(`Testing console.assert(null)`); + const packet = await consoleAPICall( + consoleFront, + () => top.console.assert(null, "assertion is false") + ); + + checkConsoleAPICall(packet.message, { + arguments: ["assertion is false"] + }); +} + +async function testTrueAssert(consoleFront) { + info(`Testing console.assert(true)`); + const onConsoleApiCall = consoleAPICall( + consoleFront, + () => top.console.assert(true, "assertion is false") + ); + + const TIMEOUT = Symbol(); + const onTimeout = new Promise(resolve => setTimeout(() => resolve(TIMEOUT), 1000)); + + const res = await Promise.race([onConsoleApiCall, onTimeout]); + is(res, TIMEOUT, + "There was no consoleAPICall event in response to a truthy console.assert"); +} + + </script> +</head> +<body> + <p id="display"></p> + <div id="content" style="display: none"> + </div> + <pre id="test"> + </pre> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_console_group_styling.html b/devtools/shared/webconsole/test/chrome/test_console_group_styling.html new file mode 100644 index 0000000000..23a93f8b8d --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_console_group_styling.html @@ -0,0 +1,121 @@ +<!DOCTYPE HTML> +<html> +<head> + <meta charset="utf-8"> + <title>Test for console.group styling with %c</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> + <script> +"use strict"; + +window.onload = async function () { + SimpleTest.waitForExplicitFinish(); + let state; + try { + state = (await attachConsole(["ConsoleAPI"])).state + const consoleFront = state.webConsoleFront; + + await testSingleCustomStyleGroup(consoleFront); + await testSingleCustomStyleGroupCollapsed(consoleFront); + await testMultipleCustomStyleGroup(consoleFront); + await testMultipleCustomStyleGroupCollapsed(consoleFront); + await testFormatterWithNoStyleGroup(consoleFront); + await testFormatterWithNoStyleGroupCollapsed(consoleFront); + } catch (e) { + ok(false, `Error thrown: ${e.message}`); + } + + await closeDebugger(state); + SimpleTest.finish(); +}; + +async function testSingleCustomStyleGroup(consoleFront) { + info("Testing console.group with a custom style"); + const packet = await consoleAPICall( + consoleFront, + () => top.console.group("%cfoobar", "color:red") + ); + + checkConsoleAPICall(packet.message, { + arguments: ["foobar"], + styles: ["color:red"] + }); +} + +async function testSingleCustomStyleGroupCollapsed(consoleFront) { + info("Testing console.groupCollapsed with a custom style"); + const packet = await consoleAPICall( + consoleFront, + () => top.console.groupCollapsed("%cfoobaz", "color:blue") + ); + + checkConsoleAPICall(packet.message, { + arguments: ["foobaz"], + styles: ["color:blue"] + }); +} + +async function testMultipleCustomStyleGroup(consoleFront) { + info("Testing console.group with multiple custom styles"); + const packet = await consoleAPICall( + consoleFront, + () => top.console.group("%cfoo%cbar", "color:red", "color:blue") + ); + + checkConsoleAPICall(packet.message, { + arguments: ["foo", "bar"], + styles: ["color:red", "color:blue"] + }); +} + +async function testMultipleCustomStyleGroupCollapsed(consoleFront) { + info("Testing console.groupCollapsed with multiple custom styles"); + const packet = await consoleAPICall( + consoleFront, + () => top.console.group("%cfoo%cbaz", "color:red", "color:green") + ); + + checkConsoleAPICall(packet.message, { + arguments: ["foo", "baz"], + styles: ["color:red", "color:green"] + }); +} + +async function testFormatterWithNoStyleGroup(consoleFront) { + info("Testing console.group with one formatter but no style"); + const packet = await consoleAPICall( + consoleFront, + () => top.console.group("%cfoobar") + ); + + checkConsoleAPICall(packet.message, { + arguments: ["%cfoobar"], + }); + is(packet.message.styles, undefined, "No 'styles' property"); +} + +async function testFormatterWithNoStyleGroupCollapsed(consoleFront) { + info("Testing console.groupCollapsed with one formatter but no style"); + const packet = await consoleAPICall( + consoleFront, + () => top.console.groupCollapsed("%cfoobaz") + ); + + checkConsoleAPICall(packet.message, { + arguments: ["%cfoobaz"], + }); + is(packet.message.styles, undefined, "No 'styles' property"); +} + + </script> +</head> +<body> + <p id="display"></p> + <div id="content" style="display: none"> + </div> + <pre id="test"> + </pre> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_console_serviceworker.html b/devtools/shared/webconsole/test/chrome/test_console_serviceworker.html new file mode 100644 index 0000000000..33b6ba1457 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_console_serviceworker.html @@ -0,0 +1,202 @@ +<!DOCTYPE HTML> +<html lang="en"> +<head> + <meta charset="utf8"> + <title>Test for the Console API and Service Workers</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> +</head> +<body> +<p>Test for the Console API and Service Workers</p> + +<script class="testbody" type="text/javascript"> +"use strict"; + +SimpleTest.waitForExplicitFinish(); + +// Utils functions +function withFrame(url) { + return new Promise(resolve => { + const iframe = document.createElement("iframe"); + iframe.onload = function () { + resolve(iframe); + }; + iframe.src = url; + document.body.appendChild(iframe); + }); +} + +function navigateFrame(iframe, url) { + return new Promise(resolve => { + iframe.onload = function () { + resolve(iframe); + }; + iframe.src = url; + }); +} + +function forceReloadFrame(iframe) { + return new Promise(resolve => { + iframe.onload = function () { + resolve(iframe); + }; + iframe.contentWindow.location.reload(true); + }); +} + +function messageServiceWorker(win, scope, message) { + return win.navigator.serviceWorker.getRegistration(scope).then(swr => { + return new Promise(resolve => { + win.navigator.serviceWorker.onmessage = evt => { + resolve(); + }; + const sw = swr.active || swr.waiting || swr.installing; + sw.postMessage({ type: "PING", message }); + }); + }); +} + +function unregisterServiceWorker(win) { + return win.navigator.serviceWorker.ready.then(swr => { + return swr.unregister(); + }); +} + +// Test +const BASE_URL = "https://example.com/chrome/devtools/shared/webconsole/test/chrome/"; +const SERVICE_WORKER_URL = BASE_URL + "helper_serviceworker.js"; +const SCOPE = BASE_URL + "foo/"; +const NONSCOPE_FRAME_URL = BASE_URL + "sandboxed_iframe.html"; +const SCOPE_FRAME_URL = SCOPE + "fake.html"; +const SCOPE_FRAME_URL2 = SCOPE + "whatsit.html"; +const MESSAGE = 'Tic Tock'; + +const expectedConsoleCalls = [ + { + level: "log", + filename: /helper_serviceworker/, + arguments: ['script evaluation'], + }, + { + level: "log", + filename: /helper_serviceworker/, + arguments: ['install event'], + }, + { + level: "log", + filename: /helper_serviceworker/, + arguments: ['activate event'], + }, + { + level: "log", + filename: /helper_serviceworker/, + arguments: ['fetch event: ' + SCOPE_FRAME_URL], + }, + { + level: "log", + filename: /helper_serviceworker/, + arguments: ['fetch event: ' + SCOPE_FRAME_URL2], + }, +]; +let consoleCalls = []; + +const startTest = async function () { + removeEventListener("load", startTest); + + await new Promise(resolve => { + SpecialPowers.pushPrefEnv({"set": [ + ["dom.serviceWorkers.enabled", true], + ["devtools.webconsole.filter.serviceworkers", true] + ]}, resolve); + }); + + const {state, response} = await attachConsoleToTab(["ConsoleAPI"]); + onAttach(state, response); +}; +addEventListener("load", startTest); + +const onAttach = async function (state, response) { + onConsoleAPICall = onConsoleAPICall.bind(null, state); + state.webConsoleFront.on("consoleAPICall", onConsoleAPICall); + + let currentFrame; + try { + // First, we need a frame from which to register our script. This + // will not trigger any console calls. + info("Loading a non-scope frame from which to register a service worker."); + currentFrame = await withFrame(NONSCOPE_FRAME_URL); + + // Now register the service worker and wait for it to become + // activate. This should trigger 3 console calls; 1 for script + // evaluation, 1 for the install event, and 1 for the activate + // event. These console calls are received because we called + // register(), not because we are in scope for the worker. + info("Registering the service worker"); + await withActiveServiceWorker(currentFrame.contentWindow, + SERVICE_WORKER_URL, SCOPE); + ok(!currentFrame.contentWindow.navigator.serviceWorker.controller, + 'current frame should not be controlled'); + + // Now that the service worker is activate, lets navigate our frame. + // This will trigger 1 more console call for the fetch event. + info("Service worker registered. Navigating frame."); + await navigateFrame(currentFrame, SCOPE_FRAME_URL); + ok(currentFrame.contentWindow.navigator.serviceWorker.controller, + 'navigated frame should be controlled'); + + // We now have a controlled frame. Lets perform a non-navigation fetch. + // This should produce another console call for the fetch event. + info("Frame navigated. Calling fetch()."); + await currentFrame.contentWindow.fetch(SCOPE_FRAME_URL2); + + // Now force refresh our controlled frame. This will cause the frame + // to bypass the service worker and become an uncontrolled frame. It + // also happens to make the frame display a 404 message because the URL + // does not resolve to a real resource. This is ok, as we really only + // care about the frame being non-controlled, but still having a location + // that matches our service worker scope so we can provide its not + // incorrectly getting console calls. + info("Completed fetch(). Force refreshing to get uncontrolled frame."); + await forceReloadFrame(currentFrame); + ok(!currentFrame.contentWindow.navigator.serviceWorker.controller, + 'current frame should not be controlled after force refresh'); + is(currentFrame.contentWindow.location.toString(), SCOPE_FRAME_URL, + 'current frame should still have in-scope location URL even though it got 404'); + + // Now postMessage() the service worker to trigger its message event + // handler. This will generate 1 or 2 to console.log() statements + // depending on if the worker thread needs to spin up again. In either + // case, though, we should not get any console calls because we don't + // have a controlled or registering document. + info("Completed force refresh. Messaging service worker."); + await messageServiceWorker(currentFrame.contentWindow, SCOPE, MESSAGE); + + info("Done messaging service worker. Unregistering service worker."); + await unregisterServiceWorker(currentFrame.contentWindow); + + info('Service worker unregistered. Checking console calls.'); + state.webConsoleFront.off("consoleAPICall", onConsoleAPICall); + checkConsoleAPICalls(consoleCalls, expectedConsoleCalls); + } catch(error) { + ok(false, 'unexpected error: ' + error); + } finally { + if (currentFrame) { + currentFrame.remove(); + currentFrame = null; + } + consoleCalls = []; + closeDebugger(state, function() { + SimpleTest.finish(); + }); + } +}; + +function onConsoleAPICall(state, packet) { + info("received message level: " + packet.message.level); + consoleCalls.push(packet.message); +} +</script> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_console_serviceworker_cached.html b/devtools/shared/webconsole/test/chrome/test_console_serviceworker_cached.html new file mode 100644 index 0000000000..9f94f82f93 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_console_serviceworker_cached.html @@ -0,0 +1,119 @@ +<!DOCTYPE HTML> +<html lang="en"> +<head> + <meta charset="utf8"> + <title>Test for getCachedMessages and Service Workers</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> +</head> +<body> +<p>Test for getCachedMessages and Service Workers</p> + +<script class="testbody" type="text/javascript"> +"use strict"; + +SimpleTest.waitForExplicitFinish(); + +const BASE_URL = "https://example.com/chrome/devtools/shared/webconsole/test/chrome/"; +const SERVICE_WORKER_URL = BASE_URL + "helper_serviceworker.js"; +const FRAME_URL = BASE_URL + "sandboxed_iframe.html"; + +const firstTabExpectedCalls = [ + { + message: { + level: "log", + filename: /helper_serviceworker/, + arguments: ['script evaluation'], + } + }, { + message: { + level: "log", + filename: /helper_serviceworker/, + arguments: ['install event'], + } + }, { + message: { + level: "log", + filename: /helper_serviceworker/, + arguments: ['activate event'], + } + }, +]; + +const secondTabExpectedCalls = [ + { + message: { + level: "log", + filename: /helper_serviceworker/, + arguments: ['fetch event: ' + FRAME_URL], + } + } +]; + +const startTest = async function () { + removeEventListener("load", startTest); + + await new Promise(resolve => { + SpecialPowers.pushPrefEnv({"set": [ + ["dom.serviceWorkers.enabled", true], + ["devtools.webconsole.filter.serviceworkers", true] + ]}, resolve); + }); + + info("Adding a tab and attaching a service worker"); + const tab1 = await addTab(FRAME_URL); + const swr = await withActiveServiceWorker(tab1.linkedBrowser.contentWindow, + SERVICE_WORKER_URL); + + info("Attaching console to tab 1"); + let {state} = await attachConsoleToTab(["ConsoleAPI"]); + let calls = await state.webConsoleFront.getCachedMessages(["ConsoleAPI"]); + checkConsoleAPICalls(calls.messages, firstTabExpectedCalls); + await closeDebugger(state); + + // Because this tab is being added after the original messages happened, + // they shouldn't show up in a call to getCachedMessages. + // However, there is a fetch event which is logged due to loading the tab. + info("Adding a new tab at the same URL"); + + await addTab(FRAME_URL); + info("Attaching console to tab 2"); + state = (await attachConsoleToTab(["ConsoleAPI"])).state; + calls = await state.webConsoleFront.getCachedMessages(["ConsoleAPI"]); + checkConsoleAPICalls(calls.messages, secondTabExpectedCalls); + await closeDebugger(state); + + await swr.unregister(); + + SimpleTest.finish(); +}; +addEventListener("load", startTest); + +// This test needs to add tabs that are controlled by a service worker +// so use some special powers to dig around and find gBrowser +const {gBrowser} = SpecialPowers._getTopChromeWindow(SpecialPowers.window); + +SimpleTest.registerCleanupFunction(() => { + while (gBrowser.tabs.length > 1) { + gBrowser.removeCurrentTab(); + } +}); + +function addTab(url) { + info("Adding a new tab with URL: '" + url + "'"); + return new Promise(resolve => { + const tab = gBrowser.selectedTab = gBrowser.addTab(url, { + triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(), + }); + gBrowser.selectedBrowser.addEventListener("load", function () { + info("URL '" + url + "' loading complete"); + resolve(tab); + }, {capture: true, once: true}); + }); +} + +</script> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_console_styling.html b/devtools/shared/webconsole/test/chrome/test_console_styling.html new file mode 100644 index 0000000000..841e19076f --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_console_styling.html @@ -0,0 +1,134 @@ +<!DOCTYPE HTML> +<html lang="en"> +<head> + <meta charset="utf8"> + <title>Test for console.log styling with %c</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> +</head> +<body> +<p>Test for console.log styling with %c</p> + +<script class="testbody" type="text/javascript"> +"use strict"; + +SimpleTest.waitForExplicitFinish(); + +let expectedConsoleCalls = []; + +function doConsoleCalls(aState) +{ + top.console.log("%cOne formatter with no styles"); + top.console.log("%cOne formatter", "color: red"); + top.console.log("%cTwo formatters%cEach with an arg", + "color: red", "background: red"); + top.console.log("%c%cTwo formatters next to each other", + "color: red", "background: red"); + top.console.log("%c%c%cThree formatters next to each other", + "color: red", "background: red", "font-size: 150%"); + top.console.log("%c%cTwo formatters%cWith a third separated", + "color: red", "background: red", "font-size: 150%"); + top.console.log("%cOne formatter", "color: red", + "Second arg with no styles"); + top.console.log("%cOne formatter", "color: red", + "%cSecond formatter is ignored", "background: blue") + + expectedConsoleCalls = [ + { + level: "log", + styles: undefined, + arguments: ["%cOne formatter with no styles"], + }, + { + level: "log", + styles: /^color: red$/, + arguments: ["One formatter"], + }, + { + level: "log", + styles: /^color: red,background: red$/, + arguments: ["Two formatters", "Each with an arg"], + }, + { + level: "log", + styles: /^background: red$/, + arguments: ["Two formatters next to each other"], + }, + { + level: "log", + styles: /^font-size: 150%$/, + arguments: ["Three formatters next to each other"], + }, + { + level: "log", + styles: /^background: red,font-size: 150%$/, + arguments: ["Two formatters", "With a third separated"], + }, + { + level: "log", + styles: /^color: red$/, + arguments: ["One formatter", "Second arg with no styles"], + }, + { + level: "log", + styles: /^color: red$/, + arguments: ["One formatter", + "%cSecond formatter is ignored", + "background: blue"], + }, + ]; +} + +async function startTest() +{ + removeEventListener("load", startTest); + + const {state, response} = await attachConsoleToTab(["ConsoleAPI"]); + onAttach(state, response); +} + +function onAttach(aState, aResponse) +{ + onConsoleAPICall = onConsoleAPICall.bind(null, aState); + aState.webConsoleFront.on("consoleAPICall", onConsoleAPICall); + doConsoleCalls(aState.actor); +} + +let consoleCalls = []; + +function onConsoleAPICall(aState, aPacket) +{ + info("received message level: " + aPacket.message.level); + + consoleCalls.push(aPacket.message); + if (consoleCalls.length != expectedConsoleCalls.length) { + return; + } + + aState.webConsoleFront.off("consoleAPICall", onConsoleAPICall); + + expectedConsoleCalls.forEach(function(aMessage, aIndex) { + info("checking received console call #" + aIndex); + const expected = expectedConsoleCalls[aIndex]; + const consoleCall = consoleCalls[aIndex]; + if (expected.styles == undefined) { + delete expected.styles; + is(consoleCall.styles, undefined, "No 'styles' property") + } + checkConsoleAPICall(consoleCall, expected); + }); + + + consoleCalls = []; + + closeDebugger(aState, function() { + SimpleTest.finish(); + }); +} + +addEventListener("load", startTest); +</script> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_console_timestamp.html b/devtools/shared/webconsole/test/chrome/test_console_timestamp.html new file mode 100644 index 0000000000..a64de0d7b2 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_console_timestamp.html @@ -0,0 +1,48 @@ +<!DOCTYPE HTML> +<html> +<head> + <meta charset="utf-8"> + <title>Test for console.group styling with %c</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> + <script> +"use strict"; + +window.onload = async function () { + SimpleTest.waitForExplicitFinish(); + let state; + try { + state = (await attachConsole(["ConsoleAPI"])).state; + const consoleFront = state.webConsoleFront; + + info("Testing console.log packet timestamp correctness"); + const clientLogTimestamp = Date.now(); + const packet = await consoleAPICall(consoleFront, + () => top.console.log("test")); + const packetReceivedTimestamp = Date.now(); + + const {timeStamp} = packet.message; + ok(clientLogTimestamp <= timeStamp && timeStamp <= packetReceivedTimestamp, + "console.log message timestamp is between the expected time range " + + `(${clientLogTimestamp} <= ${timeStamp} <= ${packetReceivedTimestamp})` + ); + } catch (e) { + ok(false, `Error thrown: ${e.message}`); + } + + await closeDebugger(state); + SimpleTest.finish(); +}; + + </script> +</head> +<body> + <p id="display"></p> + <div id="content" style="display: none"> + </div> + <pre id="test"> + </pre> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_console_worker.html b/devtools/shared/webconsole/test/chrome/test_console_worker.html new file mode 100644 index 0000000000..330c083f6b --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_console_worker.html @@ -0,0 +1,73 @@ +<!DOCTYPE HTML> +<html lang="en"> +<head> + <meta charset="utf8"> + <title>Test for the Console API and Workers</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> +</head> +<body> +<p>Test for the Console API and Workers</p> + +<script class="testbody" type="text/javascript"> +"use strict"; + +SimpleTest.waitForExplicitFinish(); + +const expectedCachedConsoleCalls = [{ + message:{ + level: "log", + filename: /console-test-worker/, + arguments: ['Log from worker init'], + } +}]; + +const expectedConsoleAPICalls = [{ + message: { + level: "log", + arguments: ['Log was requested from worker'], + } +}]; + +window.onload = async function () { + const {state} = await attachConsoleToWorker(["ConsoleAPI"]); + + await testCachedMessages(state); + await testConsoleAPI(state); + + closeDebugger(state, function() { + SimpleTest.finish(); + }); +}; + +const testCachedMessages = async function (state) { + info("testCachedMessages entered"); + return new Promise(resolve => { + const onCachedConsoleAPI = (response) => { + const consoleCalls = response.messages; + + info('Received cached response. Checking console calls.'); + checkConsoleAPICalls(consoleCalls, expectedCachedConsoleCalls); + resolve(); + }; + state.webConsoleFront.getCachedMessages(["ConsoleAPI"]).then(onCachedConsoleAPI); + }) +}; + +const testConsoleAPI = async function (state) { + info("testConsoleAPI: adding listener for consoleAPICall"); + const onConsoleApiMessage = state.webConsoleFront.once("consoleAPICall"); + state._worker_ref.postMessage({ + type: "log", + message: "Log was requested from worker" + }); + const packet = await onConsoleApiMessage; + info("received message level: " + packet.message.level); + checkConsoleAPICalls([packet], expectedConsoleAPICalls); +}; + +</script> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_consoleapi.html b/devtools/shared/webconsole/test/chrome/test_consoleapi.html new file mode 100644 index 0000000000..b5d8edf23e --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_consoleapi.html @@ -0,0 +1,225 @@ +<!DOCTYPE HTML> +<html lang="en"> +<head> + <meta charset="utf8"> + <title>Test for the Console API</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> +</head> +<body> +<p>Test for the Console API</p> + +<script class="testbody" type="text/javascript"> +"use strict"; + +SimpleTest.waitForExplicitFinish(); + +let expectedConsoleCalls = []; + +function doConsoleCalls(aState) +{ + const longString = (new Array(DevToolsServer.LONG_STRING_LENGTH + 2)).join("a"); + + top.console.log("foobarBaz-log", undefined); + + top.console.log("Float from not a number: %f", "foo"); + top.console.log("Float from string: %f", "1.2"); + top.console.log("Float from number: %f", 1.3); + + top.console.info("foobarBaz-info", null); + top.console.warn("foobarBaz-warn", top.document.documentElement); + top.console.debug(null); + top.console.trace(); + top.console.dir(top.document, top.location); + top.console.log("foo", longString); + + const sandbox = new Cu.Sandbox(null, { invisibleToDebugger: true }); + const sandboxObj = sandbox.eval("new Object"); + top.console.log(sandboxObj); + + function fromAsmJS() { + top.console.error("foobarBaz-asmjs-error", undefined); + } + + (function(global, foreign) { + "use asm"; + function inAsmJS2() { foreign.fromAsmJS() } + function inAsmJS1() { inAsmJS2() } + return inAsmJS1 + })(null, { fromAsmJS })(); + + expectedConsoleCalls = [ + { + level: "log", + filename: /test_consoleapi/, + timeStamp: FRACTIONAL_NUMBER_REGEX, + arguments: ["foobarBaz-log", { type: "undefined" }], + }, + { + level: "log", + arguments: ["Float from not a number: NaN"], + }, + { + level: "log", + arguments: ["Float from string: 1.200000"], + }, + { + level: "log", + arguments: ["Float from number: 1.300000"], + }, + { + level: "info", + filename: /test_consoleapi/, + timeStamp: FRACTIONAL_NUMBER_REGEX, + arguments: ["foobarBaz-info", { type: "null" }], + }, + { + level: "warn", + filename: /test_consoleapi/, + timeStamp: FRACTIONAL_NUMBER_REGEX, + arguments: ["foobarBaz-warn", { type: "object", actor: /[a-z]/ }], + }, + { + level: "debug", + filename: /test_consoleapi/, + timeStamp: FRACTIONAL_NUMBER_REGEX, + arguments: [{ type: "null" }], + }, + { + level: "trace", + filename: /test_consoleapi/, + timeStamp: FRACTIONAL_NUMBER_REGEX, + stacktrace: [ + { + filename: /test_consoleapi/, + functionName: "doConsoleCalls", + }, + { + filename: /test_consoleapi/, + functionName: "onAttach", + }, + ], + }, + { + level: "dir", + filename: /test_consoleapi/, + timeStamp: FRACTIONAL_NUMBER_REGEX, + arguments: [ + { + type: "object", + actor: /[a-z]/, + class: "HTMLDocument", + }, + { + type: "object", + actor: /[a-z]/, + class: "Location", + } + ], + }, + { + level: "log", + filename: /test_consoleapi/, + timeStamp: FRACTIONAL_NUMBER_REGEX, + arguments: [ + "foo", + { + type: "longString", + initial: longString.substring(0, + DevToolsServer.LONG_STRING_INITIAL_LENGTH), + length: longString.length, + actor: /[a-z]/, + }, + ], + }, + { + level: "log", + filename: /test_consoleapi/, + timeStamp: FRACTIONAL_NUMBER_REGEX, + arguments: [ + { + type: "object", + actor: /[a-z]/, + class: "InvisibleToDebugger: Object", + }, + ], + }, + { + level: "error", + filename: /test_consoleapi/, + timeStamp: FRACTIONAL_NUMBER_REGEX, + arguments: ["foobarBaz-asmjs-error", { type: "undefined" }], + + stacktrace: [ + { + filename: /test_consoleapi/, + functionName: "fromAsmJS", + }, + { + filename: /test_consoleapi/, + functionName: "inAsmJS2", + }, + { + filename: /test_consoleapi/, + functionName: "inAsmJS1", + }, + { + filename: /test_consoleapi/, + functionName: "doConsoleCalls", + }, + { + filename: /test_consoleapi/, + functionName: "onAttach", + }, + ], + }, + ]; +} + +async function startTest() +{ + removeEventListener("load", startTest); + + const {state, response} = await attachConsoleToTab(["ConsoleAPI"]); + onAttach(state, response); +} + +function onAttach(aState, aResponse) +{ + onConsoleAPICall = onConsoleAPICall.bind(null, aState); + aState.webConsoleFront.on("consoleAPICall", onConsoleAPICall); + doConsoleCalls(aState.actor); +} + +let consoleCalls = []; + +function onConsoleAPICall(aState, aPacket) +{ + info("received message level: " + aPacket.message.level); + + consoleCalls.push(aPacket.message); + if (consoleCalls.length != expectedConsoleCalls.length) { + return; + } + + aState.webConsoleFront.off("consoleAPICall", onConsoleAPICall); + + expectedConsoleCalls.forEach(function(aMessage, aIndex) { + info("checking received console call #" + aIndex); + checkConsoleAPICall(consoleCalls[aIndex], expectedConsoleCalls[aIndex]); + }); + + + consoleCalls = []; + + closeDebugger(aState, function() { + SimpleTest.finish(); + }); +} + +addEventListener("load", startTest); +</script> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_consoleapi_innerID.html b/devtools/shared/webconsole/test/chrome/test_consoleapi_innerID.html new file mode 100644 index 0000000000..98fc783a84 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_consoleapi_innerID.html @@ -0,0 +1,157 @@ +<!DOCTYPE HTML> +<html lang="en"> +<head> + <meta charset="utf8"> + <title>Test for the innerID property of the Console API</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> +</head> +<body> +<p>Test for the Console API</p> + +<script class="testbody" type="text/javascript"> +"use strict"; + +SimpleTest.waitForExplicitFinish(); + +let expectedConsoleCalls = []; + +function doConsoleCalls(aState) +{ + const { ConsoleAPI } = ChromeUtils.import("resource://gre/modules/Console.jsm"); + const console = new ConsoleAPI({ + innerID: window.top.windowGlobalChild.innerWindowId + }); + + const longString = (new Array(DevToolsServer.LONG_STRING_LENGTH + 2)).join("a"); + + console.log("foobarBaz-log", undefined); + console.info("foobarBaz-info", null); + console.warn("foobarBaz-warn", top.document.documentElement); + console.debug(null); + console.trace(); + console.dir(top.document, top.location); + console.log("foo", longString); + + expectedConsoleCalls = [ + { + level: "log", + filename: /test_consoleapi/, + timeStamp: /^\d+$/, + arguments: ["foobarBaz-log", { type: "undefined" }], + }, + { + level: "info", + filename: /test_consoleapi/, + timeStamp: /^\d+$/, + arguments: ["foobarBaz-info", { type: "null" }], + }, + { + level: "warn", + filename: /test_consoleapi/, + timeStamp: /^\d+$/, + arguments: ["foobarBaz-warn", { type: "object", actor: /[a-z]/ }], + }, + { + level: "debug", + filename: /test_consoleapi/, + timeStamp: /^\d+$/, + arguments: [{ type: "null" }], + }, + { + level: "trace", + filename: /test_consoleapi/, + timeStamp: /^\d+$/, + stacktrace: [ + { + filename: /test_consoleapi/, + functionName: "doConsoleCalls", + }, + { + filename: /test_consoleapi/, + functionName: "onAttach", + }, + ], + }, + { + level: "dir", + filename: /test_consoleapi/, + timeStamp: /^\d+$/, + arguments: [ + { + type: "object", + actor: /[a-z]/, + class: "HTMLDocument", + }, + { + type: "object", + actor: /[a-z]/, + class: "Location", + } + ], + }, + { + level: "log", + filename: /test_consoleapi/, + timeStamp: /^\d+$/, + arguments: [ + "foo", + { + type: "longString", + initial: longString.substring(0, + DevToolsServer.LONG_STRING_INITIAL_LENGTH), + length: longString.length, + actor: /[a-z]/, + }, + ], + }, + ]; +} + +async function startTest() +{ + removeEventListener("load", startTest); + + const {state} = await attachConsoleToTab(["ConsoleAPI"]); + onAttach(state); +} + +function onAttach(aState) +{ + onConsoleAPICall = onConsoleAPICall.bind(null, aState); + aState.webConsoleFront.on("consoleAPICall", onConsoleAPICall); + doConsoleCalls(aState.actor); +} + +let consoleCalls = []; + +function onConsoleAPICall(aState, aPacket) +{ + info("received message level: " + aPacket.message.level); + + consoleCalls.push(aPacket.message); + if (consoleCalls.length != expectedConsoleCalls.length) { + return; + } + + aState.webConsoleFront.off("consoleAPICall", onConsoleAPICall); + + expectedConsoleCalls.forEach(function(aMessage, aIndex) { + info("checking received console call #" + aIndex); + checkConsoleAPICall(consoleCalls[aIndex], expectedConsoleCalls[aIndex]); + }); + + + consoleCalls = []; + + closeDebugger(aState, function() { + SimpleTest.finish(); + }); +} + +addEventListener("load", startTest); +</script> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_file_uri.html b/devtools/shared/webconsole/test/chrome/test_file_uri.html new file mode 100644 index 0000000000..76c3b8193e --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_file_uri.html @@ -0,0 +1,110 @@ +<!DOCTYPE HTML> +<html lang="en"> +<head> + <meta charset="utf8"> + <title>Test for file activity tracking</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> +</head> +<body> +<p>Test for file activity tracking</p> + +<script class="testbody" type="text/javascript"> +"use strict"; + +SimpleTest.waitForExplicitFinish(); + +const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); +const {FileUtils} = ChromeUtils.import("resource://gre/modules/FileUtils.jsm"); + +let gState; +let gTmpFile; + +function doFileActivity() +{ + info("doFileActivity"); + const fileContent = "<p>hello world from bug 798764"; + + gTmpFile = FileUtils.getFile("TmpD", ["bug798764.html"]); + gTmpFile.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE); + + const fout = FileUtils.openSafeFileOutputStream(gTmpFile, + FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE); + + const stream = Cc[ + "@mozilla.org/io/arraybuffer-input-stream;1" + ].createInstance(Ci.nsIArrayBufferInputStream); + const buffer = new TextEncoder().encode(fileContent).buffer; + stream.setData(buffer, 0, buffer.byteLength); + NetUtil.asyncCopy(stream, fout, addIframe); +} + +function addIframe(aStatus) +{ + ok(Components.isSuccessCode(aStatus), + "the temporary file was saved successfully"); + + const iframe = document.createElement("iframe"); + iframe.src = NetUtil.newURI(gTmpFile).spec; + document.body.appendChild(iframe); +} + +async function startTest() +{ + removeEventListener("load", startTest); + + const {state} = await attachConsole(["FileActivity"]); + onAttach(state); +} + +function onAttach(aState) +{ + gState = aState; + gState.webConsoleFront.on("fileActivity", onFileActivity); + doFileActivity(); +} + +function onFileActivity(aPacket) +{ + gState.webConsoleFront.off("fileActivity", onFileActivity); + + info("aPacket.uri: " + aPacket.uri); + ok(/\bbug798764\b.*\.html$/.test(aPacket.uri), "file URI match"); + + testEnd(); +} + +function testEnd() +{ + if (gTmpFile) { + SimpleTest.executeSoon(function() { + try { + gTmpFile.remove(false); + } + catch (ex) { + if (ex.name != "NS_ERROR_FILE_IS_LOCKED") { + throw ex; + } + // Sometimes remove() throws because the file is not unlocked soon + // enough. + } + gTmpFile = null; + }); + } + + if (gState) { + closeDebugger(gState, function() { + gState = null; + SimpleTest.finish(); + }); + } else { + SimpleTest.finish(); + } +} + +addEventListener("load", startTest); +</script> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_jsterm_autocomplete.html b/devtools/shared/webconsole/test/chrome/test_jsterm_autocomplete.html new file mode 100644 index 0000000000..bbc9aeb6fc --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_jsterm_autocomplete.html @@ -0,0 +1,635 @@ +<!DOCTYPE HTML> +<html lang="en"> +<head> + <meta charset="utf8"> + <title>Test for JavaScript terminal functionality</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> +</head> +<body> +<p>Test for JavaScript terminal autocomplete functionality</p> + +<script class="testbody" type="text/javascript"> + "use strict"; + + SimpleTest.waitForExplicitFinish(); + const { + MAX_AUTOCOMPLETE_ATTEMPTS, + MAX_AUTOCOMPLETIONS + } = require("devtools/shared/webconsole/js-property-provider"); + const RESERVED_JS_KEYWORDS = require("devtools/shared/webconsole/reserved-js-words"); + + + addEventListener("load", startTest); + + async function startTest() { + // First run the tests with a tab as a target. + let {state} = await attachConsoleToTab(["PageError"]); + await performTests({state, isWorker: false}); + + // Then run the tests with a worker as a target. + state = (await attachConsoleToWorker(["PageError"])).state; + await performTests({state, isWorker: true}); + + SimpleTest.finish(); + } + + async function performTests({state, isWorker}) { + // Set up the global variables needed to test autocompletion in the target. + const script = ` + // This is for workers so autocomplete acts the same + if (!this.window) { + window = this; + } + + window.foobarObject = Object.create(null); + window.foobarObject.foo = 1; + window.foobarObject.foobar = 2; + window.foobarObject.foobaz = 3; + window.foobarObject.omg = 4; + window.foobarObject.omgfoo = 5; + window.foobarObject.strfoo = "foobarz"; + window.foobarObject.omgstr = "foobarz" + + (new Array(${DevToolsServer.LONG_STRING_LENGTH})).join("abb"); + window.largeObject1 = Object.create(null); + for (let i = 0; i < ${MAX_AUTOCOMPLETE_ATTEMPTS + 1}; i++) { + window.largeObject1['a' + i] = i; + } + + window.largeObject2 = Object.create(null); + for (let i = 0; i < ${MAX_AUTOCOMPLETIONS * 2}; i++) { + window.largeObject2['a' + i] = i; + } + + window.proxy1 = new Proxy({foo: 1}, { + getPrototypeOf() { throw new Error() } + }); + window.proxy2 = new Proxy(Object.create(Object.create(null, {foo:{}})), { + ownKeys() { throw new Error() } + }); + window.emojiObject = Object.create(null); + window.emojiObject["😎"] = "😎"; + + window.insensitiveTestCase = Object.create(null, Object.getOwnPropertyDescriptors({ + PROP: "", + Prop: "", + prop: "", + PRÖP: "", + pröp: "", + })); + + window.elementAccessTestCase = Object.create(null, Object.getOwnPropertyDescriptors({ + bar: "", + BAR: "", + dataTest: "", + "data-test": "", + 'da"ta"test': "", + 'da\`ta\`test': "", + "da'ta'test": "", + })); + + window.varify = true; + + var Cu_Sandbox = Cu ? Cu.Sandbox : null; + `; + await evaluateExpression(state.webConsoleFront, script); + + const tests = [ + doAutocomplete1, + doAutocomplete2, + doAutocomplete3, + doAutocomplete4, + doAutocompleteLarge1, + doAutocompleteLarge2, + doAutocompleteProxyThrowsPrototype, + doAutocompleteProxyThrowsOwnKeys, + doAutocompleteDotSurroundedBySpaces, + doAutocompleteAfterOr, + doInsensitiveAutocomplete, + doElementAccessAutocomplete, + doAutocompleteAfterOperator, + dontAutocompleteAfterDeclaration, + doKeywordsAutocomplete, + dontAutocomplete, + ]; + + if (!isWorker) { + // `Cu` is not defined in workers, then we can't test `Cu.Sandbox` + tests.push(doAutocompleteSandbox); + // Some cases are handled in worker context because we can't use parser.js. + // See Bug 1507181. + tests.push( + doAutocompleteArray, + doAutocompleteString, + doAutocompleteCommands, + doAutocompleteBracketSurroundedBySpaces, + ); + } + + for (const test of tests) { + await test(state.webConsoleFront); + } + + // Null out proxy1 and proxy2: the proxy handlers use scripted functions + // that can keep the debugger sandbox alive longer than necessary via their + // environment chain (due to the webconsole helper functions defined there). + await evaluateExpression(state.webConsoleFront, `this.proxy1 = null; this.proxy2 = null;`); + + await closeDebugger(state); + } + + async function doAutocomplete1(webConsoleFront) { + info("test autocomplete for 'window.foo'"); + const response = await webConsoleFront.autocomplete("window.foo"); + const matches = response.matches; + + is(response.matchProp, "foo", "matchProp"); + is(matches.length, 1, "matches.length"); + is(matches[0], "foobarObject", "matches[0]"); + } + + async function doAutocomplete2(webConsoleFront) { + info("test autocomplete for 'window.foobarObject.'"); + const response = await webConsoleFront.autocomplete("window.foobarObject."); + const matches = response.matches; + + ok(!response.matchProp, "matchProp"); + is(matches.length, 7, "matches.length"); + checkObject(matches, + ["foo", "foobar", "foobaz", "omg", "omgfoo", "omgstr", "strfoo"]); + } + + async function doAutocomplete3(webConsoleFront) { + // Check that completion suggestions are offered inside the string. + info("test autocomplete for 'dump(window.foobarObject.)'"); + const response = await webConsoleFront.autocomplete("dump(window.foobarObject.)", 25); + const matches = response.matches; + + ok(!response.matchProp, "matchProp"); + is(matches.length, 7, "matches.length"); + checkObject(matches, + ["foo", "foobar", "foobaz", "omg", "omgfoo", "omgstr", "strfoo"]); + } + + async function doAutocomplete4(webConsoleFront) { + // Check that completion requests can have no suggestions. + info("test autocomplete for 'dump(window.foobarObject.)'"); + const response = await webConsoleFront.autocomplete("dump(window.foobarObject.)"); + ok(!response.matchProp, "matchProp"); + is(response.matches, null, "matches is null"); + } + + async function doAutocompleteLarge1(webConsoleFront) { + // Check that completion requests with too large objects will + // have no suggestions. + info("test autocomplete for 'window.largeObject1.'"); + const response = await webConsoleFront.autocomplete("window.largeObject1."); + ok(!response.matchProp, "matchProp"); + info (response.matches.join("|")); + is(response.matches.length, 0, "Bailed out with too many properties"); + } + + async function doAutocompleteLarge2(webConsoleFront) { + // Check that completion requests with pretty large objects will + // have MAX_AUTOCOMPLETIONS suggestions + info("test autocomplete for 'window.largeObject2.'"); + const response = await webConsoleFront.autocomplete("window.largeObject2."); + ok(!response.matchProp, "matchProp"); + is(response.matches.length, MAX_AUTOCOMPLETIONS, "matches.length is MAX_AUTOCOMPLETIONS"); + } + + async function doAutocompleteProxyThrowsPrototype(webConsoleFront) { + // Check that completion provides own properties even if [[GetPrototypeOf]] throws. + info("test autocomplete for 'window.proxy1.'"); + const response = await webConsoleFront.autocomplete("window.proxy1."); + ok(!response.matchProp, "matchProp"); + is(response.matches.length, 14, "matches.length"); + ok(response.matches.includes("foo"), "matches has own property for proxy with throwing getPrototypeOf trap"); + } + + async function doAutocompleteProxyThrowsOwnKeys(webConsoleFront) { + // Check that completion provides inherited properties even if [[OwnPropertyKeys]] throws. + info("test autocomplete for 'window.proxy2.'"); + const response = await webConsoleFront.autocomplete("window.proxy2."); + ok(!response.matchProp, "matchProp"); + is(response.matches.length, 1, "matches.length"); + checkObject(response.matches, ["foo"]); + } + + async function doAutocompleteSandbox(webConsoleFront) { + // Check that completion provides inherited properties even if [[OwnPropertyKeys]] throws. + info("test autocomplete for 'Cu_Sandbox.'"); + const response = await webConsoleFront.autocomplete("Cu_Sandbox."); + ok(!response.matchProp, "matchProp"); + const keys = Object.getOwnPropertyNames(Object.prototype).sort(); + is(response.matches.length, keys.length, "matches.length"); + // checkObject(response.matches, keys); + is(response.matches.join(" - "), keys.join(" - ")); + } + + async function doAutocompleteArray(webConsoleFront) { + info("test autocomplete for [1,2,3]"); + const response = await webConsoleFront.autocomplete("[1,2,3]."); + let {matches} = response; + + ok(!!matches.length, "There are completion results for the array"); + ok(matches.includes("length") && matches.includes("filter"), + "Array autocomplete contains expected results"); + + info("test autocomplete for '[] . '"); + matches = (await webConsoleFront.autocomplete("[] . ")).matches; + ok(matches.length > 1); + ok(matches.includes("length") && matches.includes("filter"), + "Array autocomplete contains expected results"); + ok(!matches.includes("copy"), "Array autocomplete does not contain helpers"); + + info("test autocomplete for '[1,2,3]['"); + matches = (await webConsoleFront.autocomplete("[1,2,3][")).matches; + ok(matches.length > 1); + ok(matches.includes('"length"') && matches.includes('"filter"'), + "Array autocomplete contains expected results, surrounded by quotes"); + + info("test autocomplete for '[1,2,3]['"); + matches = (await webConsoleFront.autocomplete("[1,2,3]['")).matches; + ok(matches.length > 1); + ok(matches.includes("'length'") && matches.includes("'filter'"), + "Array autocomplete contains expected results, surrounded by quotes"); + + info("test autocomplete for '[1,2,3][l"); + matches = (await webConsoleFront.autocomplete("[1,2,3][l")).matches; + ok(matches.length >= 1); + ok(matches.includes('"length"'), + "Array autocomplete contains expected results, surrounded by quotes"); + + info("test autocomplete for '[1,2,3]['l"); + matches = (await webConsoleFront.autocomplete("[1,2,3]['l")).matches; + ok(matches.length >= 1); + ok(matches.includes("'length'"), + "Array autocomplete contains expected results, surrounded by quotes"); + } + + async function doAutocompleteString(webConsoleFront) { + info(`test autocomplete for "foo".`); + const response = await webConsoleFront.autocomplete(`"foo".`); + let {matches} = response; + + ok(!!matches.length, "There are completion results for the string"); + ok(matches.includes("substr") && matches.includes("trim"), + "String autocomplete contains expected results"); + + info("test autocomplete for `foo`["); + matches = (await webConsoleFront.autocomplete("`foo`[")).matches; + ok(matches.length > 1, "autocomplete string with bracket works"); + ok(matches.includes('"substr"') && matches.includes('"trim"'), + "String autocomplete contains expected results, surrounded by quotes"); + } + + async function doAutocompleteDotSurroundedBySpaces(webConsoleFront) { + info("test autocomplete for 'window.foobarObject\n .'"); + let {matches} = await webConsoleFront.autocomplete("window.foobarObject\n ."); + is(matches.length, 7); + checkObject(matches, + ["foo", "foobar", "foobaz", "omg", "omgfoo", "omgstr", "strfoo"]); + + info("test autocomplete for 'window.foobarObject\n .o'"); + matches = (await webConsoleFront.autocomplete("window.foobarObject\n .o")).matches; + is(matches.length, 3); + checkObject(matches, ["omg", "omgfoo", "omgstr"]); + + info("test autocomplete for 'window.foobarObject\n .\n s'"); + matches = (await webConsoleFront.autocomplete("window.foobarObject\n .\n s")).matches; + is(matches.length, 1); + checkObject(matches, ["strfoo"]); + + info("test autocomplete for 'window.foobarObject\n . '"); + matches = (await webConsoleFront.autocomplete("window.foobarObject\n . ")).matches; + is(matches.length, 7); + checkObject(matches, + ["foo", "foobar", "foobaz", "omg", "omgfoo", "omgstr", "strfoo"]); + + matches = + (await webConsoleFront.autocomplete("window.foobarObject. foo ; window.foo")).matches; + is(matches.length, 1); + checkObject(matches, ["foobarObject"]); + } + + async function doAutocompleteBracketSurroundedBySpaces(webConsoleFront) { + const wrap = (arr, quote = `"`) => arr.map(x => `${quote}${x}${quote}`); + let matches = await getAutocompleteMatches(webConsoleFront, "window.foobarObject\n [") + is(matches.length, 7); + checkObject(matches, + wrap(["foo", "foobar", "foobaz", "omg", "omgfoo", "omgstr", "strfoo"])); + + matches = await getAutocompleteMatches(webConsoleFront, "window.foobarObject\n ['o") + is(matches.length, 3); + checkObject(matches, wrap(["omg", "omgfoo", "omgstr"], "'")); + + matches = await getAutocompleteMatches(webConsoleFront, "window.foobarObject\n [\n s"); + is(matches.length, 1); + checkObject(matches, [`"strfoo"`]); + + matches = await getAutocompleteMatches(webConsoleFront, "window.foobarObject\n [ "); + is(matches.length, 7); + checkObject(matches, + wrap(["foo", "foobar", "foobaz", "omg", "omgfoo", "omgstr", "strfoo"])); + + matches = await getAutocompleteMatches(webConsoleFront, "window.emojiObject [ '"); + is(matches.length, 1); + checkObject(matches, [`'😎'`]); + } + + async function doAutocompleteAfterOr(webConsoleFront) { + info("test autocomplete for 'true || foo'"); + const {matches} = await webConsoleFront.autocomplete("true || foobar"); + is(matches.length, 1, "autocomplete returns expected results"); + is(matches.join("-"), "foobarObject"); + } + + async function doInsensitiveAutocomplete(webConsoleFront) { + info("test autocomplete for 'window.insensitiveTestCase.'"); + let {matches} = await webConsoleFront.autocomplete("window.insensitiveTestCase."); + is(matches.join("-"), "prop-pröp-Prop-PROP-PRÖP", + "autocomplete returns the expected items, in the expected order"); + + info("test autocomplete for 'window.insensitiveTestCase.p'"); + matches = (await webConsoleFront.autocomplete("window.insensitiveTestCase.p")).matches; + is(matches.join("-"), "prop-pröp-Prop-PROP-PRÖP", + "autocomplete is case-insensitive when first letter is lowercased"); + + info("test autocomplete for 'window.insensitiveTestCase.pRoP'"); + matches = (await webConsoleFront.autocomplete("window.insensitiveTestCase.pRoP")).matches; + is(matches.join("-"), "prop-Prop-PROP", + "autocomplete is case-insensitive when first letter is lowercased"); + + info("test autocomplete for 'window.insensitiveTestCase.P'"); + matches = (await webConsoleFront.autocomplete("window.insensitiveTestCase.P")).matches; + is(matches.join("-"), "Prop-PROP-PRÖP", + "autocomplete is case-sensitive when first letter is uppercased"); + + info("test autocomplete for 'window.insensitiveTestCase.PROP'"); + matches = (await webConsoleFront.autocomplete("window.insensitiveTestCase.PROP")).matches; + is(matches.join("-"), "PROP", + "autocomplete is case-sensitive when first letter is uppercased"); + + info("test autocomplete for 'window.insensitiveTestCase.prö'"); + matches = (await webConsoleFront.autocomplete("window.insensitiveTestCase.prö")).matches; + is(matches.join("-"), "pröp-PRÖP", "expected result with lowercase diacritic"); + + info("test autocomplete for 'window.insensitiveTestCase.PRÖ'"); + matches = (await webConsoleFront.autocomplete("window.insensitiveTestCase.PRÖ")).matches; + is(matches.join("-"), "PRÖP", "expected result with uppercase diacritic"); + } + + async function doElementAccessAutocomplete(webConsoleFront) { + info("test autocomplete for 'window.elementAccessTestCase['"); + let res = (await webConsoleFront.autocomplete("window.elementAccessTestCase[")); + is( + res.matches.join("|"), + `"bar"|"da'ta'test"|"da\\"ta\\"test"|"da\`ta\`test"|"data-test"|"dataTest"|"BAR"`, + "autocomplete returns the expected items, wrapped in quotes"); + is(res.isElementAccess, true); + + info("test autocomplete for 'window.elementAccessTestCase[d'"); + res = await webConsoleFront.autocomplete("window.elementAccessTestCase[d"); + is( + res.matches.join("|"), + `"da'ta'test"|"da\\"ta\\"test"|"da\`ta\`test"|"data-test"|"dataTest"`, + "autocomplete returns the expected filtered items"); + is(res.isElementAccess, true); + + info(`test autocomplete for 'window.elementAccessTestCase["d'`); + res = await webConsoleFront.autocomplete(`window.elementAccessTestCase["d`); + is( + res.matches.join("|"), + `"da'ta'test"|"da\\"ta\\"test"|"da\`ta\`test"|"data-test"|"dataTest"`, + "autocomplete returns the expected items, wrapped in quotes"); + is(res.isElementAccess, true); + + info(`test autocomplete for 'window.elementAccessTestCase["data-`); + res = await webConsoleFront.autocomplete(`window.elementAccessTestCase["data-`); + is(res.matches.join("|"), `"data-test"`, + "autocomplete returns the expected items, wrapped in quotes"); + is(res.isElementAccess, true); + + info(`test autocomplete for 'window.elementAccessTestCase['d'`); + res = await webConsoleFront.autocomplete(`window.elementAccessTestCase['d`); + is( + res.matches.join("|"), + `'da"ta"test'|'da\\'ta\\'test'|'da\`ta\`test'|'data-test'|'dataTest'`, + "autocomplete returns the expected items, wrapped in the same quotes the user entered"); + is(res.isElementAccess, true); + + info("test autocomplete for 'window.elementAccessTestCase[`d'"); + res = await webConsoleFront.autocomplete("window.elementAccessTestCase[`d"); + is( + res.matches.join("|"), + "`da'ta'test`|`da\"ta\"test`|`da\\`ta\\`test`|`data-test`|`dataTest`", + "autocomplete returns the expected items, wrapped in the same quotes the user entered"); + is(res.isElementAccess, true); + + info(`test autocomplete for '['`); + res = await webConsoleFront.autocomplete(`[`); + is(res.matches, null, "it does not return anything"); + + info(`test autocomplete for '[1,2,3'`); + res = await webConsoleFront.autocomplete(`[1,2,3`); + is(res.matches, null, "it does not return anything"); + + info(`test autocomplete for '["'`); + res = await webConsoleFront.autocomplete(`["`); + is(res.matches, null, "it does not return anything"); + + info(`test autocomplete for '[;'`); + res = await webConsoleFront.autocomplete(`[;`); + is(res.matches, null, "it does not return anything"); + } + + async function doAutocompleteCommands(webConsoleFront) { + info("test autocomplete for 'c'"); + let matches = (await webConsoleFront.autocomplete("c")).matches; + ok(matches.includes("clear"), "commands are returned"); + + info("test autocomplete for 's'"); + matches = (await webConsoleFront.autocomplete("s")).matches; + is(matches.includes("screenshot"), false, "screenshot is not returned"); + + info("test autocomplete for ':s'"); + matches = (await webConsoleFront.autocomplete(":s")).matches; + is(matches.includes(":screenshot"), true, "screenshot is returned"); + + info("test autocomplete for 'window.c'"); + matches = (await webConsoleFront.autocomplete("window.c")).matches; + ok(!matches.includes("clear"), "commands are not returned"); + + info("test autocomplete for 'window[c'"); + matches = (await webConsoleFront.autocomplete("window[c")).matches; + ok(!matches.includes("clear"), "commands are not returned"); + + info(`test autocomplete for 'window["c'`); + matches = (await webConsoleFront.autocomplete(`window["c`)).matches; + ok(!matches.includes("clear"), "commands are not returned"); + + info(`test autocomplete for 'window["c'`); + matches = (await webConsoleFront.autocomplete(`window["c`)).matches; + ok(!matches.includes("clear"), "commands are not returned"); + + info(`test autocomplete for 'window[";c'`); + matches = (await webConsoleFront.autocomplete(`window[";c`)).matches; + ok(!matches.includes("clear"), "commands are not returned"); + + info(`test autocomplete for 'window[;c'`); + matches = (await webConsoleFront.autocomplete(`window[;c`)).matches; + ok(!matches.includes("clear"), "commands are not returned"); + } + + async function doAutocompleteAfterOperator(webConsoleFront) { + const inputs = [ + "true;foob", + "true,foob", + "({key:foob", + "a=foob", + "if(a<foob", + "if(a>foob", + "1+foob", + "1-foob", + "++foob", + "--foob", + "1*foob", + "2**foob", + "1/foob", + "1%foob", + "1|foob", + "1&foob", + "1^foob", + "~foob", + "1<<foob", + "1>>foob", + "1>>>foob", + "false||foob", + "false&&foob", + "x=true?foob", + "x=false?1:foob", + "!foob", + "false??foob", + ]; + + for (const input of inputs) { + info(`test autocomplete for "${input}"`); + const matches = (await webConsoleFront.autocomplete(input)).matches; + ok(matches.includes("foobarObject"), `Expected autocomplete result for ${input}"`); + } + } + + async function dontAutocompleteAfterDeclaration(webConsoleFront) { + info("test autocomplete for 'var win'"); + let matches = (await webConsoleFront.autocomplete("var win")).matches; + is(matches, null, "no autocompletion on a var declaration"); + + info("test autocomplete for 'const win'"); + matches = (await webConsoleFront.autocomplete("const win")).matches; + is(matches, null, "no autocompletion on a const declaration"); + + info("test autocomplete for 'let win'"); + matches = (await webConsoleFront.autocomplete("let win")).matches; + is(matches, null, "no autocompletion on a let declaration"); + + info("test autocomplete for 'function win'"); + matches = (await webConsoleFront.autocomplete("function win")).matches; + is(matches, null, "no autocompletion on a function declaration"); + + info("test autocomplete for 'class win'"); + matches = (await webConsoleFront.autocomplete("class win")).matches; + is(matches, null, "no autocompletion on a class declaration"); + + info("test autocomplete for 'const win = win'"); + matches = (await webConsoleFront.autocomplete("const win = win")).matches; + ok(matches.includes("window"), "autocompletion still happens after the `=` sign"); + + info("test autocomplete for 'in var'"); + matches = (await webConsoleFront.autocomplete("in var")).matches; + ok(matches.includes("varify"), + "autocompletion still happens with a property name starting with 'var'"); +} + +async function doKeywordsAutocomplete(webConsoleFront) { + info("test autocomplete for 'func'"); + let matches = (await webConsoleFront.autocomplete("func")).matches; + ok(matches.includes("function"), "keywords are returned"); + + info("test autocomplete for ':func'"); + matches = (await webConsoleFront.autocomplete(":func")).matches; + is(!matches.includes("function"), true, + "'function' is not returned when prefixed with ':'"); + + info("test autocomplete for 'window.func'"); + matches = (await webConsoleFront.autocomplete("window.func")).matches; + ok(!matches.includes("function"), + "'function' is not returned when doing a property access"); + + info("test autocomplete for 'window[func'"); + matches = (await webConsoleFront.autocomplete("window[func")).matches; + ok(!matches.includes("function"), + "'function' is not returned when doing an element access"); + } + + async function dontAutocomplete(webConsoleFront) { + const inputs = [ + "", + " ", + "\n", + "\n ", + " \n ", + " \n", + "true;", + "true,", + "({key:", + "a=", + "if(a<", + "if(a>", + "1+", + "1-", + "++", + "--", + "1*", + "2**", + "1/", + "1%", + "1|", + "1&", + "1^", + "~", + "1<<", + "1>>", + "1>>>", + "false||", + "false&&", + "x=true?", + "x=false?1:", + "!", + ...RESERVED_JS_KEYWORDS.map(keyword => `${keyword} `), + ...RESERVED_JS_KEYWORDS.map(keyword => `${keyword} `), + ]; + for (const input of inputs) { + info(`test autocomplete for "${input}"`); + const matches = (await webConsoleFront.autocomplete(input)).matches; + is(matches, null, `No autocomplete result for ${input}"`); + } + } + + async function getAutocompleteMatches(webConsoleFront, input) { + info(`test autocomplete for "${input}"`); + const res = (await webConsoleFront.autocomplete(input)); + return res.matches; + } + + async function evaluateExpression(consoleFront, expression) { + const onEvaluationResult = consoleFront.once("evaluationResult"); + await consoleFront.evaluateJSAsync({ text: expression }); + return onEvaluationResult; + } + +</script> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_network_get.html b/devtools/shared/webconsole/test/chrome/test_network_get.html new file mode 100644 index 0000000000..71bb6c388c --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_network_get.html @@ -0,0 +1,132 @@ +<!DOCTYPE HTML> +<html lang="en"> +<head> + <meta charset="utf8"> + <title>Test for the network actor (GET request)</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> +</head> +<body> +<p>Test for the network actor (GET request)</p> + +<iframe src="http://example.com/chrome/devtools/shared/webconsole/test/chrome/network_requests_iframe.html"></iframe> + +<script class="testbody" type="text/javascript"> +"use strict"; + +SimpleTest.waitForExplicitFinish(); + +async function startTest() +{ + await SpecialPowers.pushPrefEnv({ + 'set': [ + // Bug 1617611: Fix all the tests broken by "cookies SameSite=lax by default" + ['network.cookie.sameSite.laxByDefault', false], + ] + }); + + const commands = await createCommandsForTab(); + const target = commands.targetCommand.targetFront; + const resourceCommand = commands.resourceCommand; + + info("test network GET request"); + const resource = await new Promise(resolve => { + resourceCommand + .watchResources([resourceCommand.TYPES.NETWORK_EVENT], { + onAvailable: () => {}, + onUpdated: resourceUpdate => { + resolve(resourceUpdate[0].resource); + }, + }) + .then(() => { + // Spawn the network request after we started watching + const iframe = document.querySelector("iframe").contentWindow; + iframe.wrappedJSObject.testXhrGet(null, "data.json?" + Date.now()); + }); + }); + + const webConsoleFront = await target.getFront("console"); + const netActor = resource.actor; + + info("checking request headers"); + const requestHeadersPacket = await webConsoleFront.getRequestHeaders(netActor); + ok(!!requestHeadersPacket.headers.length, `request headers > 0 (${requestHeadersPacket.headers.length})`); + ok(requestHeadersPacket.headersSize > 0, `request headersSize > 0 (${requestHeadersPacket.headersSize})`); + ok(!!requestHeadersPacket.rawHeaders, "request rawHeaders available"); + + checkHeadersOrCookies(requestHeadersPacket.headers, { + Referer: /network_requests_iframe\.html/, + Cookie: /bug768096/, + }); + + checkRawHeaders(requestHeadersPacket.rawHeaders, { + Referer: /network_requests_iframe\.html/, + Cookie: /bug768096/, + }); + + info("checking request cookies"); + const requestCookiesPacket = await webConsoleFront.getRequestCookies(netActor); + is(requestCookiesPacket.cookies.length, 3, "request cookies length"); + + checkHeadersOrCookies(requestCookiesPacket.cookies, { + foobar: "fooval", + omgfoo: "bug768096", + badcookie: "bug826798=st3fan", + }); + + info("checking request POST data"); + const postDataPacket = await webConsoleFront.getRequestPostData(netActor); + ok(!postDataPacket.postData.text, "no request POST data"); + ok(!postDataPacket.postDataDiscarded, "request POST data was not discarded"); + + info("checking response headers"); + const responseHeaderPacket = await webConsoleFront.getResponseHeaders(netActor); + + ok(!!responseHeaderPacket.headers.length, "response headers > 0"); + ok(responseHeaderPacket.headersSize > 0, "response headersSize > 0"); + ok(!!responseHeaderPacket.rawHeaders, "response rawHeaders available"); + + checkHeadersOrCookies(responseHeaderPacket.headers, { + "content-type": /^application\/(json|octet-stream)$/, + "content-length": /^\d+$/, + }); + + checkRawHeaders(responseHeaderPacket.rawHeaders, { + "content-type": /^application\/(json|octet-stream)$/, + "content-length": /^\d+$/, + }); + + info("checking response cookies"); + const responseCookiesPacket = await webConsoleFront.getResponseCookies(netActor); + is(responseCookiesPacket.cookies.length, 0, "response cookies length"); + + info("checking response content"); + const responseContentPacket = await webConsoleFront.getResponseContent(netActor); + ok(responseContentPacket.content.text, "response content text"); + ok(!responseContentPacket.contentDiscarded, "response content was not discarded"); + + info("checking event timings"); + const eventTimingPacket = await webConsoleFront.getEventTimings(netActor); + checkObject(eventTimingPacket, { + timings: { + blocked: /^-1|\d+$/, + dns: /^-1|\d+$/, + connect: /^-1|\d+$/, + send: /^-1|\d+$/, + wait: /^-1|\d+$/, + receive: /^-1|\d+$/, + }, + totalTime: /^\d+$/, + }); + + await commands.destroy(); + SpecialPowers.clearUserPref("network.cookie.sameSite.laxByDefault"); + SimpleTest.finish(); +} + +addEventListener("load", startTest, { once: true}); +</script> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_network_post.html b/devtools/shared/webconsole/test/chrome/test_network_post.html new file mode 100644 index 0000000000..237494c323 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_network_post.html @@ -0,0 +1,143 @@ +<!DOCTYPE HTML> +<html lang="en"> +<head> + <meta charset="utf8"> + <title>Test for the network actor (POST request)</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> +</head> +<body> +<p>Test for the network actor (POST request)</p> + +<iframe src="http://example.com/chrome/devtools/shared/webconsole/test/chrome/network_requests_iframe.html"></iframe> + +<script class="testbody" type="text/javascript"> +"use strict"; + +SimpleTest.waitForExplicitFinish(); + +async function startTest() +{ + await SpecialPowers.pushPrefEnv({ + 'set': [ + // Bug 1617611: Fix all the tests broken by "cookies SameSite=lax by default" + ['network.cookie.sameSite.laxByDefault', false], + ] + }); + + const commands = await createCommandsForTab(); + const target = commands.targetCommand.targetFront; + const resourceCommand = commands.resourceCommand; + + info("test network POST request"); + const resource = await new Promise(resolve => { + resourceCommand + .watchResources([resourceCommand.TYPES.NETWORK_EVENT], { + onAvailable: () => {}, + onUpdated: resourceUpdate => { + resolve(resourceUpdate[0].resource); + }, + }) + .then(() => { + // Spawn the network request after we started watching + const iframe = document.querySelector("iframe").contentWindow; + iframe.wrappedJSObject.testXhrPost(); + }); + }); + + const webConsoleFront = await target.getFront("console"); + const netActor = resource.actor; + + info("checking request headers"); + const requestHeadersPacket = await webConsoleFront.getRequestHeaders(netActor); + + ok(!!requestHeadersPacket.headers.length, "request headers > 0"); + ok(requestHeadersPacket.headersSize > 0, "request headersSize > 0"); + ok(!!requestHeadersPacket.rawHeaders.length, "request rawHeaders available"); + + checkHeadersOrCookies(requestHeadersPacket.headers, { + Referer: /network_requests_iframe\.html/, + Cookie: /bug768096/, + }); + + checkRawHeaders(requestHeadersPacket.rawHeaders, { + Referer: /network_requests_iframe\.html/, + Cookie: /bug768096/, + }); + + info("checking request cookies"); + const requestCookiesPacket = await webConsoleFront.getRequestCookies(netActor); + is(requestCookiesPacket.cookies.length, 3, "request cookies length"); + + checkHeadersOrCookies(requestCookiesPacket.cookies, { + foobar: "fooval", + omgfoo: "bug768096", + badcookie: "bug826798=st3fan", + }); + + info("checking request POST data"); + const requestPostDataPacket = await webConsoleFront.getRequestPostData(netActor); + + checkObject(requestPostDataPacket, { + postData: { + text: /^Hello world! foobaz barr.+foobaz barr$/, + }, + postDataDiscarded: false, + }); + + is(requestPostDataPacket.postData.text.length, 552, "postData text length"); + + info("checking response headers"); + const responseHeadersPacket = await webConsoleFront.getResponseHeaders(netActor); + ok(!!responseHeadersPacket.headers.length, "response headers > 0"); + ok(responseHeadersPacket.headersSize > 0, "response headersSize > 0"); + ok(!!responseHeadersPacket.rawHeaders, "response rawHeaders available"); + + checkHeadersOrCookies(responseHeadersPacket.headers, { + "content-type": /^application\/(json|octet-stream)$/, + "content-length": /^\d+$/, + }); + + checkRawHeaders(responseHeadersPacket.rawHeaders, { + "content-type": /^application\/(json|octet-stream)$/, + "content-length": /^\d+$/, + }); + + info("checking response cookies"); + const responseCookiesPacket = await webConsoleFront.getResponseCookies(netActor); + is(responseCookiesPacket.cookies.length, 0, "response cookies length"); + + info("checking response content"); + const responseContentPacket = await webConsoleFront.getResponseContent(netActor); + checkObject(responseContentPacket, { + content: { + text: /"test JSON data"/, + }, + contentDiscarded: false, + }); + + info("checking event timings"); + const eventTimingsPacket = await webConsoleFront.getEventTimings(netActor); + checkObject(eventTimingsPacket, { + timings: { + blocked: /^-1|\d+$/, + dns: /^-1|\d+$/, + connect: /^-1|\d+$/, + send: /^-1|\d+$/, + wait: /^-1|\d+$/, + receive: /^-1|\d+$/, + }, + totalTime: /^\d+$/, + }); + + await commands.destroy(); + SpecialPowers.clearUserPref("network.cookie.sameSite.laxByDefault"); + SimpleTest.finish(); +} + +addEventListener("load", startTest, { once: true }); +</script> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_network_security-hsts.html b/devtools/shared/webconsole/test/chrome/test_network_security-hsts.html new file mode 100644 index 0000000000..6139aa4e05 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_network_security-hsts.html @@ -0,0 +1,89 @@ +<!DOCTYPE HTML> +<html lang="en"> +<head> + <meta charset="utf8"> + <title>Test for the network actor (HSTS detection)</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> +</head> +<body> +<p>Test for the network actor (HSTS detection)</p> + +<iframe src="https://example.com/chrome/devtools/shared/webconsole/test/chrome/network_requests_iframe.html"></iframe> + +<script class="testbody" type="text/javascript"> +"use strict"; + +SimpleTest.waitForExplicitFinish(); + +const TEST_CASES = [ + { + desc: "no HSTS", + url: "https://example.com", + usesHSTS: false, + }, + { + desc: "HSTS from this response", + url: "https://example.com/"+ + "browser/browser/base/content/test/general/browser_star_hsts.sjs", + usesHSTS: true, + }, + { + desc: "stored HSTS from previous response", + url: "https://example.com/", + usesHSTS: true, + } +]; + +async function startTest() +{ + info("Test detection of HTTP Strict Transport Security."); + for (const testCase of TEST_CASES) { + await checkHSTS(testCase) + } + + // Reset HSTS state. + const gSSService = Cc["@mozilla.org/ssservice;1"].getService(Ci.nsISiteSecurityService); + const uri = Services.io.newURI(TEST_CASES[0].url); + gSSService.resetState(uri); + + SimpleTest.finish(); +} + +async function checkHSTS({desc, url, usesHSTS}) { + info("Testing HSTS for " + url); + const commands = await createCommandsForTab(); + const target = commands.targetCommand.targetFront; + const resourceCommand = commands.resourceCommand; + + const resource = await new Promise(resolve => { + resourceCommand + .watchResources([resourceCommand.TYPES.NETWORK_EVENT], { + onAvailable: () => {}, + onUpdated: resourceUpdate => { + resolve(resourceUpdate[0].resource); + }, + }) + .then(() => { + // Spawn the network requests after we started watching + const iframe = document.querySelector("iframe").contentWindow; + iframe.wrappedJSObject.makeXhrCallback("GET", url); + }); + }); + + const webConsoleFront = await target.getFront("console"); + const packet = await webConsoleFront.getSecurityInfo(resource.actor); + is( + packet.securityInfo.hsts, + usesHSTS, + "Strict Transport Security detected correctly for " + url + ); + await commands.destroy(); +} + +addEventListener("load", startTest, { once: true }); +</script> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_nsiconsolemessage.html b/devtools/shared/webconsole/test/chrome/test_nsiconsolemessage.html new file mode 100644 index 0000000000..4e460225df --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_nsiconsolemessage.html @@ -0,0 +1,74 @@ +<!DOCTYPE HTML> +<html lang="en"> +<head> + <meta charset="utf8"> + <title>Test for nsIConsoleMessages</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> +</head> +<body> +<p>Make sure that nsIConsoleMessages are logged. See bug 859756.</p> + +<script class="testbody" type="text/javascript"> +"use strict"; +SimpleTest.waitForExplicitFinish(); + +let expectedMessages = []; + +async function startTest() +{ + removeEventListener("load", startTest); + const {state} = await attachConsole(["PageError"]); + onAttach(state); +} + +function onAttach(aState) +{ + onLogMessage = onLogMessage.bind(null, aState); + aState.webConsoleFront.on("logMessage", onLogMessage); + + expectedMessages = [{ + message: "hello world! bug859756", + timeStamp: FRACTIONAL_NUMBER_REGEX, + }]; + + Services.console.logStringMessage("hello world! bug859756"); + + info("waiting for messages"); +} + +const receivedMessages = []; + +function onLogMessage(aState, aPacket) +{ + info("received message: " + aPacket.message); + + let found = false; + for (const expected of expectedMessages) { + if (expected.message == aPacket.message) { + found = true; + break; + } + } + if (!found) { + return; + } + + receivedMessages.push(aPacket); + if (receivedMessages.length != expectedMessages.length) { + return; + } + + aState.webConsoleFront.off("logMessage", onLogMessage); + + checkObject(receivedMessages, expectedMessages); + + closeDebugger(aState, () => SimpleTest.finish()); +} + +addEventListener("load", startTest); +</script> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_object_actor.html b/devtools/shared/webconsole/test/chrome/test_object_actor.html new file mode 100644 index 0000000000..f42035e2ce --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_object_actor.html @@ -0,0 +1,158 @@ +<!DOCTYPE HTML> +<html lang="en"> +<head> + <meta charset="utf8"> + <title>Test for the object actor</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> +</head> +<body> +<p>Test for the object actor</p> + +<script class="testbody" type="text/javascript"> +"use strict"; + +SimpleTest.waitForExplicitFinish(); + +SpecialPowers.pushPrefEnv({ + "set": [["security.allow_eval_with_system_principal", true]] +}); + +async function startTest() { + removeEventListener("load", startTest); + + const longString = (new Array(DevToolsServer.LONG_STRING_LENGTH + 3)).join("\u0629"); + createTestGlobalVariable(longString); + + const {state} = await attachConsoleToTab(["ConsoleAPI"]); + const onConsoleApiCall = state.webConsoleFront.once("consoleAPICall"); + top.console.log("hello", top.wrappedJSObject.foobarObject); + const {message} = await onConsoleApiCall; + + info("checking the console API call packet"); + checkConsoleAPICall(message, { + level: "log", + filename: /test_object_actor/, + arguments: ["hello", { + type: "object", + actor: /[a-z]/, + }], + }); + + info("inspecting object properties"); + const {ownProperties} = await message.arguments[1].getPrototypeAndProperties(); + + const expectedProps = { + "abArray": { + value: { + type: "object", + class: "Array", + actor: /[a-z]/, + }, + }, + "foo": { + configurable: true, + enumerable: true, + writable: true, + value: 1, + }, + "foobar": { + value: "hello", + }, + "foobaz": { + value: { + type: "object", + class: "HTMLDocument", + actor: /[a-z]/, + }, + }, + "getterAndSetter": { + get: { + type: "object", + class: "Function", + actor: /[a-z]/, + }, + set: { + type: "object", + class: "Function", + actor: /[a-z]/, + }, + }, + "longStringObj": { + value: { + type: "object", + class: "Object", + actor: /[a-z]/, + }, + }, + "notInspectable": { + value: { + type: "object", + class: "Object", + actor: /[a-z]/, + }, + }, + "omg": { + value: { type: "null" }, + }, + "omgfn": { + value: { + type: "object", + class: "Function", + actor: /[a-z]/, + }, + }, + "tamarbuta": { + value: { + type: "longString", + initial: longString.substring(0, + DevToolsServer.LONG_STRING_INITIAL_LENGTH), + length: longString.length, + }, + }, + "testfoo": { + value: false, + }, + }; + is(Object.keys(ownProperties).length, Object.keys(expectedProps).length, + "number of enumerable properties"); + checkObject(ownProperties, expectedProps); + + await closeDebugger(state); + SimpleTest.finish(); +} + + +function createTestGlobalVariable(longString) { + // Here we put the objects in the correct window, to avoid having them all + // wrapped by proxies for cross-compartment access. + const foobarObject = top.Object.create(null); + foobarObject.tamarbuta = longString; + foobarObject.foo = 1; + foobarObject.foobar = "hello"; + foobarObject.omg = null; + foobarObject.testfoo = false; + foobarObject.notInspectable = top.Object.create(null); + foobarObject.omgfn = new top.Function("return 'myResult'"); + foobarObject.abArray = new top.Array("a", "b"); + foobarObject.foobaz = top.document; + + top.Object.defineProperty(foobarObject, "getterAndSetter", { + enumerable: true, + get: new top.Function("return 'foo';"), + set: new top.Function("1+2"), + }); + + foobarObject.longStringObj = top.Object.create(null); + foobarObject.longStringObj.toSource = new top.Function("'" + longString + "'"); + foobarObject.longStringObj.toString = new top.Function("'" + longString + "'"); + foobarObject.longStringObj.boom = "explode"; + top.wrappedJSObject.foobarObject = foobarObject; +} + +addEventListener("load", startTest); +</script> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_object_actor_native_getters.html b/devtools/shared/webconsole/test/chrome/test_object_actor_native_getters.html new file mode 100644 index 0000000000..6ac292fb9a --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_object_actor_native_getters.html @@ -0,0 +1,75 @@ +<!DOCTYPE HTML> +<html lang="en"> +<head> + <meta charset="utf8"> + <title>Test for the native getters in object actors</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> +</head> +<body> +<p>Test for the native getters in object actors</p> + +<script class="testbody" type="text/javascript"> +"use strict"; + +SimpleTest.waitForExplicitFinish(); + +async function startTest() { + removeEventListener("load", startTest); + const {state} = await attachConsoleToTab(["ConsoleAPI"]); + + const onConsoleAPICall = state.webConsoleFront.once("consoleAPICall"); + top.console.log("hello", document); + const {message} = await onConsoleAPICall; + + info("checking the console API call packet"); + checkConsoleAPICall(message, { + level: "log", + filename: /test_object_actor/, + arguments: ["hello", { + type: "object", + actor: /[a-z]/, + }], + }); + + info("inspecting object properties"); + const args = message.arguments; + const {ownProperties, safeGetterValues} = await args[1].getPrototypeAndProperties(); + + const expectedProps = { + "location": { + get: { + type: "object", + class: "Function", + actor: /[a-z]/, + }, + }, + }; + ok(Object.keys(ownProperties).length >= Object.keys(expectedProps).length, + "number of properties"); + + info("check ownProperties"); + checkObject(ownProperties, expectedProps); + + info("check safeGetterValues"); + checkObject(safeGetterValues, { + "title": { + getterValue: /native getters in object actors/, + getterPrototypeLevel: 2, + }, + "styleSheets": { + getterValue: /Front for obj\//, + getterPrototypeLevel: 2, + }, + }); + + await closeDebugger(state); + SimpleTest.finish(); +} + +addEventListener("load", startTest); +</script> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_object_actor_native_getters_lenient_this.html b/devtools/shared/webconsole/test/chrome/test_object_actor_native_getters_lenient_this.html new file mode 100644 index 0000000000..473dfb3b03 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_object_actor_native_getters_lenient_this.html @@ -0,0 +1,54 @@ +<!DOCTYPE HTML> +<html lang="en"> +<head> + <meta charset="utf8"> + <title>Test that WebIDL attributes with the LenientThis extended attribute + do not appear in the wrong objects</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> +</head> +<body> +<p>Test for the native getters in object actors</p> + +<script class="testbody" type="text/javascript"> +"use strict"; + +SimpleTest.waitForExplicitFinish(); + +async function startTest() { + removeEventListener("load", startTest); + const {state} = await attachConsoleToTab(["ConsoleAPI"]); + + const onConsoleApiCall = state.webConsoleFront.once("consoleAPICall"); + const docAsProto = Object.create(document); + top.console.log("hello", docAsProto); + const {message} = await onConsoleApiCall; + + info("checking the console API call packet"); + checkConsoleAPICall(message, { + level: "log", + filename: /test_object_actor/, + arguments: ["hello", { + type: "object", + actor: /[a-z]/, + }], + }); + + info("inspecting object properties"); + const args = message.arguments; + + const {ownProperties, safeGetterValues} = await args[1].getPrototypeAndProperties(); + + is(Object.keys(ownProperties).length, 0, "number of properties"); + is(Object.keys(safeGetterValues).length, 0, "number of safe getters"); + + await closeDebugger(state); + SimpleTest.finish(); +} + +addEventListener("load", startTest); +</script> +</body> +</html> diff --git a/devtools/shared/webconsole/test/chrome/test_page_errors.html b/devtools/shared/webconsole/test/chrome/test_page_errors.html new file mode 100644 index 0000000000..0976eed92d --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_page_errors.html @@ -0,0 +1,224 @@ +<!DOCTYPE HTML> +<html lang="en"> +<head> + <meta charset="utf8"> + <title>Test for page errors</title> + <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> + <script type="text/javascript" src="common.js"></script> + <!-- Any copyright is dedicated to the Public Domain. + - http://creativecommons.org/publicdomain/zero/1.0/ --> +</head> +<body> +<p>Test for page errors</p> + +<script class="testbody" type="text/javascript"> +"use strict"; + +const { MESSAGE_CATEGORY } = require("devtools/shared/constants"); +SimpleTest.waitForExplicitFinish(); + +const previousEnabled = window.docShell.cssErrorReportingEnabled; +window.docShell.cssErrorReportingEnabled = true; + +SimpleTest.registerCleanupFunction(() => { + window.docShell.cssErrorReportingEnabled = previousEnabled; +}); + +let expectedPageErrors = []; + +const NO_UNCAUGHT_EXCEPTION = Symbol(); + +function doPageErrors() { + expectedPageErrors = { + "document.body.style.color = 'fooColor';": { + errorMessage: /fooColor/, + sourceName: /test_page_errors/, + category: MESSAGE_CATEGORY.CSS_PARSER, + timeStamp: FRACTIONAL_NUMBER_REGEX, + error: false, + warning: true, + }, + "document.doTheImpossible();": { + errorMessage: /doTheImpossible/, + errorMessageName: undefined, + sourceName: /test_page_errors/, + category: "chrome javascript", + timeStamp: FRACTIONAL_NUMBER_REGEX, + error: true, + warning: false, + }, + "(42).toString(0);": { + errorMessage: /radix/, + errorMessageName: "JSMSG_BAD_RADIX", + sourceName: /test_page_errors/, + category: "chrome javascript", + timeStamp: FRACTIONAL_NUMBER_REGEX, + error: true, + warning: false, + }, + "'use strict'; (Object.freeze({name: 'Elsa', score: 157})).score = 0;": { + errorMessage: /read.only/, + errorMessageName: "JSMSG_READ_ONLY", + sourceName: /test_page_errors/, + category: "chrome javascript", + timeStamp: FRACTIONAL_NUMBER_REGEX, + error: true, + warning: false, + }, + "([]).length = -1": { + errorMessage: /array length/, + errorMessageName: "JSMSG_BAD_ARRAY_LENGTH", + sourceName: /test_page_errors/, + category: "chrome javascript", + timeStamp: FRACTIONAL_NUMBER_REGEX, + error: true, + warning: false, + }, + "'abc'.repeat(-1);": { + errorMessage: /repeat count.*non-negative/, + errorMessageName: "JSMSG_NEGATIVE_REPETITION_COUNT", + sourceName: /test_page_errors/, + category: "chrome javascript", + timeStamp: FRACTIONAL_NUMBER_REGEX, + error: true, + warning: false, + }, + "'a'.repeat(2e28);": { + errorMessage: /repeat count.*less than infinity/, + errorMessageName: "JSMSG_RESULTING_STRING_TOO_LARGE", + sourceName: /test_page_errors/, + category: "chrome javascript", + timeStamp: FRACTIONAL_NUMBER_REGEX, + error: true, + warning: false, + }, + "77.1234.toExponential(-1);": { + errorMessage: /out of range/, + errorMessageName: "JSMSG_PRECISION_RANGE", + sourceName: /test_page_errors/, + category: "chrome javascript", + timeStamp: FRACTIONAL_NUMBER_REGEX, + error: true, + warning: false, + }, + "function a() { return; 1 + 1; }": { + errorMessage: /unreachable code/, + errorMessageName: "JSMSG_STMT_AFTER_RETURN", + sourceName: /test_page_errors/, + category: "chrome javascript", + timeStamp: FRACTIONAL_NUMBER_REGEX, + error: false, + warning: true, + }, + "let a, a;": { + errorMessage: /redeclaration of/, + errorMessageName: "JSMSG_REDECLARED_VAR", + sourceName: /test_page_errors/, + category: "chrome javascript", + timeStamp: FRACTIONAL_NUMBER_REGEX, + error: true, + warning: false, + notes: [ + { + messageBody: /Previously declared at line/, + frame: { + source: /test_page_errors/, + } + } + ] + }, + [`let error = new TypeError("abc"); + error.name = "MyError"; + error.message = "here"; + throw error`]: { + errorMessage: /MyError: here/, + errorMessageName: "", + sourceName: /test_page_errors/, + category: "chrome javascript", + timeStamp: FRACTIONAL_NUMBER_REGEX, + error: true, + warning: false, + }, + "DOMTokenList.prototype.contains.call([])": { + errorMessage: /does not implement interface/, + errorMessageName: "MSG_METHOD_THIS_DOES_NOT_IMPLEMENT_INTERFACE", + sourceName: /test_page_errors/, + category: "chrome javascript", + timeStamp: FRACTIONAL_NUMBER_REGEX, + error: true, + warning: false, + }, + [`let error2 = new TypeError("abc"); + error2.name = "MyPromiseError"; + error2.message = "here2"; + Promise.reject(error2)`]: { + errorMessage: /MyPromiseError: here2/, + errorMessageName: "", + sourceName: /test_page_errors/, + category: "chrome javascript", + timeStamp: FRACTIONAL_NUMBER_REGEX, + error: true, + warning: false, + // Promise.reject doesn't produce an uncaught exception + // even though |exception: true|. + [NO_UNCAUGHT_EXCEPTION]: true + } + }; + + let container = document.createElement("script"); + for (const stmt of Object.keys(expectedPageErrors)) { + if (expectedPageErrors[stmt].error && + !expectedPageErrors[stmt][NO_UNCAUGHT_EXCEPTION]) { + SimpleTest.expectUncaughtException(); + } + info("starting stmt: " + stmt); + container = document.createElement("script"); + document.body.appendChild(container); + container.textContent = stmt; + document.body.removeChild(container); + info("ending stmt: " + stmt); + } +} + +async function startTest() { + removeEventListener("load", startTest); + + const {state} = await attachConsole(["PageError"]); + onAttach(state); +} + +function onAttach(state) { + onPageError = onPageError.bind(null, state); + state.webConsoleFront.on("pageError", onPageError); + doPageErrors(); +} + +const pageErrors = []; + +function onPageError(state, packet) { + if (!packet.pageError.sourceName.includes("test_page_errors")) { + info("Ignoring error from unknown source: " + packet.pageError.sourceName); + return; + } + + pageErrors.push(packet.pageError); + if (pageErrors.length != Object.keys(expectedPageErrors).length) { + return; + } + + state.webConsoleFront.off("pageError", onPageError); + + Object.values(expectedPageErrors).forEach(function(message, index) { + info("checking received page error #" + index); + checkObject(pageErrors[index], Object.values(expectedPageErrors)[index]); + }); + + closeDebugger(state, function() { + SimpleTest.finish(); + }); +} + +addEventListener("load", startTest); +</script> +</body> +</html> diff --git a/devtools/shared/webconsole/test/xpcshell/.eslintrc.js b/devtools/shared/webconsole/test/xpcshell/.eslintrc.js new file mode 100644 index 0000000000..8611c174f5 --- /dev/null +++ b/devtools/shared/webconsole/test/xpcshell/.eslintrc.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = { + // Extend from the common devtools xpcshell eslintrc config. + extends: "../../../../.eslintrc.xpcshell.js", +}; diff --git a/devtools/shared/webconsole/test/xpcshell/head.js b/devtools/shared/webconsole/test/xpcshell/head.js new file mode 100644 index 0000000000..e65552771e --- /dev/null +++ b/devtools/shared/webconsole/test/xpcshell/head.js @@ -0,0 +1,10 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +/* exported require */ + +"use strict"; + +var { require } = ChromeUtils.importESModule( + "resource://devtools/shared/loader/Loader.sys.mjs" +); diff --git a/devtools/shared/webconsole/test/xpcshell/test_analyze_input_string.js b/devtools/shared/webconsole/test/xpcshell/test_analyze_input_string.js new file mode 100644 index 0000000000..3df015056f --- /dev/null +++ b/devtools/shared/webconsole/test/xpcshell/test_analyze_input_string.js @@ -0,0 +1,225 @@ +// Any copyright is dedicated to the Public Domain. +// http://creativecommons.org/publicdomain/zero/1.0/ + +"use strict"; +const { + analyzeInputString, +} = require("resource://devtools/shared/webconsole/analyze-input-string.js"); + +add_task(() => { + const tests = [ + { + desc: "simple property access", + input: `var a = {b: 1};a.b`, + expected: { + isElementAccess: false, + isPropertyAccess: true, + expressionBeforePropertyAccess: `var a = {b: 1};a`, + lastStatement: "a.b", + mainExpression: `a`, + matchProp: `b`, + }, + }, + { + desc: "deep property access", + input: `a.b.c`, + expected: { + isElementAccess: false, + isPropertyAccess: true, + expressionBeforePropertyAccess: `a.b`, + lastStatement: "a.b.c", + mainExpression: `a.b`, + matchProp: `c`, + }, + }, + { + desc: "element access", + input: `a["b`, + expected: { + isElementAccess: true, + isPropertyAccess: true, + expressionBeforePropertyAccess: `a`, + lastStatement: `a["b`, + mainExpression: `a`, + matchProp: `"b`, + }, + }, + { + desc: "element access without quotes", + input: `a[b`, + expected: { + isElementAccess: true, + isPropertyAccess: true, + expressionBeforePropertyAccess: `a`, + lastStatement: `a[b`, + mainExpression: `a`, + matchProp: `b`, + }, + }, + { + desc: "simple optional chaining access", + input: `a?.b`, + expected: { + isElementAccess: false, + isPropertyAccess: true, + expressionBeforePropertyAccess: `a`, + lastStatement: `a?.b`, + mainExpression: `a`, + matchProp: `b`, + }, + }, + { + desc: "deep optional chaining access", + input: `a?.b?.c`, + expected: { + isElementAccess: false, + isPropertyAccess: true, + expressionBeforePropertyAccess: `a?.b`, + lastStatement: `a?.b?.c`, + mainExpression: `a?.b`, + matchProp: `c`, + }, + }, + { + desc: "optional chaining element access", + input: `a?.["b`, + expected: { + isElementAccess: true, + isPropertyAccess: true, + expressionBeforePropertyAccess: `a`, + lastStatement: `a?.["b`, + mainExpression: `a`, + matchProp: `"b`, + }, + }, + { + desc: "optional chaining element access without quotes", + input: `a?.[b`, + expected: { + isElementAccess: true, + isPropertyAccess: true, + expressionBeforePropertyAccess: `a`, + lastStatement: `a?.[b`, + mainExpression: `a`, + matchProp: `b`, + }, + }, + { + desc: "deep optional chaining element access with quotes", + input: `var a = {b: 1, c: ["."]}; a?.["b"]?.c?.["d[.`, + expected: { + isElementAccess: true, + isPropertyAccess: true, + expressionBeforePropertyAccess: `var a = {b: 1, c: ["."]}; a?.["b"]?.c`, + lastStatement: `a?.["b"]?.c?.["d[.`, + mainExpression: `a?.["b"]?.c`, + matchProp: `"d[.`, + }, + }, + { + desc: "literal arrays with newline", + input: `[1,2,3,\n4\n].`, + expected: { + isElementAccess: false, + isPropertyAccess: true, + expressionBeforePropertyAccess: `[1,2,3,\n4\n]`, + lastStatement: `[1,2,3,4].`, + mainExpression: `[1,2,3,4]`, + matchProp: ``, + }, + }, + { + desc: "number literal with newline", + input: `1\n.`, + expected: { + isElementAccess: false, + isPropertyAccess: true, + expressionBeforePropertyAccess: `1\n`, + lastStatement: `1\n.`, + mainExpression: `1`, + matchProp: ``, + }, + }, + { + desc: "string literal", + input: `"abc".`, + expected: { + isElementAccess: false, + isPropertyAccess: true, + expressionBeforePropertyAccess: `"abc"`, + lastStatement: `"abc".`, + mainExpression: `"abc"`, + matchProp: ``, + }, + }, + { + desc: "string literal containing backslash", + input: `"\\n".`, + expected: { + isElementAccess: false, + isPropertyAccess: true, + expressionBeforePropertyAccess: `"\\n"`, + lastStatement: `"\\n".`, + mainExpression: `"\\n"`, + matchProp: ``, + }, + }, + { + desc: "single quote string literal containing backslash", + input: `'\\r'.`, + expected: { + isElementAccess: false, + isPropertyAccess: true, + expressionBeforePropertyAccess: `'\\r'`, + lastStatement: `'\\r'.`, + mainExpression: `'\\r'`, + matchProp: ``, + }, + }, + { + desc: "template string literal containing backslash", + input: "`\\\\`.", + expected: { + isElementAccess: false, + isPropertyAccess: true, + expressionBeforePropertyAccess: "`\\\\`", + lastStatement: "`\\\\`.", + mainExpression: "`\\\\`", + matchProp: ``, + }, + }, + { + desc: "unterminated double quote string literal", + input: `"\n`, + expected: { + err: "unterminated string literal", + }, + }, + { + desc: "unterminated single quote string literal", + input: `'\n`, + expected: { + err: "unterminated string literal", + }, + }, + { + desc: "optional chaining operator with spaces", + input: `test ?. ["propA"] ?. [0] ?. ["propB"] ?. ['to`, + expected: { + isElementAccess: true, + isPropertyAccess: true, + expressionBeforePropertyAccess: `test ?. ["propA"] ?. [0] ?. ["propB"] `, + lastStatement: `test ?. ["propA"] ?. [0] ?. ["propB"] ?. ['to`, + mainExpression: `test ?. ["propA"] ?. [0] ?. ["propB"]`, + matchProp: `'to`, + }, + }, + ]; + + for (const { input, desc, expected } of tests) { + const result = analyzeInputString(input); + for (const [key, value] of Object.entries(expected)) { + Assert.equal(value, result[key], `${desc} | ${key} has expected value`); + } + } +}); diff --git a/devtools/shared/webconsole/test/xpcshell/test_js_property_provider.js b/devtools/shared/webconsole/test/xpcshell/test_js_property_provider.js new file mode 100644 index 0000000000..a6f2daee4b --- /dev/null +++ b/devtools/shared/webconsole/test/xpcshell/test_js_property_provider.js @@ -0,0 +1,746 @@ +// Any copyright is dedicated to the Public Domain. +// http://creativecommons.org/publicdomain/zero/1.0/ + +"use strict"; +const { + FallibleJSPropertyProvider: JSPropertyProvider, +} = require("resource://devtools/shared/webconsole/js-property-provider.js"); + +const { addDebuggerToGlobal } = ChromeUtils.importESModule( + "resource://gre/modules/jsdebugger.sys.mjs" +); +addDebuggerToGlobal(globalThis); + +function run_test() { + Services.prefs.setBoolPref( + "security.allow_parent_unrestricted_js_loads", + true + ); + registerCleanupFunction(() => { + Services.prefs.clearUserPref("security.allow_parent_unrestricted_js_loads"); + }); + + const testArray = `var testArray = [ + {propA: "A"}, + { + propB: "B", + propC: [ + "D" + ] + }, + [ + {propE: "E"} + ] + ]`; + + const testObject = 'var testObject = {"propA": [{"propB": "B"}]}'; + const testHyphenated = 'var testHyphenated = {"prop-A": "res-A"}'; + const testLet = "let foobar = {a: ''}; const blargh = {a: 1};"; + + const testGenerators = ` + // Test with generator using a named function. + function* genFunc() { + for (let i = 0; i < 10; i++) { + yield i; + } + } + let gen1 = genFunc(); + gen1.next(); + + // Test with generator using an anonymous function. + let gen2 = (function* () { + for (let i = 0; i < 10; i++) { + yield i; + } + })();`; + + const testGetters = ` + var testGetters = { + get x() { + return Object.create(null, Object.getOwnPropertyDescriptors({ + hello: "", + world: "", + })); + }, + get y() { + return Object.create(null, Object.getOwnPropertyDescriptors({ + get y() { + return "plop"; + }, + })); + } + }; + `; + + const testProxies = ` + var testSelfPrototypeProxy = new Proxy({ + hello: 1 + }, { + getPrototypeOf: () => testProxy + }); + var testArrayPrototypeProxy = new Proxy({ + world: 2 + }, { + getPrototypeOf: () => Array.prototype + }) + `; + + const sandbox = Cu.Sandbox("http://example.com"); + const dbg = new Debugger(); + const dbgObject = dbg.addDebuggee(sandbox); + const dbgEnv = dbgObject.asEnvironment(); + Cu.evalInSandbox( + ` + const hello = Object.create(null, Object.getOwnPropertyDescriptors({world: 1})); + String.prototype.hello = hello; + Number.prototype.hello = hello; + Array.prototype.hello = hello; + `, + sandbox + ); + Cu.evalInSandbox(testArray, sandbox); + Cu.evalInSandbox(testObject, sandbox); + Cu.evalInSandbox(testHyphenated, sandbox); + Cu.evalInSandbox(testLet, sandbox); + Cu.evalInSandbox(testGenerators, sandbox); + Cu.evalInSandbox(testGetters, sandbox); + Cu.evalInSandbox(testProxies, sandbox); + + info("Running tests with dbgObject"); + runChecks(dbgObject, null, sandbox); + + info("Running tests with dbgEnv"); + runChecks(null, dbgEnv, sandbox); +} + +function runChecks(dbgObject, environment, sandbox) { + const propertyProvider = (inputValue, options) => + JSPropertyProvider({ + dbgObject, + environment, + inputValue, + ...options, + }); + + info("Test that suggestions are given for 'this'"); + let results = propertyProvider("t"); + test_has_result(results, "this"); + + if (dbgObject != null) { + info("Test that suggestions are given for 'this.'"); + results = propertyProvider("this."); + test_has_result(results, "testObject"); + + info("Test that suggestions are given for '(this).'"); + results = propertyProvider("(this)."); + test_has_result(results, "testObject"); + + info("Test that suggestions are given for deep 'this' properties access"); + results = propertyProvider("(this).testObject.propA."); + test_has_result(results, "shift"); + + results = propertyProvider("(this).testObject.propA["); + test_has_result(results, `"shift"`); + + results = propertyProvider("(this)['testObject']['propA']["); + test_has_result(results, `"shift"`); + + results = propertyProvider("(this).testObject['propA']."); + test_has_result(results, "shift"); + + info("Test that no suggestions are given for 'this.this'"); + results = propertyProvider("this.this"); + test_has_no_results(results); + } + + info("Test that suggestions are given for 'globalThis'"); + results = propertyProvider("g"); + test_has_result(results, "globalThis"); + + info("Test that suggestions are given for 'globalThis.'"); + results = propertyProvider("globalThis."); + test_has_result(results, "testObject"); + + info("Test that suggestions are given for '(globalThis).'"); + results = propertyProvider("(globalThis)."); + test_has_result(results, "testObject"); + + info( + "Test that suggestions are given for deep 'globalThis' properties access" + ); + results = propertyProvider("(globalThis).testObject.propA."); + test_has_result(results, "shift"); + + results = propertyProvider("(globalThis).testObject.propA["); + test_has_result(results, `"shift"`); + + results = propertyProvider("(globalThis)['testObject']['propA']["); + test_has_result(results, `"shift"`); + + results = propertyProvider("(globalThis).testObject['propA']."); + test_has_result(results, "shift"); + + info("Testing lexical scope issues (Bug 1207868)"); + results = propertyProvider("foobar"); + test_has_result(results, "foobar"); + + results = propertyProvider("foobar."); + test_has_result(results, "a"); + + results = propertyProvider("blargh"); + test_has_result(results, "blargh"); + + results = propertyProvider("blargh."); + test_has_result(results, "a"); + + info("Test that suggestions are given for 'foo[n]' where n is an integer."); + results = propertyProvider("testArray[0]."); + test_has_result(results, "propA"); + + info("Test that suggestions are given for multidimensional arrays."); + results = propertyProvider("testArray[2][0]."); + test_has_result(results, "propE"); + + info("Test that suggestions are given for nested arrays."); + results = propertyProvider("testArray[1].propC[0]."); + test_has_result(results, "indexOf"); + + info("Test that suggestions are given for literal arrays."); + results = propertyProvider("[1,2,3]."); + test_has_result(results, "indexOf"); + + results = propertyProvider("[1,2,3].h"); + test_has_result(results, "hello"); + + results = propertyProvider("[1,2,3].hello.w"); + test_has_result(results, "world"); + + info("Test that suggestions are given for literal arrays with newlines."); + results = propertyProvider("[1,2,3,\n4\n]."); + test_has_result(results, "indexOf"); + + info("Test that suggestions are given for literal strings."); + results = propertyProvider("'foo'."); + test_has_result(results, "charAt"); + results = propertyProvider('"foo".'); + test_has_result(results, "charAt"); + results = propertyProvider("`foo`."); + test_has_result(results, "charAt"); + results = propertyProvider("`foo doc`."); + test_has_result(results, "charAt"); + results = propertyProvider('`foo " doc`.'); + test_has_result(results, "charAt"); + results = propertyProvider("`foo ' doc`."); + test_has_result(results, "charAt"); + results = propertyProvider("'[1,2,3]'."); + test_has_result(results, "charAt"); + results = propertyProvider("'foo'.h"); + test_has_result(results, "hello"); + results = propertyProvider("'foo'.hello.w"); + test_has_result(results, "world"); + results = propertyProvider(`"\\n".`); + test_has_result(results, "charAt"); + results = propertyProvider(`'\\r'.`); + test_has_result(results, "charAt"); + results = propertyProvider("`\\\\`."); + test_has_result(results, "charAt"); + + info("Test that suggestions are not given for syntax errors."); + results = propertyProvider("'foo\""); + Assert.equal(null, results); + results = propertyProvider("'foo d"); + Assert.equal(null, results); + results = propertyProvider(`"foo d`); + Assert.equal(null, results); + results = propertyProvider("`foo d"); + Assert.equal(null, results); + results = propertyProvider("[1,',2]"); + Assert.equal(null, results); + results = propertyProvider("'[1,2]."); + Assert.equal(null, results); + results = propertyProvider("'foo'.."); + Assert.equal(null, results); + + info("Test that suggestions are not given without a dot."); + results = propertyProvider("'foo'"); + test_has_no_results(results); + results = propertyProvider("`foo`"); + test_has_no_results(results); + results = propertyProvider("[1,2,3]"); + test_has_no_results(results); + results = propertyProvider("[1,2,3].\n'foo'"); + test_has_no_results(results); + + info("Test that suggestions are not given for index that's out of bounds."); + results = propertyProvider("testArray[10]."); + Assert.equal(null, results); + + info("Test that invalid element access syntax does not return anything"); + results = propertyProvider("testArray[][1]."); + Assert.equal(null, results); + + info("Test that deep element access works."); + results = propertyProvider("testObject['propA'][0]."); + test_has_result(results, "propB"); + + results = propertyProvider("testArray[1]['propC']."); + test_has_result(results, "shift"); + + results = propertyProvider("testArray[1].propC[0]["); + test_has_result(results, `"trim"`); + + results = propertyProvider("testArray[1].propC[0]."); + test_has_result(results, "trim"); + + info( + "Test that suggestions are displayed when variable is wrapped in parens" + ); + results = propertyProvider("(testObject)['propA'][0]."); + test_has_result(results, "propB"); + + results = propertyProvider("(testArray)[1]['propC']."); + test_has_result(results, "shift"); + + results = propertyProvider("(testArray)[1].propC[0]["); + test_has_result(results, `"trim"`); + + results = propertyProvider("(testArray)[1].propC[0]."); + test_has_result(results, "trim"); + + info("Test that suggestions are given if there is an hyphen in the chain."); + results = propertyProvider("testHyphenated['prop-A']."); + test_has_result(results, "trim"); + + info("Test that we have suggestions for generators."); + const gen1Result = Cu.evalInSandbox("gen1.next().value", sandbox); + results = propertyProvider("gen1."); + test_has_result(results, "next"); + info("Test that the generator next() was not executed"); + const gen1NextResult = Cu.evalInSandbox("gen1.next().value", sandbox); + Assert.equal(gen1Result + 1, gen1NextResult); + + info("Test with an anonymous generator."); + const gen2Result = Cu.evalInSandbox("gen2.next().value", sandbox); + results = propertyProvider("gen2."); + test_has_result(results, "next"); + const gen2NextResult = Cu.evalInSandbox("gen2.next().value", sandbox); + Assert.equal(gen2Result + 1, gen2NextResult); + + info( + "Test that getters are not executed if authorizedEvaluations is undefined" + ); + results = propertyProvider("testGetters.x."); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); + + results = propertyProvider("testGetters.x["); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); + + results = propertyProvider("testGetters.x.hell"); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); + + results = propertyProvider("testGetters.x['hell"); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); + + info( + "Test that getters are not executed if authorizedEvaluations does not match" + ); + results = propertyProvider("testGetters.x.", { authorizedEvaluations: [] }); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); + + results = propertyProvider("testGetters.x.", { + authorizedEvaluations: [["testGetters"]], + }); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); + + results = propertyProvider("testGetters.x.", { + authorizedEvaluations: [["testGtrs", "x"]], + }); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); + + results = propertyProvider("testGetters.x.", { + authorizedEvaluations: [["x"]], + }); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); + + info("Test that deep getter property access returns intermediate getters"); + results = propertyProvider("testGetters.y.y."); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y"], + }); + + results = propertyProvider("testGetters['y'].y."); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y"], + }); + + results = propertyProvider("testGetters['y']['y']."); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y"], + }); + + results = propertyProvider("testGetters.y['y']."); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y"], + }); + + info("Test that deep getter property access invoke intermediate getters"); + results = propertyProvider("testGetters.y.y.", { + authorizedEvaluations: [["testGetters", "y"]], + }); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y", "y"], + }); + + results = propertyProvider("testGetters['y'].y.", { + authorizedEvaluations: [["testGetters", "y"]], + }); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y", "y"], + }); + + results = propertyProvider("testGetters['y']['y'].", { + authorizedEvaluations: [["testGetters", "y"]], + }); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y", "y"], + }); + + results = propertyProvider("testGetters.y['y'].", { + authorizedEvaluations: [["testGetters", "y"]], + }); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y", "y"], + }); + + info( + "Test that getters are executed if matching an authorizedEvaluation element" + ); + results = propertyProvider("testGetters.x.", { + authorizedEvaluations: [["testGetters", "x"]], + }); + test_has_exact_results(results, ["hello", "world"]); + Assert.ok(Object.keys(results).includes("isUnsafeGetter") === false); + Assert.ok(Object.keys(results).includes("getterPath") === false); + + results = propertyProvider("testGetters.x.", { + authorizedEvaluations: [["testGetters", "x"], ["y"]], + }); + test_has_exact_results(results, ["hello", "world"]); + Assert.ok(Object.keys(results).includes("isUnsafeGetter") === false); + Assert.ok(Object.keys(results).includes("getterPath") === false); + + info("Test that executing getters filters with provided string"); + results = propertyProvider("testGetters.x.hell", { + authorizedEvaluations: [["testGetters", "x"]], + }); + test_has_exact_results(results, ["hello"]); + + results = propertyProvider("testGetters.x['hell", { + authorizedEvaluations: [["testGetters", "x"]], + }); + test_has_exact_results(results, ["'hello'"]); + + info( + "Test children getters are not executed if not included in authorizedEvaluation" + ); + results = propertyProvider("testGetters.y.y.", { + authorizedEvaluations: [["testGetters", "y", "y"]], + }); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y"], + }); + + info( + "Test children getters are executed if matching an authorizedEvaluation element" + ); + results = propertyProvider("testGetters.y.y.", { + authorizedEvaluations: [ + ["testGetters", "y"], + ["testGetters", "y", "y"], + ], + }); + test_has_result(results, "trim"); + + info("Test with number literals"); + results = propertyProvider("1."); + Assert.ok(results === null, "Does not complete on possible floating number"); + + results = propertyProvider("(1).."); + Assert.ok(results === null, "Does not complete on invalid syntax"); + + results = propertyProvider("(1.1.)."); + Assert.ok(results === null, "Does not complete on invalid syntax"); + + results = propertyProvider("1.."); + test_has_result(results, "toFixed"); + + results = propertyProvider("1 ."); + test_has_result(results, "toFixed"); + + results = propertyProvider("1\n."); + test_has_result(results, "toFixed"); + + results = propertyProvider(".1."); + test_has_result(results, "toFixed"); + + results = propertyProvider("1["); + test_has_result(results, `"toFixed"`); + + results = propertyProvider("1[toFixed"); + test_has_exact_results(results, [`"toFixed"`]); + + results = propertyProvider("1['toFixed"); + test_has_exact_results(results, ["'toFixed'"]); + + results = propertyProvider("1.1["); + test_has_result(results, `"toFixed"`); + + results = propertyProvider("(1)."); + test_has_result(results, "toFixed"); + + results = propertyProvider("(.1)."); + test_has_result(results, "toFixed"); + + results = propertyProvider("(1.1)."); + test_has_result(results, "toFixed"); + + results = propertyProvider("(1).toFixed"); + test_has_exact_results(results, ["toFixed"]); + + results = propertyProvider("(1)["); + test_has_result(results, `"toFixed"`); + + results = propertyProvider("(1.1)["); + test_has_result(results, `"toFixed"`); + + results = propertyProvider("(1)[toFixed"); + test_has_exact_results(results, [`"toFixed"`]); + + results = propertyProvider("(1)['toFixed"); + test_has_exact_results(results, ["'toFixed'"]); + + results = propertyProvider("(1).h"); + test_has_result(results, "hello"); + + results = propertyProvider("(1).hello.w"); + test_has_result(results, "world"); + + info("Test access on dot-notation invalid property name"); + results = propertyProvider("testHyphenated.prop"); + Assert.ok( + !results.matches.has("prop-A"), + "Does not return invalid property name on dot access" + ); + + results = propertyProvider("testHyphenated['prop"); + test_has_result(results, `'prop-A'`); + + results = propertyProvider(`//t`); + Assert.ok(results === null, "Does not complete in inline comment"); + + results = propertyProvider(`// t`); + Assert.ok( + results === null, + "Does not complete in inline comment after space" + ); + + results = propertyProvider(`//I'm a comment\nt`); + test_has_result(results, "testObject"); + + results = propertyProvider(`1/t`); + test_has_result(results, "testObject"); + + results = propertyProvider(`/* t`); + Assert.ok(results === null, "Does not complete in multiline comment"); + + results = propertyProvider(`/*I'm\nt`); + Assert.ok( + results === null, + "Does not complete in multiline comment after line break" + ); + + results = propertyProvider(`/*I'm a comment\n \t * /t`); + Assert.ok( + results === null, + "Does not complete in multiline comment after line break and invalid comment end" + ); + + results = propertyProvider(`/*I'm a comment\n \t */t`); + test_has_result(results, "testObject"); + + results = propertyProvider(`/*I'm a comment\n \t */\n\nt`); + test_has_result(results, "testObject"); + + info("Test local expression variables"); + results = propertyProvider("b", { expressionVars: ["a", "b", "c"] }); + test_has_result(results, "b"); + Assert.equal(results.matches.has("a"), false); + Assert.equal(results.matches.has("c"), false); + + info( + "Test that local expression variables are not included when accessing an object properties" + ); + results = propertyProvider("testObject.prop", { + expressionVars: ["propLocal"], + }); + Assert.equal(results.matches.has("propLocal"), false); + test_has_result(results, "propA"); + + results = propertyProvider("testObject['prop", { + expressionVars: ["propLocal"], + }); + test_has_result(results, "'propA'"); + Assert.equal(results.matches.has("propLocal"), false); + + info("Test that expression with optional chaining operator are completed"); + results = propertyProvider("testObject?.prop"); + test_has_result(results, "propA"); + + results = propertyProvider("testObject?.propA[0]?.propB?.to"); + test_has_result(results, "toString"); + + results = propertyProvider("testObject?.propA?.[0]?.propB?.to"); + test_has_result(results, "toString"); + + results = propertyProvider( + "testObject ?. propA[0] ?. propB ?. to" + ); + test_has_result(results, "toString"); + + results = propertyProvider("testObject?.[prop"); + test_has_result(results, '"propA"'); + + results = propertyProvider(`testObject?.["prop`); + test_has_result(results, '"propA"'); + + results = propertyProvider(`testObject?.['prop`); + test_has_result(results, `'propA'`); + + results = propertyProvider(`testObject?.["propA"]?.[0]?.["propB"]?.["to`); + test_has_result(results, `"toString"`); + + results = propertyProvider( + `testObject ?. ["propA"] ?. [0] ?. ["propB"] ?. ['to` + ); + test_has_result(results, "'toString'"); + + results = propertyProvider("[1,2,3]?."); + test_has_result(results, "indexOf"); + + results = propertyProvider("'foo'?."); + test_has_result(results, "charAt"); + + results = propertyProvider("1?."); + test_has_result(results, "toFixed"); + + // check this doesn't throw since `propC` is not defined. + results = propertyProvider("testObject?.propC?.this?.does?.not?.exist?.d"); + + // check that ternary operator isn't mistaken for optional chaining + results = propertyProvider(`true?.3.to`); + test_has_result(results, `toExponential`); + + results = propertyProvider(`true?.3?.to`); + test_has_result(results, `toExponential`); + + // Test more ternary + results = propertyProvider(`true?t`); + test_has_result(results, `testObject`); + + results = propertyProvider(`true??t`); + test_has_result(results, `testObject`); + + results = propertyProvider(`true?/* comment */t`); + test_has_result(results, `testObject`); + + results = propertyProvider(`true?<t`); + test_has_no_results(results); + + // Test autocompletion on debugger statement does not throw + results = propertyProvider(`debugger.`); + Assert.ok(results === null, "Does not complete a debugger keyword"); + + // Test autocompletion on Proxies + // proxy does not get autocompletion result from prototype defined in `getPrototypeOf` + test_has_no_results(propertyProvider(`testArrayPrototypeProxy.filte`)); + results = propertyProvider(`testArrayPrototypeProxy.`); + // it does get the own property + test_has_result(results, `world`); + // as well as method from the actual proxy target prototype + test_has_result(results, `hasOwnProperty`); + + results = propertyProvider(`testSelfPrototypeProxy.`); + test_has_result(results, `hello`); + test_has_result(results, `hasOwnProperty`); +} + +/** + * A helper that ensures an empty array of results were found. + * @param Object results + * The results returned by JSPropertyProvider. + */ +function test_has_no_results(results) { + Assert.notEqual(results, null); + Assert.equal(results.matches.size, 0); +} +/** + * A helper that ensures (required) results were found. + * @param Object results + * The results returned by JSPropertyProvider. + * @param String requiredSuggestion + * A suggestion that must be found from the results. + */ +function test_has_result(results, requiredSuggestion) { + Assert.notEqual(results, null); + Assert.ok(results.matches.size > 0); + Assert.ok( + results.matches.has(requiredSuggestion), + `<${requiredSuggestion}> found in ${[...results.matches.values()].join( + " - " + )}` + ); +} + +/** + * A helper that ensures results are the expected ones. + * @param Object results + * The results returned by JSPropertyProvider. + * @param Array expectedMatches + * An array of the properties that should be returned by JsPropertyProvider. + */ +function test_has_exact_results(results, expectedMatches) { + Assert.deepEqual([...results.matches], expectedMatches); +} diff --git a/devtools/shared/webconsole/test/xpcshell/xpcshell.ini b/devtools/shared/webconsole/test/xpcshell/xpcshell.ini new file mode 100644 index 0000000000..a0d7e75ad1 --- /dev/null +++ b/devtools/shared/webconsole/test/xpcshell/xpcshell.ini @@ -0,0 +1,9 @@ +[DEFAULT] +tags = devtools +head = head.js +firefox-appdir = browser +skip-if = toolkit == 'android' +support-files = + +[test_analyze_input_string.js] +[test_js_property_provider.js] |