Path: blob/trunk/javascript/selenium-webdriver/test/chrome/devtools_test.js
2885 views
// Licensed to the Software Freedom Conservancy (SFC) under one1// or more contributor license agreements. See the NOTICE file2// distributed with this work for additional information3// regarding copyright ownership. The SFC licenses this file4// to you under the Apache License, Version 2.0 (the5// "License"); you may not use this file except in compliance6// with the License. You may obtain a copy of the License at7//8// http://www.apache.org/licenses/LICENSE-2.09//10// Unless required by applicable law or agreed to in writing,11// software distributed under the License is distributed on an12// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY13// KIND, either express or implied. See the License for the14// specific language governing permissions and limitations15// under the License.1617'use strict'1819const assert = require('node:assert')20const fs = require('node:fs')21const path = require('node:path')2223const chrome = require('selenium-webdriver/chrome')24const by = require('selenium-webdriver/lib/by')25const error = require('selenium-webdriver/lib/error')26const fileServer = require('../../lib/test/fileserver')27const io = require('selenium-webdriver/io')28const test = require('../../lib/test')29const until = require('selenium-webdriver/lib/until')3031test.suite(32function (env) {33let driver3435beforeEach(async function () {36let options = env.builder().getChromeOptions() || new chrome.Options()37options.addArguments('--headless')38driver = await env.builder().setChromeOptions(options).build()39})40afterEach(async () => await driver.quit())4142it('can send commands to devtools', async function () {43await driver.get(test.Pages.ajaxyPage)44assert.strictEqual(await driver.getCurrentUrl(), test.Pages.ajaxyPage)4546await driver.sendDevToolsCommand('Page.navigate', {47url: test.Pages.echoPage,48})49assert.strictEqual(await driver.getCurrentUrl(), test.Pages.echoPage)50})5152it('can send commands to devtools and get return', async function () {53await driver.get(test.Pages.ajaxyPage)54assert.strictEqual(await driver.getCurrentUrl(), test.Pages.ajaxyPage)5556await driver.get(test.Pages.echoPage)57assert.strictEqual(await driver.getCurrentUrl(), test.Pages.echoPage)5859let history = await driver.sendAndGetDevToolsCommand('Page.getNavigationHistory')60assert(history)61assert(history.currentIndex >= 2)62assert.strictEqual(history.entries[history.currentIndex].url, test.Pages.echoPage)63assert.strictEqual(history.entries[history.currentIndex - 1].url, test.Pages.ajaxyPage)64})6566it('sends Page.enable command using devtools', async function () {67const cdpConnection = await driver.createCDPConnection('page')68cdpConnection.execute('Page.enable', {}, function (_res, err) {69assert(!err)70})71})7273it('sends Network and Page command using devtools', async function () {74const cdpConnection = await driver.createCDPConnection('page')75cdpConnection.execute('Network.enable', {}, function (_res, err) {76assert(!err)77})7879cdpConnection.execute('Page.navigate', { url: 'chrome://newtab/' }, function (_res, err) {80assert(!err)81})82})8384describe('JS CDP events', function () {85it('calls the event listener for console.log', async function () {86const cdpConnection = await driver.createCDPConnection('page')87await driver.onLogEvent(cdpConnection, function (event) {88assert.strictEqual(event['args'][0]['value'], 'here')89})90await driver.executeScript('console.log("here")')91})9293it('calls the event listener for js exceptions', async function () {94const cdpConnection = await driver.createCDPConnection('page')95await driver.onLogException(cdpConnection, function (event) {96assert.strictEqual(event['exceptionDetails']['stackTrace']['callFrames'][0]['functionName'], 'onmouseover')97})98await driver.get(test.Pages.javascriptPage)99let element = driver.findElement({ id: 'throwing-mouseover' })100await element.click()101})102})103104describe('JS DOM events', function () {105it('calls the event listener on dom mutations', async function () {106const cdpConnection = await driver.createCDPConnection('page')107await driver.logMutationEvents(cdpConnection, function (event) {108assert.strictEqual(event['attribute_name'], 'style')109assert.strictEqual(event['current_value'], '')110assert.strictEqual(event['old_value'], 'display:none;')111})112113await driver.get(fileServer.Pages.dynamicPage)114115let element = driver.findElement({ id: 'reveal' })116await element.click()117let revealed = driver.findElement({ id: 'revealed' })118await driver.wait(until.elementIsVisible(revealed), 5000)119})120})121122describe('Basic Auth Injection', function () {123it('denies entry if username and password do not match', async function () {124const pageCdpConnection = await driver.createCDPConnection('page')125126await driver.register('random', 'random', pageCdpConnection)127await driver.get(fileServer.Pages.basicAuth)128let source = await driver.getPageSource()129console.log(source)130assert.strictEqual(source.includes('Access granted!'), false, source)131})132})133134describe('Basic Auth Injection', function () {135it('grants access if username and password are a match', async function () {136const pageCdpConnection = await driver.createCDPConnection('page')137138await driver.register('genie', 'bottle', pageCdpConnection)139await driver.get(fileServer.Pages.basicAuth)140let source = await driver.getPageSource()141assert.strictEqual(source.includes('Access granted!'), true)142})143})144145describe('setDownloadPath', function () {146it('can enable downloads in headless mode', async function () {147const dir = await io.tmpDir()148await driver.setDownloadPath(dir)149150const url = fileServer.whereIs('/data/chrome/download.bin')151await driver.get(`data:text/html,<!DOCTYPE html>152<div><a download="" href="${url}">Go!</a></div>`)153154await driver.findElement({ css: 'a' }).click()155156const downloadPath = path.join(dir, 'download.bin')157await driver.wait(() => io.exists(downloadPath), 5000)158159const goldenPath = path.join(__dirname, '../../lib/test/data/chrome/download.bin')160assert.strictEqual(fs.readFileSync(downloadPath, 'binary'), fs.readFileSync(goldenPath, 'binary'))161})162163it('throws if path is not a directory', async function () {164await assertInvalidArgumentError(() => driver.setDownloadPath())165await assertInvalidArgumentError(() => driver.setDownloadPath(null))166await assertInvalidArgumentError(() => driver.setDownloadPath(''))167await assertInvalidArgumentError(() => driver.setDownloadPath(1234))168169const file = await io.tmpFile()170await assertInvalidArgumentError(() => driver.setDownloadPath(file))171172async function assertInvalidArgumentError(fn) {173try {174await fn()175return Promise.reject(Error('should have failed'))176} catch (err) {177if (err instanceof error.InvalidArgumentError) {178return179}180throw err181}182}183})184})185186describe('Script pinning', function () {187it('allows to pin script', async function () {188await driver.get(fileServer.Pages.xhtmlTestPage)189190let script = await driver.pinScript('return document.title;')191192const result = await driver.executeScript(script)193194assert.strictEqual(result, 'XHTML Test Page')195})196197it('ensures pinned script is available on new pages', async function () {198await driver.get(fileServer.Pages.xhtmlTestPage)199await driver.createCDPConnection('page')200201let script = await driver.pinScript('return document.title;')202await driver.get(fileServer.Pages.formPage)203204const result = await driver.executeScript(script)205206assert.strictEqual(result, 'We Leave From Here')207})208209it('allows to unpin script', async function () {210let script = await driver.pinScript('return document.title;')211await driver.unpinScript(script)212213await assertJSError(() => driver.executeScript(script))214215async function assertJSError(fn) {216try {217await fn()218return Promise.reject(Error('should have failed'))219} catch (err) {220if (err instanceof error.JavascriptError) {221return222}223throw err224}225}226})227228it('ensures unpinned scripts are not available on new pages', async function () {229await driver.createCDPConnection('page')230231let script = await driver.pinScript('return document.title;')232await driver.unpinScript(script)233234await driver.get(fileServer.Pages.formPage)235236await assertJSError(() => driver.executeScript(script))237238async function assertJSError(fn) {239try {240await fn()241return Promise.reject(Error('should have failed'))242} catch (err) {243if (err instanceof error.JavascriptError) {244return245}246throw err247}248}249})250251it('handles arguments in pinned script', async function () {252await driver.get(fileServer.Pages.xhtmlTestPage)253await driver.createCDPConnection('page')254255let script = await driver.pinScript('return arguments;')256let element = await driver.findElement(by.By.id('id1'))257258const result = await driver.executeScript(script, 1, true, element)259260assert.deepEqual(result, [1, true, element])261})262263it('supports async pinned scripts', async function () {264let script = await driver.pinScript('arguments[0]()')265await assertAsyncScriptPinned(() => driver.executeAsyncScript(script))266267async function assertAsyncScriptPinned(fn) {268await fn()269}270})271})272},273{ browsers: ['chrome'] },274)275276277