Cada navegador tem capacidades e características únicas.
This is the multi-page printable view of this section. Click here to print.
Navegadores suportados
- 1: Funcionalidade específica do Chrome
- 2: Funcionalidade específica do Edge
- 3: Funcionalidade específica do Firefox
- 4: Funcionalidade específica do IE
- 5: Funcionalidade específica do Safari
1 - Funcionalidade específica do Chrome
Por omissão, Selenium 4 é compatível com Chrome v75 e superiores. Note que a versão (maior) do navegador e do chromedriver devem ser idênticas.
Opções
Capacidades comuns a todos os navegadores estão descritas na página Opções.
Capacidades únicas ao Chrome podem ser encontradas na página da Google para Capacidades e & ChromeOptions
Este é um exemplo de como iniciar uma sessão Chrome com um conjunto de opções básicas:
ChromeOptions options = getDefaultChromeOptions();
driver = new ChromeDriver(options);
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class ChromeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
ChromeOptions options = getDefaultChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = getDefaultChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void setBrowserLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBinary(getChromeLocation());
driver = new ChromeDriver(options);
}
@Test
public void extensionOptions() {
ChromeOptions options = getDefaultChromeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
ChromeOptions options = getDefaultChromeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void loggingPreferences() {
ChromeOptions options = getDefaultChromeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
ChromeDriverService service =
new ChromeDriverService.Builder().withLogFile(logLocation).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
ChromeDriverService service =
new ChromeDriverService.Builder().withLogOutput(System.out).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
ChromeDriverService service =
new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getChromeLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermission() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new ChromeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((ChromeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((ChromeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
ChromeDriver driver = new ChromeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
options = get_default_chrome_options()
driver = webdriver.Chrome(options=options)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_chrome_options()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_args():
options = get_default_chrome_options()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(chrome_bin):
options = get_default_chrome_options()
options.binary_location = chrome_bin
driver = webdriver.Chrome(options=options)
driver.quit()
def test_add_extension():
options = get_default_chrome_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_chrome_options()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_chrome_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.ChromeService(log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as fp:
assert "Starting ChromeDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.ChromeService(log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert "Starting ChromeDriver" in out
driver.quit()
def test_log_level(capfd):
service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert '[DEBUG]' in err
driver.quit()
def test_log_features(log_path):
service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(capfd):
service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
out, err = capfd.readouterr()
assert expected in err
driver.quit()
def test_set_network_conditions():
driver = webdriver.Chrome()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Chrome()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Chrome()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_chrome_options():
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
return options
var options = new ChromeOptions();
driver = new ChromeDriver(options);
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class ChromeTest
{
private ChromeDriver driver;
private string _logLocation;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new ChromeOptions();
driver = new ChromeDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new ChromeOptions();
options.AddArgument("--start-maximized");
driver = new ChromeDriver(options);
}
[TestMethod]
public void SetBrowserLocation()
{
var options = new ChromeOptions();
options.BinaryLocation = GetChromeLocation();
driver = new ChromeDriver(options);
}
[TestMethod]
public void InstallExtension()
{
var options = new ChromeOptions();
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");
options.AddExtension(extensionFilePath);
driver = new ChromeDriver(options);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void ExcludeSwitch()
{
var options = new ChromeOptions();
options.AddExcludedArgument("disable-popup-blocking");
driver = new ChromeDriver(options);
}
[TestMethod]
public void LogsToFile()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting ChromeDriver")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = ChromeDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new ChromeDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsLevel()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
// service.LogLevel = ChromiumDriverLogLevel.Debug
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
}
[TestMethod]
[Ignore("Not implemented")]
public void ConfigureDriverLogs()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.EnableAppendLog = true;
// service.readableTimeStamp = true;
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
}
[TestMethod]
public void DisableBuildCheck()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.DisableBuildCheck = true;
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private static string GetChromeLocation()
{
var options = new ChromeOptions
{
BrowserVersion = "stable"
};
return new DriverFinder(options).GetBrowserPath();
}
}
}
options = Selenium::WebDriver::Options.chrome
@driver = Selenium::WebDriver.for :chrome, options: options
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Options' do
let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.chrome
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.chrome
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.chrome
options.binary = chrome_location
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.chrome
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.chrome
options.detach = true
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.chrome
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :chrome, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('chromedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.chrome
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :chrome, service: service
}.to output(/Starting ChromeDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.chrome(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :chrome, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :chrome
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :chrome
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
service = Selenium::WebDriver::Service.chrome
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['CHROMEDRIVER_BIN'] = finder.driver_path
ENV['CHROME_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
const Options = new Chrome.Options();
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(Options)
.build();
Show full example
const Chrome = require('selenium-webdriver/chrome');
const { Browser, Builder } = require("selenium-webdriver");
const options = new Chrome.Options();
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.addArguments('--headless=new'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('exclude switches', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.excludeSwitches('enable-automation'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Keep browser open - set detach to true ', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.detachDriver(true))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
// As tests runs in ci, quitting the driver instance to avoid any failures
await driver.quit();
});
xit('Start browser from specified location ', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Basic Chrome test', async function () {
const Options = new Chrome.Options();
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(Options)
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Add Extension', async function () {
const options = new Chrome.Options();
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
});
Alguns exemplos de uso com capacidades diferentes:
Argumentos
The args
parameter is for a list of command line switches to be used when starting the browser.
There are two excellent resources for investigating these arguments:
Commonly used args include --start-maximized
, --headless=new
and --user-data-dir=...
Add an argument to options:
options.addArguments("--start-maximized");
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class ChromeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
ChromeOptions options = getDefaultChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = getDefaultChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void setBrowserLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBinary(getChromeLocation());
driver = new ChromeDriver(options);
}
@Test
public void extensionOptions() {
ChromeOptions options = getDefaultChromeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
ChromeOptions options = getDefaultChromeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void loggingPreferences() {
ChromeOptions options = getDefaultChromeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
ChromeDriverService service =
new ChromeDriverService.Builder().withLogFile(logLocation).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
ChromeDriverService service =
new ChromeDriverService.Builder().withLogOutput(System.out).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
ChromeDriverService service =
new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getChromeLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermission() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new ChromeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((ChromeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((ChromeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
ChromeDriver driver = new ChromeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
options.add_argument("--start-maximized")
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_chrome_options()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_args():
options = get_default_chrome_options()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(chrome_bin):
options = get_default_chrome_options()
options.binary_location = chrome_bin
driver = webdriver.Chrome(options=options)
driver.quit()
def test_add_extension():
options = get_default_chrome_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_chrome_options()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_chrome_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.ChromeService(log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as fp:
assert "Starting ChromeDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.ChromeService(log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert "Starting ChromeDriver" in out
driver.quit()
def test_log_level(capfd):
service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert '[DEBUG]' in err
driver.quit()
def test_log_features(log_path):
service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(capfd):
service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
out, err = capfd.readouterr()
assert expected in err
driver.quit()
def test_set_network_conditions():
driver = webdriver.Chrome()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Chrome()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Chrome()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_chrome_options():
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
return options
options.AddArgument("--start-maximized");
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class ChromeTest
{
private ChromeDriver driver;
private string _logLocation;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new ChromeOptions();
driver = new ChromeDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new ChromeOptions();
options.AddArgument("--start-maximized");
driver = new ChromeDriver(options);
}
[TestMethod]
public void SetBrowserLocation()
{
var options = new ChromeOptions();
options.BinaryLocation = GetChromeLocation();
driver = new ChromeDriver(options);
}
[TestMethod]
public void InstallExtension()
{
var options = new ChromeOptions();
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");
options.AddExtension(extensionFilePath);
driver = new ChromeDriver(options);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void ExcludeSwitch()
{
var options = new ChromeOptions();
options.AddExcludedArgument("disable-popup-blocking");
driver = new ChromeDriver(options);
}
[TestMethod]
public void LogsToFile()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting ChromeDriver")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = ChromeDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new ChromeDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsLevel()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
// service.LogLevel = ChromiumDriverLogLevel.Debug
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
}
[TestMethod]
[Ignore("Not implemented")]
public void ConfigureDriverLogs()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.EnableAppendLog = true;
// service.readableTimeStamp = true;
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
}
[TestMethod]
public void DisableBuildCheck()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.DisableBuildCheck = true;
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private static string GetChromeLocation()
{
var options = new ChromeOptions
{
BrowserVersion = "stable"
};
return new DriverFinder(options).GetBrowserPath();
}
}
}
options.args << '--start-maximized'
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Options' do
let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.chrome
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.chrome
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.chrome
options.binary = chrome_location
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.chrome
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.chrome
options.detach = true
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.chrome
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :chrome, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('chromedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.chrome
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :chrome, service: service
}.to output(/Starting ChromeDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.chrome(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :chrome, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :chrome
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :chrome
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
service = Selenium::WebDriver::Service.chrome
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['CHROMEDRIVER_BIN'] = finder.driver_path
ENV['CHROME_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.addArguments('--headless=new'))
.build();
Show full example
const Chrome = require('selenium-webdriver/chrome');
const { Browser, Builder } = require("selenium-webdriver");
const options = new Chrome.Options();
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.addArguments('--headless=new'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('exclude switches', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.excludeSwitches('enable-automation'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Keep browser open - set detach to true ', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.detachDriver(true))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
// As tests runs in ci, quitting the driver instance to avoid any failures
await driver.quit();
});
xit('Start browser from specified location ', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Basic Chrome test', async function () {
const Options = new Chrome.Options();
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(Options)
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Add Extension', async function () {
const options = new Chrome.Options();
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
});
Iniciar navegador numa localização específica
Adicionar uma localização:
options.setBinary(getChromeLocation());
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class ChromeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
ChromeOptions options = getDefaultChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = getDefaultChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void setBrowserLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBinary(getChromeLocation());
driver = new ChromeDriver(options);
}
@Test
public void extensionOptions() {
ChromeOptions options = getDefaultChromeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
ChromeOptions options = getDefaultChromeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void loggingPreferences() {
ChromeOptions options = getDefaultChromeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
ChromeDriverService service =
new ChromeDriverService.Builder().withLogFile(logLocation).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
ChromeDriverService service =
new ChromeDriverService.Builder().withLogOutput(System.out).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
ChromeDriverService service =
new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getChromeLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermission() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new ChromeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((ChromeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((ChromeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
ChromeDriver driver = new ChromeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
options.binary_location = chrome_bin
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_chrome_options()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_args():
options = get_default_chrome_options()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(chrome_bin):
options = get_default_chrome_options()
options.binary_location = chrome_bin
driver = webdriver.Chrome(options=options)
driver.quit()
def test_add_extension():
options = get_default_chrome_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_chrome_options()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_chrome_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.ChromeService(log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as fp:
assert "Starting ChromeDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.ChromeService(log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert "Starting ChromeDriver" in out
driver.quit()
def test_log_level(capfd):
service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert '[DEBUG]' in err
driver.quit()
def test_log_features(log_path):
service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(capfd):
service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
out, err = capfd.readouterr()
assert expected in err
driver.quit()
def test_set_network_conditions():
driver = webdriver.Chrome()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Chrome()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Chrome()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_chrome_options():
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
return options
options.BinaryLocation = GetChromeLocation();
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class ChromeTest
{
private ChromeDriver driver;
private string _logLocation;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new ChromeOptions();
driver = new ChromeDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new ChromeOptions();
options.AddArgument("--start-maximized");
driver = new ChromeDriver(options);
}
[TestMethod]
public void SetBrowserLocation()
{
var options = new ChromeOptions();
options.BinaryLocation = GetChromeLocation();
driver = new ChromeDriver(options);
}
[TestMethod]
public void InstallExtension()
{
var options = new ChromeOptions();
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");
options.AddExtension(extensionFilePath);
driver = new ChromeDriver(options);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void ExcludeSwitch()
{
var options = new ChromeOptions();
options.AddExcludedArgument("disable-popup-blocking");
driver = new ChromeDriver(options);
}
[TestMethod]
public void LogsToFile()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting ChromeDriver")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = ChromeDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new ChromeDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsLevel()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
// service.LogLevel = ChromiumDriverLogLevel.Debug
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
}
[TestMethod]
[Ignore("Not implemented")]
public void ConfigureDriverLogs()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.EnableAppendLog = true;
// service.readableTimeStamp = true;
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
}
[TestMethod]
public void DisableBuildCheck()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.DisableBuildCheck = true;
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private static string GetChromeLocation()
{
var options = new ChromeOptions
{
BrowserVersion = "stable"
};
return new DriverFinder(options).GetBrowserPath();
}
}
}
options.binary = chrome_location
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Options' do
let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.chrome
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.chrome
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.chrome
options.binary = chrome_location
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.chrome
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.chrome
options.detach = true
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.chrome
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :chrome, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('chromedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.chrome
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :chrome, service: service
}.to output(/Starting ChromeDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.chrome(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :chrome, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :chrome
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :chrome
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
service = Selenium::WebDriver::Service.chrome
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['CHROMEDRIVER_BIN'] = finder.driver_path
ENV['CHROME_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
.build();
Show full example
const Chrome = require('selenium-webdriver/chrome');
const { Browser, Builder } = require("selenium-webdriver");
const options = new Chrome.Options();
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.addArguments('--headless=new'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('exclude switches', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.excludeSwitches('enable-automation'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Keep browser open - set detach to true ', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.detachDriver(true))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
// As tests runs in ci, quitting the driver instance to avoid any failures
await driver.quit();
});
xit('Start browser from specified location ', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Basic Chrome test', async function () {
const Options = new Chrome.Options();
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(Options)
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Add Extension', async function () {
const options = new Chrome.Options();
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
});
Adicionar extensões
O parametro extensions
aceita ficheiros crx
The extensions
parameter accepts crx files. As for unpacked directories,
please use the load-extension
argument instead, as mentioned in
this post.
Adicionar uma extensão:
options.addExtensions(extensionFilePath);
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class ChromeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
ChromeOptions options = getDefaultChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = getDefaultChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void setBrowserLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBinary(getChromeLocation());
driver = new ChromeDriver(options);
}
@Test
public void extensionOptions() {
ChromeOptions options = getDefaultChromeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
ChromeOptions options = getDefaultChromeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void loggingPreferences() {
ChromeOptions options = getDefaultChromeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
ChromeDriverService service =
new ChromeDriverService.Builder().withLogFile(logLocation).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
ChromeDriverService service =
new ChromeDriverService.Builder().withLogOutput(System.out).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
ChromeDriverService service =
new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getChromeLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermission() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new ChromeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((ChromeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((ChromeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
ChromeDriver driver = new ChromeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
options.add_extension(extension_file_path)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_chrome_options()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_args():
options = get_default_chrome_options()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(chrome_bin):
options = get_default_chrome_options()
options.binary_location = chrome_bin
driver = webdriver.Chrome(options=options)
driver.quit()
def test_add_extension():
options = get_default_chrome_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_chrome_options()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_chrome_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.ChromeService(log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as fp:
assert "Starting ChromeDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.ChromeService(log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert "Starting ChromeDriver" in out
driver.quit()
def test_log_level(capfd):
service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert '[DEBUG]' in err
driver.quit()
def test_log_features(log_path):
service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(capfd):
service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
out, err = capfd.readouterr()
assert expected in err
driver.quit()
def test_set_network_conditions():
driver = webdriver.Chrome()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Chrome()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Chrome()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_chrome_options():
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
return options
options.AddExtension(extensionFilePath);
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class ChromeTest
{
private ChromeDriver driver;
private string _logLocation;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new ChromeOptions();
driver = new ChromeDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new ChromeOptions();
options.AddArgument("--start-maximized");
driver = new ChromeDriver(options);
}
[TestMethod]
public void SetBrowserLocation()
{
var options = new ChromeOptions();
options.BinaryLocation = GetChromeLocation();
driver = new ChromeDriver(options);
}
[TestMethod]
public void InstallExtension()
{
var options = new ChromeOptions();
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");
options.AddExtension(extensionFilePath);
driver = new ChromeDriver(options);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void ExcludeSwitch()
{
var options = new ChromeOptions();
options.AddExcludedArgument("disable-popup-blocking");
driver = new ChromeDriver(options);
}
[TestMethod]
public void LogsToFile()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting ChromeDriver")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = ChromeDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new ChromeDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsLevel()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
// service.LogLevel = ChromiumDriverLogLevel.Debug
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
}
[TestMethod]
[Ignore("Not implemented")]
public void ConfigureDriverLogs()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.EnableAppendLog = true;
// service.readableTimeStamp = true;
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
}
[TestMethod]
public void DisableBuildCheck()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.DisableBuildCheck = true;
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private static string GetChromeLocation()
{
var options = new ChromeOptions
{
BrowserVersion = "stable"
};
return new DriverFinder(options).GetBrowserPath();
}
}
}
options.add_extension(extension_file_path)
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Options' do
let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.chrome
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.chrome
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.chrome
options.binary = chrome_location
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.chrome
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.chrome
options.detach = true
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.chrome
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :chrome, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('chromedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.chrome
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :chrome, service: service
}.to output(/Starting ChromeDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.chrome(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :chrome, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :chrome
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :chrome
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
service = Selenium::WebDriver::Service.chrome
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['CHROMEDRIVER_BIN'] = finder.driver_path
ENV['CHROME_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
const options = new Chrome.Options();
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
.build();
Show full example
const Chrome = require('selenium-webdriver/chrome');
const { Browser, Builder } = require("selenium-webdriver");
const options = new Chrome.Options();
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.addArguments('--headless=new'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('exclude switches', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.excludeSwitches('enable-automation'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Keep browser open - set detach to true ', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.detachDriver(true))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
// As tests runs in ci, quitting the driver instance to avoid any failures
await driver.quit();
});
xit('Start browser from specified location ', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Basic Chrome test', async function () {
const Options = new Chrome.Options();
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(Options)
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Add Extension', async function () {
const options = new Chrome.Options();
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
});
Manter o navegador aberto
Ao definir o parametro detach
para true, irá manter o navegador aberto mesmo depois do driver fechar.
Adicionar detach:
Note: This is already the default behavior in Java.
options.add_experimental_option("detach", True)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_chrome_options()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_args():
options = get_default_chrome_options()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(chrome_bin):
options = get_default_chrome_options()
options.binary_location = chrome_bin
driver = webdriver.Chrome(options=options)
driver.quit()
def test_add_extension():
options = get_default_chrome_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_chrome_options()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_chrome_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.ChromeService(log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as fp:
assert "Starting ChromeDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.ChromeService(log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert "Starting ChromeDriver" in out
driver.quit()
def test_log_level(capfd):
service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert '[DEBUG]' in err
driver.quit()
def test_log_features(log_path):
service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(capfd):
service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
out, err = capfd.readouterr()
assert expected in err
driver.quit()
def test_set_network_conditions():
driver = webdriver.Chrome()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Chrome()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Chrome()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_chrome_options():
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
return options
Note: This is already the default behavior in .NET.
options.detach = true
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Options' do
let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.chrome
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.chrome
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.chrome
options.binary = chrome_location
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.chrome
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.chrome
options.detach = true
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.chrome
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :chrome, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('chromedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.chrome
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :chrome, service: service
}.to output(/Starting ChromeDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.chrome(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :chrome, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :chrome
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :chrome
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
service = Selenium::WebDriver::Service.chrome
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['CHROMEDRIVER_BIN'] = finder.driver_path
ENV['CHROME_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.detachDriver(true))
.build();
Show full example
const Chrome = require('selenium-webdriver/chrome');
const { Browser, Builder } = require("selenium-webdriver");
const options = new Chrome.Options();
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.addArguments('--headless=new'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('exclude switches', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.excludeSwitches('enable-automation'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Keep browser open - set detach to true ', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.detachDriver(true))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
// As tests runs in ci, quitting the driver instance to avoid any failures
await driver.quit();
});
xit('Start browser from specified location ', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Basic Chrome test', async function () {
const Options = new Chrome.Options();
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(Options)
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Add Extension', async function () {
const options = new Chrome.Options();
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
});
Excluindo parametros
Chrome adiciona vários parametros, se não os pretende adicionar, passe-os em excludeSwitches
.
Um exemplo comum é voltar a activar o bloqueador de popups. A full list of default arguments can be parsed from the Chromium Source Code
Exclua parametros:
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class ChromeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
ChromeOptions options = getDefaultChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = getDefaultChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void setBrowserLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBinary(getChromeLocation());
driver = new ChromeDriver(options);
}
@Test
public void extensionOptions() {
ChromeOptions options = getDefaultChromeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
ChromeOptions options = getDefaultChromeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void loggingPreferences() {
ChromeOptions options = getDefaultChromeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
ChromeDriverService service =
new ChromeDriverService.Builder().withLogFile(logLocation).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
ChromeDriverService service =
new ChromeDriverService.Builder().withLogOutput(System.out).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
ChromeDriverService service =
new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getChromeLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermission() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new ChromeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((ChromeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((ChromeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
ChromeDriver driver = new ChromeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_chrome_options()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_args():
options = get_default_chrome_options()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(chrome_bin):
options = get_default_chrome_options()
options.binary_location = chrome_bin
driver = webdriver.Chrome(options=options)
driver.quit()
def test_add_extension():
options = get_default_chrome_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_chrome_options()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_chrome_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.ChromeService(log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as fp:
assert "Starting ChromeDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.ChromeService(log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert "Starting ChromeDriver" in out
driver.quit()
def test_log_level(capfd):
service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert '[DEBUG]' in err
driver.quit()
def test_log_features(log_path):
service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(capfd):
service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
out, err = capfd.readouterr()
assert expected in err
driver.quit()
def test_set_network_conditions():
driver = webdriver.Chrome()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Chrome()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Chrome()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_chrome_options():
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
return options
options.AddExcludedArgument("disable-popup-blocking");
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class ChromeTest
{
private ChromeDriver driver;
private string _logLocation;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new ChromeOptions();
driver = new ChromeDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new ChromeOptions();
options.AddArgument("--start-maximized");
driver = new ChromeDriver(options);
}
[TestMethod]
public void SetBrowserLocation()
{
var options = new ChromeOptions();
options.BinaryLocation = GetChromeLocation();
driver = new ChromeDriver(options);
}
[TestMethod]
public void InstallExtension()
{
var options = new ChromeOptions();
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");
options.AddExtension(extensionFilePath);
driver = new ChromeDriver(options);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void ExcludeSwitch()
{
var options = new ChromeOptions();
options.AddExcludedArgument("disable-popup-blocking");
driver = new ChromeDriver(options);
}
[TestMethod]
public void LogsToFile()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting ChromeDriver")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = ChromeDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new ChromeDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsLevel()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
// service.LogLevel = ChromiumDriverLogLevel.Debug
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
}
[TestMethod]
[Ignore("Not implemented")]
public void ConfigureDriverLogs()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.EnableAppendLog = true;
// service.readableTimeStamp = true;
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
}
[TestMethod]
public void DisableBuildCheck()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.DisableBuildCheck = true;
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private static string GetChromeLocation()
{
var options = new ChromeOptions
{
BrowserVersion = "stable"
};
return new DriverFinder(options).GetBrowserPath();
}
}
}
options.exclude_switches << 'disable-popup-blocking'
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Options' do
let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.chrome
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.chrome
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.chrome
options.binary = chrome_location
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.chrome
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.chrome
options.detach = true
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.chrome
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :chrome, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('chromedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.chrome
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :chrome, service: service
}.to output(/Starting ChromeDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.chrome(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :chrome, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :chrome
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :chrome
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
service = Selenium::WebDriver::Service.chrome
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['CHROMEDRIVER_BIN'] = finder.driver_path
ENV['CHROME_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.excludeSwitches('enable-automation'))
.build();
Show full example
const Chrome = require('selenium-webdriver/chrome');
const { Browser, Builder } = require("selenium-webdriver");
const options = new Chrome.Options();
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.addArguments('--headless=new'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('exclude switches', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.excludeSwitches('enable-automation'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Keep browser open - set detach to true ', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.detachDriver(true))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
// As tests runs in ci, quitting the driver instance to avoid any failures
await driver.quit();
});
xit('Start browser from specified location ', async function () {
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Basic Chrome test', async function () {
const Options = new Chrome.Options();
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(Options)
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Add Extension', async function () {
const options = new Chrome.Options();
let driver = new Builder()
.forBrowser(Browser.CHROME)
.setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
});
Service
Examples for creating a default Service object, and for setting driver location and port can be found on the Driver Service page.
Log output
Getting driver logs can be helpful for debugging issues. The Service class lets you direct where the logs will go. Logging output is ignored unless the user directs it somewhere.
File output
To change the logging output to save to a specific file:
ChromeDriverService service =
new ChromeDriverService.Builder().withLogFile(logLocation).build();
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class ChromeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
ChromeOptions options = getDefaultChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = getDefaultChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void setBrowserLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBinary(getChromeLocation());
driver = new ChromeDriver(options);
}
@Test
public void extensionOptions() {
ChromeOptions options = getDefaultChromeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
ChromeOptions options = getDefaultChromeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void loggingPreferences() {
ChromeOptions options = getDefaultChromeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
ChromeDriverService service =
new ChromeDriverService.Builder().withLogFile(logLocation).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
ChromeDriverService service =
new ChromeDriverService.Builder().withLogOutput(System.out).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
ChromeDriverService service =
new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getChromeLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermission() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new ChromeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((ChromeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((ChromeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
ChromeDriver driver = new ChromeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
Note: Java also allows setting file output by System Property:
Property key: ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY
Property value: String representing path to log file
service = webdriver.ChromeService(log_output=log_path)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_chrome_options()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_args():
options = get_default_chrome_options()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(chrome_bin):
options = get_default_chrome_options()
options.binary_location = chrome_bin
driver = webdriver.Chrome(options=options)
driver.quit()
def test_add_extension():
options = get_default_chrome_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_chrome_options()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_chrome_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.ChromeService(log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as fp:
assert "Starting ChromeDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.ChromeService(log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert "Starting ChromeDriver" in out
driver.quit()
def test_log_level(capfd):
service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert '[DEBUG]' in err
driver.quit()
def test_log_features(log_path):
service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(capfd):
service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
out, err = capfd.readouterr()
assert expected in err
driver.quit()
def test_set_network_conditions():
driver = webdriver.Chrome()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Chrome()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Chrome()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_chrome_options():
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
return options
service.LogPath = GetLogLocation();
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class ChromeTest
{
private ChromeDriver driver;
private string _logLocation;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new ChromeOptions();
driver = new ChromeDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new ChromeOptions();
options.AddArgument("--start-maximized");
driver = new ChromeDriver(options);
}
[TestMethod]
public void SetBrowserLocation()
{
var options = new ChromeOptions();
options.BinaryLocation = GetChromeLocation();
driver = new ChromeDriver(options);
}
[TestMethod]
public void InstallExtension()
{
var options = new ChromeOptions();
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");
options.AddExtension(extensionFilePath);
driver = new ChromeDriver(options);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void ExcludeSwitch()
{
var options = new ChromeOptions();
options.AddExcludedArgument("disable-popup-blocking");
driver = new ChromeDriver(options);
}
[TestMethod]
public void LogsToFile()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting ChromeDriver")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = ChromeDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new ChromeDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsLevel()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
// service.LogLevel = ChromiumDriverLogLevel.Debug
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
}
[TestMethod]
[Ignore("Not implemented")]
public void ConfigureDriverLogs()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.EnableAppendLog = true;
// service.readableTimeStamp = true;
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
}
[TestMethod]
public void DisableBuildCheck()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.DisableBuildCheck = true;
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private static string GetChromeLocation()
{
var options = new ChromeOptions
{
BrowserVersion = "stable"
};
return new DriverFinder(options).GetBrowserPath();
}
}
}
service.log = file_name
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Options' do
let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.chrome
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.chrome
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.chrome
options.binary = chrome_location
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.chrome
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.chrome
options.detach = true
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.chrome
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :chrome, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('chromedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.chrome
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :chrome, service: service
}.to output(/Starting ChromeDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.chrome(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :chrome, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :chrome
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :chrome
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
service = Selenium::WebDriver::Service.chrome
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['CHROMEDRIVER_BIN'] = finder.driver_path
ENV['CHROME_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
Console output
To change the logging output to display in the console as STDOUT:
ChromeDriverService service =
new ChromeDriverService.Builder().withLogOutput(System.out).build();
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class ChromeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
ChromeOptions options = getDefaultChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = getDefaultChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void setBrowserLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBinary(getChromeLocation());
driver = new ChromeDriver(options);
}
@Test
public void extensionOptions() {
ChromeOptions options = getDefaultChromeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
ChromeOptions options = getDefaultChromeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void loggingPreferences() {
ChromeOptions options = getDefaultChromeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
ChromeDriverService service =
new ChromeDriverService.Builder().withLogFile(logLocation).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
ChromeDriverService service =
new ChromeDriverService.Builder().withLogOutput(System.out).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
ChromeDriverService service =
new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getChromeLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermission() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new ChromeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((ChromeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((ChromeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
ChromeDriver driver = new ChromeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
Note: Java also allows setting console output by System Property;
Property key: ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY
Property value: DriverService.LOG_STDOUT
or DriverService.LOG_STDERR
service = webdriver.ChromeService(log_output=subprocess.STDOUT)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_chrome_options()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_args():
options = get_default_chrome_options()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(chrome_bin):
options = get_default_chrome_options()
options.binary_location = chrome_bin
driver = webdriver.Chrome(options=options)
driver.quit()
def test_add_extension():
options = get_default_chrome_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_chrome_options()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_chrome_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.ChromeService(log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as fp:
assert "Starting ChromeDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.ChromeService(log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert "Starting ChromeDriver" in out
driver.quit()
def test_log_level(capfd):
service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert '[DEBUG]' in err
driver.quit()
def test_log_features(log_path):
service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(capfd):
service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
out, err = capfd.readouterr()
assert expected in err
driver.quit()
def test_set_network_conditions():
driver = webdriver.Chrome()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Chrome()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Chrome()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_chrome_options():
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
return options
$stdout
and $stderr
are both valid values
service.log = $stdout
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Options' do
let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.chrome
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.chrome
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.chrome
options.binary = chrome_location
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.chrome
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.chrome
options.detach = true
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.chrome
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :chrome, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('chromedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.chrome
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :chrome, service: service
}.to output(/Starting ChromeDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.chrome(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :chrome, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :chrome
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :chrome
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
service = Selenium::WebDriver::Service.chrome
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['CHROMEDRIVER_BIN'] = finder.driver_path
ENV['CHROME_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
Log level
There are 6 available log levels: ALL
, DEBUG
, INFO
, WARNING
, SEVERE
, and OFF
.
Note that --verbose
is equivalent to --log-level=ALL
and --silent
is equivalent to --log-level=OFF
,
so this example is just setting the log level generically:
ChromeDriverService service =
new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class ChromeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
ChromeOptions options = getDefaultChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = getDefaultChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void setBrowserLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBinary(getChromeLocation());
driver = new ChromeDriver(options);
}
@Test
public void extensionOptions() {
ChromeOptions options = getDefaultChromeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
ChromeOptions options = getDefaultChromeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void loggingPreferences() {
ChromeOptions options = getDefaultChromeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
ChromeDriverService service =
new ChromeDriverService.Builder().withLogFile(logLocation).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
ChromeDriverService service =
new ChromeDriverService.Builder().withLogOutput(System.out).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
ChromeDriverService service =
new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getChromeLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermission() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new ChromeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((ChromeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((ChromeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
ChromeDriver driver = new ChromeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
Note: Java also allows setting log level by System Property:
Property key: ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY
Property value: String representation of ChromiumDriverLogLevel
enum
service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_chrome_options()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_args():
options = get_default_chrome_options()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(chrome_bin):
options = get_default_chrome_options()
options.binary_location = chrome_bin
driver = webdriver.Chrome(options=options)
driver.quit()
def test_add_extension():
options = get_default_chrome_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_chrome_options()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_chrome_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.ChromeService(log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as fp:
assert "Starting ChromeDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.ChromeService(log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert "Starting ChromeDriver" in out
driver.quit()
def test_log_level(capfd):
service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert '[DEBUG]' in err
driver.quit()
def test_log_features(log_path):
service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(capfd):
service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
out, err = capfd.readouterr()
assert expected in err
driver.quit()
def test_set_network_conditions():
driver = webdriver.Chrome()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Chrome()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Chrome()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_chrome_options():
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
return options
service.args << '--log-level=DEBUG'
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Options' do
let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.chrome
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.chrome
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.chrome
options.binary = chrome_location
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.chrome
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.chrome
options.detach = true
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.chrome
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :chrome, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('chromedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.chrome
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :chrome, service: service
}.to output(/Starting ChromeDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.chrome(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :chrome, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :chrome
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :chrome
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
service = Selenium::WebDriver::Service.chrome
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['CHROMEDRIVER_BIN'] = finder.driver_path
ENV['CHROME_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
Log file features
There are 2 features that are only available when logging to a file:
- append log
- readable timestamps
To use them, you need to also explicitly specify the log path and log level. The log output will be managed by the driver, not the process, so minor differences may be seen.
ChromeDriverService service =
new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class ChromeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
ChromeOptions options = getDefaultChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = getDefaultChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void setBrowserLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBinary(getChromeLocation());
driver = new ChromeDriver(options);
}
@Test
public void extensionOptions() {
ChromeOptions options = getDefaultChromeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
ChromeOptions options = getDefaultChromeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void loggingPreferences() {
ChromeOptions options = getDefaultChromeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
ChromeDriverService service =
new ChromeDriverService.Builder().withLogFile(logLocation).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
ChromeDriverService service =
new ChromeDriverService.Builder().withLogOutput(System.out).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
ChromeDriverService service =
new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getChromeLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermission() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new ChromeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((ChromeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((ChromeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
ChromeDriver driver = new ChromeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
Note: Java also allows toggling these features by System Property:
Property keys: ChromeDriverService.CHROME_DRIVER_APPEND_LOG_PROPERTY
and ChromeDriverService.CHROME_DRIVER_READABLE_TIMESTAMP
Property value: "true"
or "false"
service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_chrome_options()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_args():
options = get_default_chrome_options()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(chrome_bin):
options = get_default_chrome_options()
options.binary_location = chrome_bin
driver = webdriver.Chrome(options=options)
driver.quit()
def test_add_extension():
options = get_default_chrome_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_chrome_options()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_chrome_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.ChromeService(log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as fp:
assert "Starting ChromeDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.ChromeService(log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert "Starting ChromeDriver" in out
driver.quit()
def test_log_level(capfd):
service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert '[DEBUG]' in err
driver.quit()
def test_log_features(log_path):
service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(capfd):
service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
out, err = capfd.readouterr()
assert expected in err
driver.quit()
def test_set_network_conditions():
driver = webdriver.Chrome()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Chrome()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Chrome()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_chrome_options():
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
return options
service.args << '--append-log'
service.args << '--readable-timestamp'
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Options' do
let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.chrome
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.chrome
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.chrome
options.binary = chrome_location
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.chrome
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.chrome
options.detach = true
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.chrome
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :chrome, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('chromedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.chrome
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :chrome, service: service
}.to output(/Starting ChromeDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.chrome(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :chrome, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :chrome
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :chrome
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
service = Selenium::WebDriver::Service.chrome
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['CHROMEDRIVER_BIN'] = finder.driver_path
ENV['CHROME_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
Disabling build check
Chromedriver and Chrome browser versions should match, and if they don’t the driver will error. If you disable the build check, you can force the driver to be used with any version of Chrome. Note that this is an unsupported feature, and bugs will not be investigated.
ChromeDriverService service =
new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class ChromeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
ChromeOptions options = getDefaultChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = getDefaultChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void setBrowserLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBinary(getChromeLocation());
driver = new ChromeDriver(options);
}
@Test
public void extensionOptions() {
ChromeOptions options = getDefaultChromeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
ChromeOptions options = getDefaultChromeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void loggingPreferences() {
ChromeOptions options = getDefaultChromeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
ChromeDriverService service =
new ChromeDriverService.Builder().withLogFile(logLocation).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
ChromeDriverService service =
new ChromeDriverService.Builder().withLogOutput(System.out).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
ChromeDriverService service =
new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getChromeLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermission() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new ChromeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((ChromeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((ChromeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
ChromeDriver driver = new ChromeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
Note: Java also allows disabling build checks by System Property:
Property key: ChromeDriverService.CHROME_DRIVER_DISABLE_BUILD_CHECK
Property value: "true"
or "false"
service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_chrome_options()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_args():
options = get_default_chrome_options()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(chrome_bin):
options = get_default_chrome_options()
options.binary_location = chrome_bin
driver = webdriver.Chrome(options=options)
driver.quit()
def test_add_extension():
options = get_default_chrome_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_chrome_options()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_chrome_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.ChromeService(log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as fp:
assert "Starting ChromeDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.ChromeService(log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert "Starting ChromeDriver" in out
driver.quit()
def test_log_level(capfd):
service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert '[DEBUG]' in err
driver.quit()
def test_log_features(log_path):
service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(capfd):
service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
out, err = capfd.readouterr()
assert expected in err
driver.quit()
def test_set_network_conditions():
driver = webdriver.Chrome()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Chrome()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Chrome()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_chrome_options():
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
return options
service.DisableBuildCheck = true;
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class ChromeTest
{
private ChromeDriver driver;
private string _logLocation;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new ChromeOptions();
driver = new ChromeDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new ChromeOptions();
options.AddArgument("--start-maximized");
driver = new ChromeDriver(options);
}
[TestMethod]
public void SetBrowserLocation()
{
var options = new ChromeOptions();
options.BinaryLocation = GetChromeLocation();
driver = new ChromeDriver(options);
}
[TestMethod]
public void InstallExtension()
{
var options = new ChromeOptions();
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");
options.AddExtension(extensionFilePath);
driver = new ChromeDriver(options);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void ExcludeSwitch()
{
var options = new ChromeOptions();
options.AddExcludedArgument("disable-popup-blocking");
driver = new ChromeDriver(options);
}
[TestMethod]
public void LogsToFile()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting ChromeDriver")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = ChromeDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new ChromeDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsLevel()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
// service.LogLevel = ChromiumDriverLogLevel.Debug
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
}
[TestMethod]
[Ignore("Not implemented")]
public void ConfigureDriverLogs()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.EnableAppendLog = true;
// service.readableTimeStamp = true;
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
}
[TestMethod]
public void DisableBuildCheck()
{
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.DisableBuildCheck = true;
driver = new ChromeDriver(service);
driver.Quit(); // Close the Service log file before reading
var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private static string GetChromeLocation()
{
var options = new ChromeOptions
{
BrowserVersion = "stable"
};
return new DriverFinder(options).GetBrowserPath();
}
}
}
service.args << '--disable-build-check'
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Options' do
let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.chrome
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.chrome
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.chrome
options.binary = chrome_location
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.chrome
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.chrome
options.detach = true
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.chrome
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :chrome, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('chromedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.chrome
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :chrome, service: service
}.to output(/Starting ChromeDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.chrome(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :chrome, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :chrome
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :chrome
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
service = Selenium::WebDriver::Service.chrome
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['CHROMEDRIVER_BIN'] = finder.driver_path
ENV['CHROME_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
Special Features
Casting
Pode comandar dispositivos Chrome Cast, incluindo partilhar abas
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class ChromeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
ChromeOptions options = getDefaultChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = getDefaultChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void setBrowserLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBinary(getChromeLocation());
driver = new ChromeDriver(options);
}
@Test
public void extensionOptions() {
ChromeOptions options = getDefaultChromeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
ChromeOptions options = getDefaultChromeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void loggingPreferences() {
ChromeOptions options = getDefaultChromeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
ChromeDriverService service =
new ChromeDriverService.Builder().withLogFile(logLocation).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
ChromeDriverService service =
new ChromeDriverService.Builder().withLogOutput(System.out).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
ChromeDriverService service =
new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getChromeLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermission() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new ChromeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((ChromeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((ChromeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
ChromeDriver driver = new ChromeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_chrome_options()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_args():
options = get_default_chrome_options()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(chrome_bin):
options = get_default_chrome_options()
options.binary_location = chrome_bin
driver = webdriver.Chrome(options=options)
driver.quit()
def test_add_extension():
options = get_default_chrome_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_chrome_options()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_chrome_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.ChromeService(log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as fp:
assert "Starting ChromeDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.ChromeService(log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert "Starting ChromeDriver" in out
driver.quit()
def test_log_level(capfd):
service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert '[DEBUG]' in err
driver.quit()
def test_log_features(log_path):
service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(capfd):
service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
out, err = capfd.readouterr()
assert expected in err
driver.quit()
def test_set_network_conditions():
driver = webdriver.Chrome()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Chrome()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Chrome()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_chrome_options():
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
return options
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Options' do
let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.chrome
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.chrome
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.chrome
options.binary = chrome_location
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.chrome
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.chrome
options.detach = true
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.chrome
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :chrome, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('chromedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.chrome
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :chrome, service: service
}.to output(/Starting ChromeDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.chrome(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :chrome, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :chrome
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :chrome
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
service = Selenium::WebDriver::Service.chrome
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['CHROMEDRIVER_BIN'] = finder.driver_path
ENV['CHROME_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
Condições de rede
Pode simular vários estados de rede (como exemplo, simular situações com pouca banda).
The following examples are for local webdrivers. For remote webdrivers, please refer to the Remote WebDriver page.
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((ChromeDriver) driver).setNetworkConditions(networkConditions);
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class ChromeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
ChromeOptions options = getDefaultChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = getDefaultChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void setBrowserLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBinary(getChromeLocation());
driver = new ChromeDriver(options);
}
@Test
public void extensionOptions() {
ChromeOptions options = getDefaultChromeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
ChromeOptions options = getDefaultChromeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void loggingPreferences() {
ChromeOptions options = getDefaultChromeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
ChromeDriverService service =
new ChromeDriverService.Builder().withLogFile(logLocation).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
ChromeDriverService service =
new ChromeDriverService.Builder().withLogOutput(System.out).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
ChromeDriverService service =
new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getChromeLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermission() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new ChromeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((ChromeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((ChromeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
ChromeDriver driver = new ChromeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_chrome_options()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_args():
options = get_default_chrome_options()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(chrome_bin):
options = get_default_chrome_options()
options.binary_location = chrome_bin
driver = webdriver.Chrome(options=options)
driver.quit()
def test_add_extension():
options = get_default_chrome_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_chrome_options()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_chrome_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.ChromeService(log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as fp:
assert "Starting ChromeDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.ChromeService(log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert "Starting ChromeDriver" in out
driver.quit()
def test_log_level(capfd):
service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert '[DEBUG]' in err
driver.quit()
def test_log_features(log_path):
service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(capfd):
service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
out, err = capfd.readouterr()
assert expected in err
driver.quit()
def test_set_network_conditions():
driver = webdriver.Chrome()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Chrome()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Chrome()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_chrome_options():
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
return options
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Options' do
let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.chrome
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.chrome
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.chrome
options.binary = chrome_location
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.chrome
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.chrome
options.detach = true
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.chrome
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :chrome, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('chromedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.chrome
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :chrome, service: service
}.to output(/Starting ChromeDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.chrome(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :chrome, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :chrome
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :chrome
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
service = Selenium::WebDriver::Service.chrome
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['CHROMEDRIVER_BIN'] = finder.driver_path
ENV['CHROME_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
Logs
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class ChromeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
ChromeOptions options = getDefaultChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = getDefaultChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void setBrowserLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBinary(getChromeLocation());
driver = new ChromeDriver(options);
}
@Test
public void extensionOptions() {
ChromeOptions options = getDefaultChromeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
ChromeOptions options = getDefaultChromeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void loggingPreferences() {
ChromeOptions options = getDefaultChromeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
ChromeDriverService service =
new ChromeDriverService.Builder().withLogFile(logLocation).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
ChromeDriverService service =
new ChromeDriverService.Builder().withLogOutput(System.out).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
ChromeDriverService service =
new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getChromeLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermission() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new ChromeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((ChromeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((ChromeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
ChromeDriver driver = new ChromeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
logs = driver.get_log("browser")
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_chrome_options()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_args():
options = get_default_chrome_options()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(chrome_bin):
options = get_default_chrome_options()
options.binary_location = chrome_bin
driver = webdriver.Chrome(options=options)
driver.quit()
def test_add_extension():
options = get_default_chrome_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_chrome_options()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_chrome_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.ChromeService(log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as fp:
assert "Starting ChromeDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.ChromeService(log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert "Starting ChromeDriver" in out
driver.quit()
def test_log_level(capfd):
service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert '[DEBUG]' in err
driver.quit()
def test_log_features(log_path):
service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(capfd):
service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
out, err = capfd.readouterr()
assert expected in err
driver.quit()
def test_set_network_conditions():
driver = webdriver.Chrome()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Chrome()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Chrome()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_chrome_options():
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
return options
logs = @driver.logs.get(:browser)
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Options' do
let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.chrome
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.chrome
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.chrome
options.binary = chrome_location
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.chrome
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.chrome
options.detach = true
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.chrome
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :chrome, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('chromedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.chrome
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :chrome, service: service
}.to output(/Starting ChromeDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.chrome(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :chrome, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :chrome
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :chrome
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
service = Selenium::WebDriver::Service.chrome
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['CHROMEDRIVER_BIN'] = finder.driver_path
ENV['CHROME_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
Permissões
driver.setPermission("camera", "denied");
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class ChromeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
ChromeOptions options = getDefaultChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = getDefaultChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void setBrowserLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBinary(getChromeLocation());
driver = new ChromeDriver(options);
}
@Test
public void extensionOptions() {
ChromeOptions options = getDefaultChromeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
ChromeOptions options = getDefaultChromeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void loggingPreferences() {
ChromeOptions options = getDefaultChromeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
ChromeDriverService service =
new ChromeDriverService.Builder().withLogFile(logLocation).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
ChromeDriverService service =
new ChromeDriverService.Builder().withLogOutput(System.out).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
ChromeDriverService service =
new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
ChromeDriverService service =
new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getChromeLocation() {
ChromeOptions options = getDefaultChromeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermission() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new ChromeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((ChromeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((ChromeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
ChromeDriver driver = new ChromeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
driver.set_permissions('camera', 'denied')
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_chrome_options()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_args():
options = get_default_chrome_options()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(chrome_bin):
options = get_default_chrome_options()
options.binary_location = chrome_bin
driver = webdriver.Chrome(options=options)
driver.quit()
def test_add_extension():
options = get_default_chrome_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Chrome(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_chrome_options()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_chrome_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.ChromeService(log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as fp:
assert "Starting ChromeDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.ChromeService(log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert "Starting ChromeDriver" in out
driver.quit()
def test_log_level(capfd):
service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert '[DEBUG]' in err
driver.quit()
def test_log_features(log_path):
service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(capfd):
service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
out, err = capfd.readouterr()
assert expected in err
driver.quit()
def test_set_network_conditions():
driver = webdriver.Chrome()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Chrome()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Chrome()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_chrome_options():
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
return options
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Options' do
let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.chrome
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.chrome
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.chrome
options.binary = chrome_location
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.chrome
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.chrome
options.detach = true
@driver = Selenium::WebDriver.for :chrome, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.chrome
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :chrome, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('chromedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.chrome
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :chrome, service: service
}.to output(/Starting ChromeDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.chrome
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.chrome(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :chrome, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :chrome, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :chrome
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :chrome
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :chrome
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
service = Selenium::WebDriver::Service.chrome
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['CHROMEDRIVER_BIN'] = finder.driver_path
ENV['CHROME_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
DevTools
Veja a secção [Chrome DevTools] para mais informação em como usar Chrome DevTools
2 - Funcionalidade específica do Edge
Microsoft Edge foi criado com recurso ao Chromium, cuja versão mais antiga suportada é a v79. Tal como o Chrome, a versão (maior) do edgedriver deve ser igual à do navegador Edge.
Todas as capacidades e opções encontradas na página Chrome page irão funcionar de igual forma para o Edge.
Opções
Capabilities common to all browsers are described on the Options page.
Capabilities unique to Chromium are documented at Google’s page for Capabilities & ChromeOptions
Este é um exemplo de como iniciar uma sessão Edge com um conjunto de opções básicas:
EdgeOptions options = getDefaultEdgeOptions();
driver = new EdgeDriver(options);
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class EdgeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
EdgeOptions options = getDefaultEdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = getDefaultEdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void setBrowserLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBinary(getEdgeLocation());
driver = new EdgeDriver(options);
}
@Test
public void extensionOptions() {
EdgeOptions options = getDefaultEdgeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
EdgeOptions options = getDefaultEdgeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void loggingPreferences() {
EdgeOptions options = getDefaultEdgeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
EdgeDriverService service =
new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getEdgeLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermissions() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new EdgeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((EdgeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((EdgeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
EdgeDriver driver = new EdgeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
options = get_default_edge_options()
driver = webdriver.Edge(options=options)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_edge_options()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = get_default_edge_options()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(edge_bin):
options = get_default_edge_options()
options.binary_location = edge_bin
driver = webdriver.Edge(options=options)
driver.quit()
def test_add_extension():
options = get_default_edge_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Edge(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_edge_options()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_edge_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.EdgeService(log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.EdgeService(log_output=subprocess.STDOUT)
driver = webdriver.Edge(service=service)
out, err = capfd.readouterr()
assert "Starting Microsoft Edge WebDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)
driver = webdriver.Edge(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
with open(log_path, 'r') as f:
assert expected in f.read()
driver.quit()
def test_set_network_conditions():
driver = webdriver.Edge()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Edge()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Edge()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Edge()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_edge_options():
options = webdriver.EdgeOptions()
options.add_argument("--no-sandbox")
return options
var options = new EdgeOptions();
driver = new EdgeDriver(options);
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class EdgeTest
{
private EdgeDriver driver;
private string _logLocation;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new EdgeOptions();
driver = new EdgeDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new EdgeOptions();
options.AddArgument("--start-maximized");
driver = new EdgeDriver(options);
}
[TestMethod]
public void SetBrowserLocation()
{
var options = new EdgeOptions();
options.BinaryLocation = GetEdgeLocation();
driver = new EdgeDriver(options);
}
[TestMethod]
public void InstallExtension()
{
var options = new EdgeOptions();
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");
options.AddExtension(extensionFilePath);
driver = new EdgeDriver(options);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void ExcludeSwitch()
{
var options = new EdgeOptions();
options.AddExcludedArgument("disable-popup-blocking");
driver = new EdgeDriver(options);
}
[TestMethod]
public void LogsToFile()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting Microsoft Edge WebDriver")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = EdgeDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new EdgeDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsLevel()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
// service.LogLevel = ChromiumDriverLogLevel.Debug
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
}
[TestMethod]
[Ignore("Not implemented")]
public void ConfigureDriverLogs()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.EnableAppendLog = true;
// service.readableTimeStamp = true;
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
}
[TestMethod]
public void DisableBuildCheck()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.DisableBuildCheck = true;
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private static string GetEdgeLocation()
{
var options = new EdgeOptions
{
BrowserVersion = "stable"
};
return new DriverFinder(options).GetBrowserPath();
}
}
}
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.edge
options.binary = edge_location
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.edge
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :edge, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('msedgedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.edge
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :edge, service: service
}.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.edge(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :edge, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :edge
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :edge
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
service = Selenium::WebDriver::Service.edge
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['EDGEDRIVER_BIN'] = finder.driver_path
ENV['EDGE_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
let options = new edge.Options();
driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(options)
.build();
Show full example
const {Browser, Builder} = require('selenium-webdriver');
const edge = require('selenium-webdriver/edge');
describe('Open Edge', function () {
let driver;
before(async function () {
let options = new edge.Options();
driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(options)
.build();
});
after(async () => await driver.quit());
it('Basic Edge test', async function () {
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
});
});
Argumentos
The args
parameter is for a list of command line switches to be used when starting the browser.
There are two excellent resources for investigating these arguments:
Opções mais frequentes incluem --start-maximized
e --headless=new
e --user-data-dir=...
Adicione uma opção:
options.addArguments("--start-maximized");
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class EdgeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
EdgeOptions options = getDefaultEdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = getDefaultEdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void setBrowserLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBinary(getEdgeLocation());
driver = new EdgeDriver(options);
}
@Test
public void extensionOptions() {
EdgeOptions options = getDefaultEdgeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
EdgeOptions options = getDefaultEdgeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void loggingPreferences() {
EdgeOptions options = getDefaultEdgeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
EdgeDriverService service =
new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getEdgeLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermissions() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new EdgeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((EdgeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((EdgeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
EdgeDriver driver = new EdgeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
options.add_argument("--start-maximized")
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_edge_options()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = get_default_edge_options()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(edge_bin):
options = get_default_edge_options()
options.binary_location = edge_bin
driver = webdriver.Edge(options=options)
driver.quit()
def test_add_extension():
options = get_default_edge_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Edge(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_edge_options()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_edge_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.EdgeService(log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.EdgeService(log_output=subprocess.STDOUT)
driver = webdriver.Edge(service=service)
out, err = capfd.readouterr()
assert "Starting Microsoft Edge WebDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)
driver = webdriver.Edge(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
with open(log_path, 'r') as f:
assert expected in f.read()
driver.quit()
def test_set_network_conditions():
driver = webdriver.Edge()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Edge()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Edge()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Edge()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_edge_options():
options = webdriver.EdgeOptions()
options.add_argument("--no-sandbox")
return options
options.AddArgument("--start-maximized");
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class EdgeTest
{
private EdgeDriver driver;
private string _logLocation;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new EdgeOptions();
driver = new EdgeDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new EdgeOptions();
options.AddArgument("--start-maximized");
driver = new EdgeDriver(options);
}
[TestMethod]
public void SetBrowserLocation()
{
var options = new EdgeOptions();
options.BinaryLocation = GetEdgeLocation();
driver = new EdgeDriver(options);
}
[TestMethod]
public void InstallExtension()
{
var options = new EdgeOptions();
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");
options.AddExtension(extensionFilePath);
driver = new EdgeDriver(options);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void ExcludeSwitch()
{
var options = new EdgeOptions();
options.AddExcludedArgument("disable-popup-blocking");
driver = new EdgeDriver(options);
}
[TestMethod]
public void LogsToFile()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting Microsoft Edge WebDriver")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = EdgeDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new EdgeDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsLevel()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
// service.LogLevel = ChromiumDriverLogLevel.Debug
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
}
[TestMethod]
[Ignore("Not implemented")]
public void ConfigureDriverLogs()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.EnableAppendLog = true;
// service.readableTimeStamp = true;
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
}
[TestMethod]
public void DisableBuildCheck()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.DisableBuildCheck = true;
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private static string GetEdgeLocation()
{
var options = new EdgeOptions
{
BrowserVersion = "stable"
};
return new DriverFinder(options).GetBrowserPath();
}
}
}
options.args << '--start-maximized'
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.edge
options.binary = edge_location
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.edge
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :edge, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('msedgedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.edge
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :edge, service: service
}.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.edge(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :edge, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :edge
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :edge
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
service = Selenium::WebDriver::Service.edge
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['EDGEDRIVER_BIN'] = finder.driver_path
ENV['EDGE_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
.setEdgeOptions(options.addArguments('--headless=new'))
Show full example
const {Browser, By, Builder } = require('selenium-webdriver');
const edge = require('selenium-webdriver/edge');
const options = new edge.Options();
const assert = require("assert");
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(options.addArguments('--headless=new'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('exclude switches', async function () {
let driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(options.excludeSwitches('enable-automation'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Keep browser open - set detach to true ', async function () {
let driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(options.detachDriver(true))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
// As tests runs in ci, quitting the driver instance to avoid any failures
await driver.quit();
});
it('Basic edge test', async function () {
const Options = new edge.Options();
let driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(Options)
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Add Extension', async function () {
let driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
let injected = await driver.findElement(By.id('webextensions-selenium-example'));
assert.equal(await injected.getText(), `Content injected by webextensions-selenium-example`)
await driver.quit();
});
});
Start browser in a specified location
The binary
parameter takes the path of an alternate location of browser to use. With this parameter you can
use chromedriver to drive various Chromium based browsers.
Add a browser location to options:
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class EdgeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
EdgeOptions options = getDefaultEdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = getDefaultEdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void setBrowserLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBinary(getEdgeLocation());
driver = new EdgeDriver(options);
}
@Test
public void extensionOptions() {
EdgeOptions options = getDefaultEdgeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
EdgeOptions options = getDefaultEdgeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void loggingPreferences() {
EdgeOptions options = getDefaultEdgeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
EdgeDriverService service =
new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getEdgeLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermissions() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new EdgeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((EdgeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((EdgeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
EdgeDriver driver = new EdgeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
options.binary_location = edge_bin
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_edge_options()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = get_default_edge_options()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(edge_bin):
options = get_default_edge_options()
options.binary_location = edge_bin
driver = webdriver.Edge(options=options)
driver.quit()
def test_add_extension():
options = get_default_edge_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Edge(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_edge_options()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_edge_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.EdgeService(log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.EdgeService(log_output=subprocess.STDOUT)
driver = webdriver.Edge(service=service)
out, err = capfd.readouterr()
assert "Starting Microsoft Edge WebDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)
driver = webdriver.Edge(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
with open(log_path, 'r') as f:
assert expected in f.read()
driver.quit()
def test_set_network_conditions():
driver = webdriver.Edge()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Edge()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Edge()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Edge()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_edge_options():
options = webdriver.EdgeOptions()
options.add_argument("--no-sandbox")
return options
options.BinaryLocation = GetEdgeLocation();
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class EdgeTest
{
private EdgeDriver driver;
private string _logLocation;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new EdgeOptions();
driver = new EdgeDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new EdgeOptions();
options.AddArgument("--start-maximized");
driver = new EdgeDriver(options);
}
[TestMethod]
public void SetBrowserLocation()
{
var options = new EdgeOptions();
options.BinaryLocation = GetEdgeLocation();
driver = new EdgeDriver(options);
}
[TestMethod]
public void InstallExtension()
{
var options = new EdgeOptions();
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");
options.AddExtension(extensionFilePath);
driver = new EdgeDriver(options);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void ExcludeSwitch()
{
var options = new EdgeOptions();
options.AddExcludedArgument("disable-popup-blocking");
driver = new EdgeDriver(options);
}
[TestMethod]
public void LogsToFile()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting Microsoft Edge WebDriver")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = EdgeDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new EdgeDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsLevel()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
// service.LogLevel = ChromiumDriverLogLevel.Debug
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
}
[TestMethod]
[Ignore("Not implemented")]
public void ConfigureDriverLogs()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.EnableAppendLog = true;
// service.readableTimeStamp = true;
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
}
[TestMethod]
public void DisableBuildCheck()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.DisableBuildCheck = true;
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private static string GetEdgeLocation()
{
var options = new EdgeOptions
{
BrowserVersion = "stable"
};
return new DriverFinder(options).GetBrowserPath();
}
}
}
options.binary = edge_location
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.edge
options.binary = edge_location
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.edge
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :edge, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('msedgedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.edge
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :edge, service: service
}.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.edge(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :edge, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :edge
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :edge
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
service = Selenium::WebDriver::Service.edge
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['EDGEDRIVER_BIN'] = finder.driver_path
ENV['EDGE_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
Add extensions
The extensions
parameter accepts crx files. As for unpacked directories,
please use the load-extension
argument instead, as mentioned in
this post.
Add an extension to options:
options.addExtensions(extensionFilePath);
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class EdgeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
EdgeOptions options = getDefaultEdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = getDefaultEdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void setBrowserLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBinary(getEdgeLocation());
driver = new EdgeDriver(options);
}
@Test
public void extensionOptions() {
EdgeOptions options = getDefaultEdgeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
EdgeOptions options = getDefaultEdgeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void loggingPreferences() {
EdgeOptions options = getDefaultEdgeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
EdgeDriverService service =
new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getEdgeLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermissions() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new EdgeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((EdgeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((EdgeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
EdgeDriver driver = new EdgeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
options.add_extension(extension_file_path)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_edge_options()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = get_default_edge_options()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(edge_bin):
options = get_default_edge_options()
options.binary_location = edge_bin
driver = webdriver.Edge(options=options)
driver.quit()
def test_add_extension():
options = get_default_edge_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Edge(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_edge_options()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_edge_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.EdgeService(log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.EdgeService(log_output=subprocess.STDOUT)
driver = webdriver.Edge(service=service)
out, err = capfd.readouterr()
assert "Starting Microsoft Edge WebDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)
driver = webdriver.Edge(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
with open(log_path, 'r') as f:
assert expected in f.read()
driver.quit()
def test_set_network_conditions():
driver = webdriver.Edge()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Edge()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Edge()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Edge()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_edge_options():
options = webdriver.EdgeOptions()
options.add_argument("--no-sandbox")
return options
options.AddExtension(extensionFilePath);
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class EdgeTest
{
private EdgeDriver driver;
private string _logLocation;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new EdgeOptions();
driver = new EdgeDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new EdgeOptions();
options.AddArgument("--start-maximized");
driver = new EdgeDriver(options);
}
[TestMethod]
public void SetBrowserLocation()
{
var options = new EdgeOptions();
options.BinaryLocation = GetEdgeLocation();
driver = new EdgeDriver(options);
}
[TestMethod]
public void InstallExtension()
{
var options = new EdgeOptions();
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");
options.AddExtension(extensionFilePath);
driver = new EdgeDriver(options);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void ExcludeSwitch()
{
var options = new EdgeOptions();
options.AddExcludedArgument("disable-popup-blocking");
driver = new EdgeDriver(options);
}
[TestMethod]
public void LogsToFile()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting Microsoft Edge WebDriver")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = EdgeDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new EdgeDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsLevel()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
// service.LogLevel = ChromiumDriverLogLevel.Debug
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
}
[TestMethod]
[Ignore("Not implemented")]
public void ConfigureDriverLogs()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.EnableAppendLog = true;
// service.readableTimeStamp = true;
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
}
[TestMethod]
public void DisableBuildCheck()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.DisableBuildCheck = true;
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private static string GetEdgeLocation()
{
var options = new EdgeOptions
{
BrowserVersion = "stable"
};
return new DriverFinder(options).GetBrowserPath();
}
}
}
options.add_extension(extension_file_path)
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.edge
options.binary = edge_location
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.edge
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :edge, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('msedgedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.edge
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :edge, service: service
}.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.edge(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :edge, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :edge
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :edge
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
service = Selenium::WebDriver::Service.edge
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['EDGEDRIVER_BIN'] = finder.driver_path
ENV['EDGE_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
.setEdgeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
Show full example
const {Browser, By, Builder } = require('selenium-webdriver');
const edge = require('selenium-webdriver/edge');
const options = new edge.Options();
const assert = require("assert");
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(options.addArguments('--headless=new'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('exclude switches', async function () {
let driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(options.excludeSwitches('enable-automation'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Keep browser open - set detach to true ', async function () {
let driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(options.detachDriver(true))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
// As tests runs in ci, quitting the driver instance to avoid any failures
await driver.quit();
});
it('Basic edge test', async function () {
const Options = new edge.Options();
let driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(Options)
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Add Extension', async function () {
let driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
let injected = await driver.findElement(By.id('webextensions-selenium-example'));
assert.equal(await injected.getText(), `Content injected by webextensions-selenium-example`)
await driver.quit();
});
});
Keeping browser open
Setting the detach
parameter to true will keep the browser open after the process has ended,
so long as the quit command is not sent to the driver.
Note: This is already the default behavior in Java.
options.add_experimental_option("detach", True)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_edge_options()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = get_default_edge_options()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(edge_bin):
options = get_default_edge_options()
options.binary_location = edge_bin
driver = webdriver.Edge(options=options)
driver.quit()
def test_add_extension():
options = get_default_edge_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Edge(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_edge_options()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_edge_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.EdgeService(log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.EdgeService(log_output=subprocess.STDOUT)
driver = webdriver.Edge(service=service)
out, err = capfd.readouterr()
assert "Starting Microsoft Edge WebDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)
driver = webdriver.Edge(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
with open(log_path, 'r') as f:
assert expected in f.read()
driver.quit()
def test_set_network_conditions():
driver = webdriver.Edge()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Edge()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Edge()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Edge()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_edge_options():
options = webdriver.EdgeOptions()
options.add_argument("--no-sandbox")
return options
Note: This is already the default behavior in .NET.
options.detach = true
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.edge
options.binary = edge_location
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.edge
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :edge, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('msedgedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.edge
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :edge, service: service
}.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.edge(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :edge, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :edge
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :edge
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
service = Selenium::WebDriver::Service.edge
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['EDGEDRIVER_BIN'] = finder.driver_path
ENV['EDGE_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
.setEdgeOptions(options.detachDriver(true))
Show full example
const {Browser, By, Builder } = require('selenium-webdriver');
const edge = require('selenium-webdriver/edge');
const options = new edge.Options();
const assert = require("assert");
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(options.addArguments('--headless=new'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('exclude switches', async function () {
let driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(options.excludeSwitches('enable-automation'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Keep browser open - set detach to true ', async function () {
let driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(options.detachDriver(true))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
// As tests runs in ci, quitting the driver instance to avoid any failures
await driver.quit();
});
it('Basic edge test', async function () {
const Options = new edge.Options();
let driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(Options)
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Add Extension', async function () {
let driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
let injected = await driver.findElement(By.id('webextensions-selenium-example'));
assert.equal(await injected.getText(), `Content injected by webextensions-selenium-example`)
await driver.quit();
});
});
Excluding arguments
MSEdgedriver has several default arguments it uses to start the browser.
If you do not want those arguments added, pass them into excludeSwitches
.
A common example is to turn the popup blocker back on. A full list of default arguments
can be parsed from the
Chromium Source Code
Set excluded arguments on options:
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class EdgeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
EdgeOptions options = getDefaultEdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = getDefaultEdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void setBrowserLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBinary(getEdgeLocation());
driver = new EdgeDriver(options);
}
@Test
public void extensionOptions() {
EdgeOptions options = getDefaultEdgeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
EdgeOptions options = getDefaultEdgeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void loggingPreferences() {
EdgeOptions options = getDefaultEdgeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
EdgeDriverService service =
new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getEdgeLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermissions() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new EdgeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((EdgeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((EdgeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
EdgeDriver driver = new EdgeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_edge_options()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = get_default_edge_options()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(edge_bin):
options = get_default_edge_options()
options.binary_location = edge_bin
driver = webdriver.Edge(options=options)
driver.quit()
def test_add_extension():
options = get_default_edge_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Edge(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_edge_options()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_edge_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.EdgeService(log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.EdgeService(log_output=subprocess.STDOUT)
driver = webdriver.Edge(service=service)
out, err = capfd.readouterr()
assert "Starting Microsoft Edge WebDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)
driver = webdriver.Edge(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
with open(log_path, 'r') as f:
assert expected in f.read()
driver.quit()
def test_set_network_conditions():
driver = webdriver.Edge()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Edge()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Edge()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Edge()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_edge_options():
options = webdriver.EdgeOptions()
options.add_argument("--no-sandbox")
return options
options.AddExcludedArgument("disable-popup-blocking");
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class EdgeTest
{
private EdgeDriver driver;
private string _logLocation;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new EdgeOptions();
driver = new EdgeDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new EdgeOptions();
options.AddArgument("--start-maximized");
driver = new EdgeDriver(options);
}
[TestMethod]
public void SetBrowserLocation()
{
var options = new EdgeOptions();
options.BinaryLocation = GetEdgeLocation();
driver = new EdgeDriver(options);
}
[TestMethod]
public void InstallExtension()
{
var options = new EdgeOptions();
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");
options.AddExtension(extensionFilePath);
driver = new EdgeDriver(options);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void ExcludeSwitch()
{
var options = new EdgeOptions();
options.AddExcludedArgument("disable-popup-blocking");
driver = new EdgeDriver(options);
}
[TestMethod]
public void LogsToFile()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting Microsoft Edge WebDriver")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = EdgeDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new EdgeDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsLevel()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
// service.LogLevel = ChromiumDriverLogLevel.Debug
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
}
[TestMethod]
[Ignore("Not implemented")]
public void ConfigureDriverLogs()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.EnableAppendLog = true;
// service.readableTimeStamp = true;
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
}
[TestMethod]
public void DisableBuildCheck()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.DisableBuildCheck = true;
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private static string GetEdgeLocation()
{
var options = new EdgeOptions
{
BrowserVersion = "stable"
};
return new DriverFinder(options).GetBrowserPath();
}
}
}
options.exclude_switches << 'disable-popup-blocking'
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.edge
options.binary = edge_location
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.edge
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :edge, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('msedgedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.edge
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :edge, service: service
}.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.edge(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :edge, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :edge
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :edge
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
service = Selenium::WebDriver::Service.edge
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['EDGEDRIVER_BIN'] = finder.driver_path
ENV['EDGE_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
.setEdgeOptions(options.excludeSwitches('enable-automation'))
Show full example
const {Browser, By, Builder } = require('selenium-webdriver');
const edge = require('selenium-webdriver/edge');
const options = new edge.Options();
const assert = require("assert");
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(options.addArguments('--headless=new'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('exclude switches', async function () {
let driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(options.excludeSwitches('enable-automation'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Keep browser open - set detach to true ', async function () {
let driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(options.detachDriver(true))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
// As tests runs in ci, quitting the driver instance to avoid any failures
await driver.quit();
});
it('Basic edge test', async function () {
const Options = new edge.Options();
let driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(Options)
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Add Extension', async function () {
let driver = new Builder()
.forBrowser(Browser.EDGE)
.setEdgeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
let injected = await driver.findElement(By.id('webextensions-selenium-example'));
assert.equal(await injected.getText(), `Content injected by webextensions-selenium-example`)
await driver.quit();
});
});
Service
Examples for creating a default Service object, and for setting driver location and port can be found on the Driver Service page.
Log output
Getting driver logs can be helpful for debugging issues. The Service class lets you direct where the logs will go. Logging output is ignored unless the user directs it somewhere.
File output
To change the logging output to save to a specific file:
EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class EdgeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
EdgeOptions options = getDefaultEdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = getDefaultEdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void setBrowserLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBinary(getEdgeLocation());
driver = new EdgeDriver(options);
}
@Test
public void extensionOptions() {
EdgeOptions options = getDefaultEdgeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
EdgeOptions options = getDefaultEdgeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void loggingPreferences() {
EdgeOptions options = getDefaultEdgeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
EdgeDriverService service =
new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getEdgeLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermissions() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new EdgeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((EdgeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((EdgeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
EdgeDriver driver = new EdgeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
Note: Java also allows setting file output by System Property:
Property key: EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY
Property value: String representing path to log file
service = webdriver.EdgeService(log_output=log_path)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_edge_options()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = get_default_edge_options()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(edge_bin):
options = get_default_edge_options()
options.binary_location = edge_bin
driver = webdriver.Edge(options=options)
driver.quit()
def test_add_extension():
options = get_default_edge_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Edge(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_edge_options()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_edge_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.EdgeService(log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.EdgeService(log_output=subprocess.STDOUT)
driver = webdriver.Edge(service=service)
out, err = capfd.readouterr()
assert "Starting Microsoft Edge WebDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)
driver = webdriver.Edge(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
with open(log_path, 'r') as f:
assert expected in f.read()
driver.quit()
def test_set_network_conditions():
driver = webdriver.Edge()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Edge()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Edge()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Edge()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_edge_options():
options = webdriver.EdgeOptions()
options.add_argument("--no-sandbox")
return options
service.LogPath = GetLogLocation();
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class EdgeTest
{
private EdgeDriver driver;
private string _logLocation;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new EdgeOptions();
driver = new EdgeDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new EdgeOptions();
options.AddArgument("--start-maximized");
driver = new EdgeDriver(options);
}
[TestMethod]
public void SetBrowserLocation()
{
var options = new EdgeOptions();
options.BinaryLocation = GetEdgeLocation();
driver = new EdgeDriver(options);
}
[TestMethod]
public void InstallExtension()
{
var options = new EdgeOptions();
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");
options.AddExtension(extensionFilePath);
driver = new EdgeDriver(options);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void ExcludeSwitch()
{
var options = new EdgeOptions();
options.AddExcludedArgument("disable-popup-blocking");
driver = new EdgeDriver(options);
}
[TestMethod]
public void LogsToFile()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting Microsoft Edge WebDriver")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = EdgeDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new EdgeDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsLevel()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
// service.LogLevel = ChromiumDriverLogLevel.Debug
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
}
[TestMethod]
[Ignore("Not implemented")]
public void ConfigureDriverLogs()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.EnableAppendLog = true;
// service.readableTimeStamp = true;
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
}
[TestMethod]
public void DisableBuildCheck()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.DisableBuildCheck = true;
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private static string GetEdgeLocation()
{
var options = new EdgeOptions
{
BrowserVersion = "stable"
};
return new DriverFinder(options).GetBrowserPath();
}
}
}
service.log = file_name
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.edge
options.binary = edge_location
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.edge
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :edge, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('msedgedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.edge
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :edge, service: service
}.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.edge(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :edge, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :edge
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :edge
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
service = Selenium::WebDriver::Service.edge
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['EDGEDRIVER_BIN'] = finder.driver_path
ENV['EDGE_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
Console output
To change the logging output to display in the console as STDOUT:
EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class EdgeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
EdgeOptions options = getDefaultEdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = getDefaultEdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void setBrowserLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBinary(getEdgeLocation());
driver = new EdgeDriver(options);
}
@Test
public void extensionOptions() {
EdgeOptions options = getDefaultEdgeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
EdgeOptions options = getDefaultEdgeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void loggingPreferences() {
EdgeOptions options = getDefaultEdgeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
EdgeDriverService service =
new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getEdgeLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermissions() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new EdgeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((EdgeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((EdgeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
EdgeDriver driver = new EdgeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
Note: Java also allows setting console output by System Property;
Property key: EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY
Property value: DriverService.LOG_STDOUT
or DriverService.LOG_STDERR
service = webdriver.EdgeService(log_output=subprocess.STDOUT)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_edge_options()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = get_default_edge_options()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(edge_bin):
options = get_default_edge_options()
options.binary_location = edge_bin
driver = webdriver.Edge(options=options)
driver.quit()
def test_add_extension():
options = get_default_edge_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Edge(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_edge_options()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_edge_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.EdgeService(log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.EdgeService(log_output=subprocess.STDOUT)
driver = webdriver.Edge(service=service)
out, err = capfd.readouterr()
assert "Starting Microsoft Edge WebDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)
driver = webdriver.Edge(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
with open(log_path, 'r') as f:
assert expected in f.read()
driver.quit()
def test_set_network_conditions():
driver = webdriver.Edge()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Edge()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Edge()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Edge()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_edge_options():
options = webdriver.EdgeOptions()
options.add_argument("--no-sandbox")
return options
$stdout
and $stderr
are both valid values
service.log = $stdout
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.edge
options.binary = edge_location
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.edge
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :edge, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('msedgedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.edge
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :edge, service: service
}.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.edge(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :edge, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :edge
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :edge
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
service = Selenium::WebDriver::Service.edge
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['EDGEDRIVER_BIN'] = finder.driver_path
ENV['EDGE_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
Log level
There are 6 available log levels: ALL
, DEBUG
, INFO
, WARNING
, SEVERE
, and OFF
.
Note that --verbose
is equivalent to --log-level=ALL
and --silent
is equivalent to --log-level=OFF
,
so this example is just setting the log level generically:
EdgeDriverService service =
new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class EdgeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
EdgeOptions options = getDefaultEdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = getDefaultEdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void setBrowserLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBinary(getEdgeLocation());
driver = new EdgeDriver(options);
}
@Test
public void extensionOptions() {
EdgeOptions options = getDefaultEdgeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
EdgeOptions options = getDefaultEdgeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void loggingPreferences() {
EdgeOptions options = getDefaultEdgeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
EdgeDriverService service =
new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getEdgeLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermissions() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new EdgeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((EdgeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((EdgeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
EdgeDriver driver = new EdgeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
Note: Java also allows setting log level by System Property:
Property key: EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY
Property value: String representation of ChromiumDriverLogLevel
enum
service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_edge_options()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = get_default_edge_options()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(edge_bin):
options = get_default_edge_options()
options.binary_location = edge_bin
driver = webdriver.Edge(options=options)
driver.quit()
def test_add_extension():
options = get_default_edge_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Edge(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_edge_options()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_edge_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.EdgeService(log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.EdgeService(log_output=subprocess.STDOUT)
driver = webdriver.Edge(service=service)
out, err = capfd.readouterr()
assert "Starting Microsoft Edge WebDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)
driver = webdriver.Edge(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
with open(log_path, 'r') as f:
assert expected in f.read()
driver.quit()
def test_set_network_conditions():
driver = webdriver.Edge()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Edge()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Edge()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Edge()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_edge_options():
options = webdriver.EdgeOptions()
options.add_argument("--no-sandbox")
return options
service.args << '--log-level=DEBUG'
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.edge
options.binary = edge_location
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.edge
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :edge, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('msedgedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.edge
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :edge, service: service
}.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.edge(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :edge, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :edge
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :edge
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
service = Selenium::WebDriver::Service.edge
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['EDGEDRIVER_BIN'] = finder.driver_path
ENV['EDGE_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
Log file features
There are 2 features that are only available when logging to a file:
- append log
- readable timestamps
To use them, you need to also explicitly specify the log path and log level. The log output will be managed by the driver, not the process, so minor differences may be seen.
EdgeDriverService service =
new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class EdgeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
EdgeOptions options = getDefaultEdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = getDefaultEdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void setBrowserLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBinary(getEdgeLocation());
driver = new EdgeDriver(options);
}
@Test
public void extensionOptions() {
EdgeOptions options = getDefaultEdgeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
EdgeOptions options = getDefaultEdgeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void loggingPreferences() {
EdgeOptions options = getDefaultEdgeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
EdgeDriverService service =
new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getEdgeLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermissions() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new EdgeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((EdgeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((EdgeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
EdgeDriver driver = new EdgeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
Note: Java also allows toggling these features by System Property:
Property keys: EdgeDriverService.EDGE_DRIVER_APPEND_LOG_PROPERTY
and EdgeDriverService.EDGE_DRIVER_READABLE_TIMESTAMP
Property value: "true"
or "false"
service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_edge_options()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = get_default_edge_options()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(edge_bin):
options = get_default_edge_options()
options.binary_location = edge_bin
driver = webdriver.Edge(options=options)
driver.quit()
def test_add_extension():
options = get_default_edge_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Edge(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_edge_options()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_edge_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.EdgeService(log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.EdgeService(log_output=subprocess.STDOUT)
driver = webdriver.Edge(service=service)
out, err = capfd.readouterr()
assert "Starting Microsoft Edge WebDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)
driver = webdriver.Edge(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
with open(log_path, 'r') as f:
assert expected in f.read()
driver.quit()
def test_set_network_conditions():
driver = webdriver.Edge()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Edge()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Edge()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Edge()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_edge_options():
options = webdriver.EdgeOptions()
options.add_argument("--no-sandbox")
return options
service.args << '--append-log'
service.args << '--readable-timestamp'
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.edge
options.binary = edge_location
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.edge
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :edge, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('msedgedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.edge
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :edge, service: service
}.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.edge(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :edge, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :edge
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :edge
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
service = Selenium::WebDriver::Service.edge
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['EDGEDRIVER_BIN'] = finder.driver_path
ENV['EDGE_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
Disabling build check
Edge browser and msedgedriver versions should match, and if they don’t the driver will error. If you disable the build check, you can force the driver to be used with any version of Edge. Note that this is an unsupported feature, and bugs will not be investigated.
EdgeDriverService service =
new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class EdgeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
EdgeOptions options = getDefaultEdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = getDefaultEdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void setBrowserLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBinary(getEdgeLocation());
driver = new EdgeDriver(options);
}
@Test
public void extensionOptions() {
EdgeOptions options = getDefaultEdgeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
EdgeOptions options = getDefaultEdgeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void loggingPreferences() {
EdgeOptions options = getDefaultEdgeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
EdgeDriverService service =
new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getEdgeLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermissions() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new EdgeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((EdgeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((EdgeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
EdgeDriver driver = new EdgeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
Note: Java also allows disabling build checks by System Property:
Property key: EdgeDriverService.EDGE_DRIVER_DISABLE_BUILD_CHECK
Property value: "true"
or "false"
service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_edge_options()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = get_default_edge_options()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(edge_bin):
options = get_default_edge_options()
options.binary_location = edge_bin
driver = webdriver.Edge(options=options)
driver.quit()
def test_add_extension():
options = get_default_edge_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Edge(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_edge_options()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_edge_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.EdgeService(log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.EdgeService(log_output=subprocess.STDOUT)
driver = webdriver.Edge(service=service)
out, err = capfd.readouterr()
assert "Starting Microsoft Edge WebDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)
driver = webdriver.Edge(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
with open(log_path, 'r') as f:
assert expected in f.read()
driver.quit()
def test_set_network_conditions():
driver = webdriver.Edge()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Edge()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Edge()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Edge()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_edge_options():
options = webdriver.EdgeOptions()
options.add_argument("--no-sandbox")
return options
service.DisableBuildCheck = true;
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class EdgeTest
{
private EdgeDriver driver;
private string _logLocation;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new EdgeOptions();
driver = new EdgeDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new EdgeOptions();
options.AddArgument("--start-maximized");
driver = new EdgeDriver(options);
}
[TestMethod]
public void SetBrowserLocation()
{
var options = new EdgeOptions();
options.BinaryLocation = GetEdgeLocation();
driver = new EdgeDriver(options);
}
[TestMethod]
public void InstallExtension()
{
var options = new EdgeOptions();
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");
options.AddExtension(extensionFilePath);
driver = new EdgeDriver(options);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void ExcludeSwitch()
{
var options = new EdgeOptions();
options.AddExcludedArgument("disable-popup-blocking");
driver = new EdgeDriver(options);
}
[TestMethod]
public void LogsToFile()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting Microsoft Edge WebDriver")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = EdgeDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new EdgeDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsLevel()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
// service.LogLevel = ChromiumDriverLogLevel.Debug
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
}
[TestMethod]
[Ignore("Not implemented")]
public void ConfigureDriverLogs()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.EnableAppendLog = true;
// service.readableTimeStamp = true;
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
}
[TestMethod]
public void DisableBuildCheck()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.DisableBuildCheck = true;
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private static string GetEdgeLocation()
{
var options = new EdgeOptions
{
BrowserVersion = "stable"
};
return new DriverFinder(options).GetBrowserPath();
}
}
}
service.args << '--disable-build-check'
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.edge
options.binary = edge_location
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.edge
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :edge, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('msedgedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.edge
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :edge, service: service
}.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.edge(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :edge, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :edge
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :edge
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
service = Selenium::WebDriver::Service.edge
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['EDGEDRIVER_BIN'] = finder.driver_path
ENV['EDGE_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
Modo compatibilidade Internet Explorer
O Microsoft Edge pode ser controlado em modo “compatibilidade Internet Explorer”, são usadas classes do Internet Explorer Driver em conjunção com o Microsoft Edge. Leia a página Internet Explorer para mais detalhes.
Special Features
Some browsers have implemented additional features that are unique to them.
Casting
You can drive Chrome Cast devices with Edge, including sharing tabs
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class EdgeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
EdgeOptions options = getDefaultEdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = getDefaultEdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void setBrowserLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBinary(getEdgeLocation());
driver = new EdgeDriver(options);
}
@Test
public void extensionOptions() {
EdgeOptions options = getDefaultEdgeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
EdgeOptions options = getDefaultEdgeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void loggingPreferences() {
EdgeOptions options = getDefaultEdgeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
EdgeDriverService service =
new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getEdgeLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermissions() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new EdgeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((EdgeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((EdgeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
EdgeDriver driver = new EdgeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_edge_options()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = get_default_edge_options()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(edge_bin):
options = get_default_edge_options()
options.binary_location = edge_bin
driver = webdriver.Edge(options=options)
driver.quit()
def test_add_extension():
options = get_default_edge_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Edge(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_edge_options()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_edge_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.EdgeService(log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.EdgeService(log_output=subprocess.STDOUT)
driver = webdriver.Edge(service=service)
out, err = capfd.readouterr()
assert "Starting Microsoft Edge WebDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)
driver = webdriver.Edge(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
with open(log_path, 'r') as f:
assert expected in f.read()
driver.quit()
def test_set_network_conditions():
driver = webdriver.Edge()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Edge()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Edge()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Edge()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_edge_options():
options = webdriver.EdgeOptions()
options.add_argument("--no-sandbox")
return options
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.edge
options.binary = edge_location
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.edge
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :edge, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('msedgedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.edge
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :edge, service: service
}.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.edge(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :edge, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :edge
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :edge
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
service = Selenium::WebDriver::Service.edge
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['EDGEDRIVER_BIN'] = finder.driver_path
ENV['EDGE_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
Network conditions
You can simulate various network conditions.
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class EdgeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
EdgeOptions options = getDefaultEdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = getDefaultEdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void setBrowserLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBinary(getEdgeLocation());
driver = new EdgeDriver(options);
}
@Test
public void extensionOptions() {
EdgeOptions options = getDefaultEdgeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
EdgeOptions options = getDefaultEdgeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void loggingPreferences() {
EdgeOptions options = getDefaultEdgeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
EdgeDriverService service =
new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getEdgeLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermissions() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new EdgeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((EdgeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((EdgeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
EdgeDriver driver = new EdgeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_edge_options()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = get_default_edge_options()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(edge_bin):
options = get_default_edge_options()
options.binary_location = edge_bin
driver = webdriver.Edge(options=options)
driver.quit()
def test_add_extension():
options = get_default_edge_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Edge(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_edge_options()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_edge_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.EdgeService(log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.EdgeService(log_output=subprocess.STDOUT)
driver = webdriver.Edge(service=service)
out, err = capfd.readouterr()
assert "Starting Microsoft Edge WebDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)
driver = webdriver.Edge(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
with open(log_path, 'r') as f:
assert expected in f.read()
driver.quit()
def test_set_network_conditions():
driver = webdriver.Edge()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Edge()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Edge()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Edge()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_edge_options():
options = webdriver.EdgeOptions()
options.add_argument("--no-sandbox")
return options
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.edge
options.binary = edge_location
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.edge
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :edge, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('msedgedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.edge
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :edge, service: service
}.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.edge(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :edge, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :edge
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :edge
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
service = Selenium::WebDriver::Service.edge
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['EDGEDRIVER_BIN'] = finder.driver_path
ENV['EDGE_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
Logs
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class EdgeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
EdgeOptions options = getDefaultEdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = getDefaultEdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void setBrowserLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBinary(getEdgeLocation());
driver = new EdgeDriver(options);
}
@Test
public void extensionOptions() {
EdgeOptions options = getDefaultEdgeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
EdgeOptions options = getDefaultEdgeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void loggingPreferences() {
EdgeOptions options = getDefaultEdgeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
EdgeDriverService service =
new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getEdgeLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermissions() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new EdgeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((EdgeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((EdgeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
EdgeDriver driver = new EdgeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
logs = driver.get_log("browser")
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_edge_options()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = get_default_edge_options()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(edge_bin):
options = get_default_edge_options()
options.binary_location = edge_bin
driver = webdriver.Edge(options=options)
driver.quit()
def test_add_extension():
options = get_default_edge_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Edge(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_edge_options()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_edge_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.EdgeService(log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.EdgeService(log_output=subprocess.STDOUT)
driver = webdriver.Edge(service=service)
out, err = capfd.readouterr()
assert "Starting Microsoft Edge WebDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)
driver = webdriver.Edge(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
with open(log_path, 'r') as f:
assert expected in f.read()
driver.quit()
def test_set_network_conditions():
driver = webdriver.Edge()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Edge()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Edge()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Edge()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_edge_options():
options = webdriver.EdgeOptions()
options.add_argument("--no-sandbox")
return options
logs = @driver.logs.get(:browser)
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.edge
options.binary = edge_location
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.edge
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :edge, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('msedgedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.edge
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :edge, service: service
}.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.edge(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :edge, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :edge
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :edge
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
service = Selenium::WebDriver::Service.edge
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['EDGEDRIVER_BIN'] = finder.driver_path
ENV['EDGE_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
Permissions
driver.setPermission("camera", "denied");
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class EdgeTest extends BaseTest {
@AfterEach
public void clearProperties() {
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
}
@Test
public void basicOptions() {
EdgeOptions options = getDefaultEdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = getDefaultEdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void setBrowserLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBinary(getEdgeLocation());
driver = new EdgeDriver(options);
}
@Test
public void extensionOptions() {
EdgeOptions options = getDefaultEdgeOptions();
Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
File extensionFilePath = new File(path.toUri());
options.addExtensions(extensionFilePath);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void excludeSwitches() {
EdgeOptions options = getDefaultEdgeOptions();
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void loggingPreferences() {
EdgeOptions options = getDefaultEdgeOptions();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);
driver = new EdgeDriver(options);
driver.get("https://www.selenium.dev");
LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
Assertions.assertFalse(logEntries.getAll().isEmpty());
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
EdgeDriverService service =
new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
File logLocation = getTempFile("configureDriverLogs", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
File logLocation = getTempFile("disableBuildChecks", ".log");
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service =
new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
String expected =
"[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getEdgeLocation() {
EdgeOptions options = getDefaultEdgeOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
return new File(finder.getBrowserPath());
}
@Test
public void setPermissions() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev");
driver.setPermission("camera", "denied");
// Verify the permission state is 'denied'
String script = "return navigator.permissions.query({ name: 'camera' })" +
" .then(permissionStatus => permissionStatus.state);";
String permissionState = (String) driver.executeScript(script);
Assertions.assertEquals("denied", permissionState);
driver.quit();
}
@Test
public void setNetworkConditions() {
driver = new EdgeDriver();
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.setOffline(false);
networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
networkConditions.setUploadThroughput(2000 * 1024 / 8); // 2000 kbps
((EdgeDriver) driver).setNetworkConditions(networkConditions);
driver.get("https://www.selenium.dev");
// Assert the network conditions are set as expected
ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
Assertions.assertAll(
() -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
() -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
() -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
() -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
);
((EdgeDriver) driver).deleteNetworkConditions();
driver.quit();
}
@Test
public void castFeatures() {
EdgeDriver driver = new EdgeDriver();
List<Map<String, String>> sinks = driver.getCastSinks();
if (!sinks.isEmpty()) {
String sinkName = sinks.get(0).get("name");
driver.startTabMirroring(sinkName);
driver.stopCasting(sinkName);
}
driver.quit();
}
@Test
public void getBrowserLogs() {
EdgeDriver driver = new EdgeDriver();
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
consoleLogButton.click();
LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
// Assert that at least one log contains the expected message
boolean logFound = false;
for (LogEntry log : logs) {
if (log.getMessage().contains("I am console error")) {
logFound = true;
break;
}
}
Assertions.assertTrue(logFound, "No matching log message found.");
driver.quit();
}
}
driver.set_permissions('camera', 'denied')
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_basic_options():
options = get_default_edge_options()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = get_default_edge_options()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_set_browser_location(edge_bin):
options = get_default_edge_options()
options.binary_location = edge_bin
driver = webdriver.Edge(options=options)
driver.quit()
def test_add_extension():
options = get_default_edge_options()
extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")
options.add_extension(extension_file_path)
driver = webdriver.Edge(options=options)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
driver.quit()
def test_keep_browser_open():
options = get_default_edge_options()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = get_default_edge_options()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.EdgeService(log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.EdgeService(log_output=subprocess.STDOUT)
driver = webdriver.Edge(service=service)
out, err = capfd.readouterr()
assert "Starting Microsoft Edge WebDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)
driver = webdriver.Edge(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
with open(log_path, 'r') as f:
assert expected in f.read()
driver.quit()
def test_set_network_conditions():
driver = webdriver.Edge()
network_conditions = {
"offline": False,
"latency": 20, # 20 ms of latency
"download_throughput": 2000 * 1024 / 8, # 2000 kbps
"upload_throughput": 2000 * 1024 / 8, # 2000 kbps
}
driver.set_network_conditions(**network_conditions)
driver.get("https://www.selenium.dev")
# check whether the network conditions are set
assert driver.get_network_conditions() == network_conditions
driver.quit()
def test_set_permissions():
driver = webdriver.Edge()
driver.get('https://www.selenium.dev')
driver.set_permissions('camera', 'denied')
assert get_permission_state(driver, 'camera') == 'denied'
driver.quit()
def get_permission_state(driver, name):
"""Helper function to query the permission state."""
script = """
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""
return driver.execute_async_script(script, name)
def test_cast_features():
driver = webdriver.Edge()
try:
sinks = driver.get_sinks()
if sinks:
sink_name = sinks[0]['name']
driver.start_tab_mirroring(sink_name)
driver.stop_casting(sink_name)
else:
pytest.skip("No available Cast sinks to test with.")
finally:
driver.quit()
def test_get_browser_logs():
driver = webdriver.Edge()
driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
driver.find_element(By.ID, "consoleError").click()
logs = driver.get_log("browser")
# Assert that at least one log contains the expected message
assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
driver.quit()
def get_default_edge_options():
options = webdriver.EdgeOptions()
options.add_argument("--no-sandbox")
return options
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge
options.args << '--start-maximized'
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.edge
options.binary = edge_location
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add extensions' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
options = Selenium::WebDriver::Options.edge
options.add_extension(extension_file_path)
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.selenium.dev/selenium/web/blank.html')
injected = @driver.find_element(:id, 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'disable-popup-blocking'
@driver = Selenium::WebDriver.for :edge, options: options
end
end
describe 'Service' do
let(:file_name) { File.expand_path('msedgedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.edge
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :edge, service: service
}.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.edge(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :edge, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
describe 'Special Features' do
it 'casts' do
@driver = Selenium::WebDriver.for :edge
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
end
it 'gets and sets network conditions' do
@driver = Selenium::WebDriver.for :edge
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
expect(@driver.network_conditions).to eq(
'offline' => false,
'latency' => 100,
'download_throughput' => 200,
'upload_throughput' => 200)
end
it 'gets the browser logs' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
sleep 1
logs = @driver.logs.get(:browser)
expect(logs.first.message).to include 'Failed to load resource'
end
it 'sets permissions' do
@driver = Selenium::WebDriver.for :edge
@driver.navigate.to 'https://www.selenium.dev/selenium/web/'
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
expect(permission('camera')).to eq('denied')
expect(permission('clipboard-read')).to eq('denied')
expect(permission('clipboard-write')).to eq('prompt')
end
end
def driver_finder
options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
service = Selenium::WebDriver::Service.edge
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['EDGEDRIVER_BIN'] = finder.driver_path
ENV['EDGE_BIN'] = finder.browser_path
end
def permission(name)
@driver.execute_async_script('callback = arguments[arguments.length - 1];' \
'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
end
end
DevTools
See the [Chrome DevTools] section for more information about using DevTools in Edge
3 - Funcionalidade específica do Firefox
Por omissão, Selenium 4 é compatível com Firefox 78 ou superior. Recomendamos que use sempre a versão mais recente do geckodriver.
Opções
Capacidades comuns a todos os navegadores estão descritas na página Opções.
Capacidades únicas ao Firefox podem ser encontradas na página da Mozilla para firefoxOptions
Este é um exemplo de como iniciar uma sessão Firefox com um conjunto de opções básicas:
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class FirefoxTest extends BaseTest {
private FirefoxDriver driver;
@AfterEach
public void clearProperties() {
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void arguments() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
@Test
@DisabledOnOs(OS.WINDOWS)
public void setBrowserLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBinary(getFirefoxLocation());
driver = new FirefoxDriver(options);
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogFile(logLocation).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogOutput(System.out).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
File logLocation = getTempFile("geckodriver-", "log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());
FirefoxDriverService service =
new GeckoDriverService.Builder().withTruncatedLogs(false).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() {
File profileDirectory = getTempDirectory("profile-");
FirefoxDriverService service =
new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = startFirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
private Path getFirefoxLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
return Path.of(finder.getBrowserPath());
}
@Test
public void fullPageScreenshot() throws Exception {
driver = startFirefoxDriver();
driver.get("https://www.selenium.dev");
File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);
File targetFile = new File("full_page_screenshot.png");
Files.move(screenshot.toPath(), targetFile.toPath());
// Verify the screenshot file exists
Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
Files.deleteIfExists(targetFile.toPath());
driver.quit();
}
@Test
public void setContext() {
driver = startFirefoxDriver();
((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
driver.executeScript("console.log('Inside Chrome context');");
// Verify the context is back to "content"
Assertions.assertEquals(
FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
"The context should be 'chrome'"
);
driver.quit();
}
@Test
public void firefoxProfile() {
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
profile.setPreference("javascript.enabled", "False");
options.setProfile(profile);
driver = new FirefoxDriver(options);
driver.quit();
}
}
options = webdriver.FirefoxOptions()
driver = webdriver.Firefox(options=options)
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_arguments():
options = webdriver.FirefoxOptions()
options.add_argument("-headless")
driver = webdriver.Firefox(options=options)
driver.quit()
def test_set_browser_location(firefox_bin):
options = webdriver.FirefoxOptions()
options.binary_location = firefox_bin
driver = webdriver.Firefox(options=options)
driver.quit()
def test_log_to_file(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
driver.get("https://www.selenium.dev")
with open(log_path, 'r') as fp:
assert "geckodriver INFO Listening on" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.FirefoxService(log_output=subprocess.STDOUT)
driver = webdriver.Firefox(service=service)
out, err = capfd.readouterr()
assert "geckodriver INFO Listening on" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert '\tDEBUG' in f.read()
driver.quit()
def test_log_truncation(log_path):
service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert ' ... ' not in f.read()
driver.quit()
def test_profile_location(temp_dir):
service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])
driver = webdriver.Firefox(service=service)
profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]
assert profile_name in os.listdir(temp_dir)
driver.quit()
def test_install_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
driver.install_addon(addon_path_xpi)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
id = driver.install_addon(addon_path_xpi)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
driver = firefox_driver
driver.install_addon(addon_path_dir, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
driver = firefox_driver
driver.install_addon(addon_path_dir_slash, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_full_page_screenshot(firefox_driver):
driver = firefox_driver
driver.get("https://www.selenium.dev")
driver.save_full_page_screenshot("full_page_screenshot.png")
assert os.path.exists("full_page_screenshot.png")
driver.quit()
def test_set_context(firefox_driver):
driver = firefox_driver
with driver.context(driver.CONTEXT_CHROME):
driver.execute_script("console.log('Inside Chrome context');")
# Check if the context is back to content
assert driver.execute("GET_CONTEXT")["value"] == "content"
def test_firefox_profile():
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
options = Options()
firefox_profile = FirefoxProfile()
firefox_profile.set_preference("javascript.enabled", False)
options.profile = firefox_profile
driver = webdriver.Firefox(options=options)
driver.quit()
var options = new FirefoxOptions();
driver = new FirefoxDriver(options);
Show full example
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class FirefoxTest
{
private FirefoxDriver driver;
private string _logLocation;
private string _tempPath;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
if (_tempPath != null && File.Exists(_tempPath))
{
File.Delete(_tempPath);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new FirefoxOptions();
options.AddArgument("-headless");
driver = new FirefoxDriver(options);
}
[TestMethod]
public void SetBinary()
{
var options = new FirefoxOptions();
options.BinaryLocation = GetFirefoxLocation();
driver = new FirefoxDriver(options);
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToFile()
{
var service = FirefoxDriverService.CreateDefaultService();
//service.LogFile = _logLocation
driver = new FirefoxDriver(service);
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("geckodriver INFO Listening on")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = FirefoxDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new FirefoxDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("geckodriver INFO Listening on"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("You can set it, just can't see it")]
public void LogsLevel()
{
var service = FirefoxDriverService.CreateDefaultService();
//service.LogFile = _logLocation
service.LogLevel = FirefoxDriverLogLevel.Debug;
driver = new FirefoxDriver(service);
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Marionette\tDEBUG")));
}
[TestMethod]
[Ignore("Not implemented")]
public void StopsTruncatingLogs()
{
var service = FirefoxDriverService.CreateDefaultService();
//service.TruncateLogs = false;
service.LogLevel = FirefoxDriverLogLevel.Debug;
driver = new FirefoxDriver(service);
var lines = File.ReadLines(GetLogLocation());
Assert.IsNull(lines.FirstOrDefault(line => line.Contains(" ... ")));
}
[TestMethod]
[Ignore("Not implemented")]
public void SetProfileLocation()
{
var service = FirefoxDriverService.CreateDefaultService();
// service.ProfileRoot = GetTempDirectory();
driver = new FirefoxDriver(service);
string profile = (string)driver.Capabilities.GetCapability("moz:profile");
string[] directories = profile.Split("/");
var dirName = directories.Last();
Assert.AreEqual(GetTempDirectory() + "/" + dirName, profile);
}
[TestMethod]
public void InstallAddon()
{
SetWaitingDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void UnInstallAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
string extensionId = driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.UninstallAddOn(extensionId);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
Assert.AreEqual(driver.FindElements(By.Id("webextensions-selenium-example")).Count, 0);
}
[TestMethod]
public void InstallUnsignedAddon()
{
SetWaitingDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionDirPath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example/");
driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
private string GetLogLocation()
{
if (_logLocation != null && !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private string GetTempDirectory()
{
if (_tempPath != null && !File.Exists(_tempPath))
{
_tempPath = Path.GetTempPath();
}
return _tempPath;
}
private void SetWaitingDriver()
{
driver = new FirefoxDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2);
}
private static string GetFirefoxLocation()
{
var options = new FirefoxOptions()
{
BrowserVersion = "stable"
};
return new DriverFinder(options).GetBrowserPath();
}
}
}
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox
options.args << '-headless'
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.firefox
options.binary = firefox_location
@driver = Selenium::WebDriver.for :firefox, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('geckodriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.rm_rf(root_directory)
end
it 'logs to file' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
end
it 'logs to console' do
service = Selenium::WebDriver::Service.firefox
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :firefox, service: service
}.to output(/geckodriver INFO Listening on/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
service.args += %w[--log debug]
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).to eq true
end
it 'stops truncating log lines' do
service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])
service.args << '--log-no-truncate'
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
end
it 'sets default profile location' do
service = Selenium::WebDriver::Service.firefox
service.args += ['--profile-root', root_directory]
@driver = Selenium::WebDriver.for :firefox, service: service
profile_location = Dir.new(@driver.capabilities['moz:profile'])
expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
end
end
describe 'Features' do
let(:driver) { start_firefox }
it 'installs addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'takes full page screenshot' do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
Dir.mktmpdir('screenshot_test') do |dir|
screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))
expect(screenshot).to be_a File
end
end
it 'sets the context' do
driver.context = 'content'
expect(driver.context).to eq 'content'
end
end
describe 'Profile' do
it 'creates a new profile' do
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.dir'] = '/tmp/webdriver-downloads'
options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
expect(options.profile).to eq(profile)
end
end
def driver_finder
options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
service = Selenium::WebDriver::Service.firefox
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['GECKODRIVER_BIN'] = finder.driver_path
ENV['FIREFOX_BIN'] = finder.browser_path
end
end
driver = new Builder()
.forBrowser(Browser.FIREFOX)
.setFirefoxOptions(options)
.build();
Show full example
const {Browser, Builder} = require('selenium-webdriver');
const firefox = require('selenium-webdriver/firefox');
describe('Open Firefox', function () {
let driver;
before(async function () {
let options = new firefox.Options();
driver = new Builder()
.forBrowser(Browser.FIREFOX)
.setFirefoxOptions(options)
.build();
});
after(async () => await driver.quit());
it('Basic Firefox test', async function () {
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
});
});
Alguns exemplos de uso com capacidades diferentes:
Argumentos
O parametro args
é usado para indicar uma lista de opções ao iniciar o navegador.
Opções mais frequentes incluem -headless
e "-profile", "/path/to/profile"
Adicione uma opção:
options.addArguments("-headless");
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class FirefoxTest extends BaseTest {
private FirefoxDriver driver;
@AfterEach
public void clearProperties() {
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void arguments() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
@Test
@DisabledOnOs(OS.WINDOWS)
public void setBrowserLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBinary(getFirefoxLocation());
driver = new FirefoxDriver(options);
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogFile(logLocation).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogOutput(System.out).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
File logLocation = getTempFile("geckodriver-", "log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());
FirefoxDriverService service =
new GeckoDriverService.Builder().withTruncatedLogs(false).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() {
File profileDirectory = getTempDirectory("profile-");
FirefoxDriverService service =
new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = startFirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
private Path getFirefoxLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
return Path.of(finder.getBrowserPath());
}
@Test
public void fullPageScreenshot() throws Exception {
driver = startFirefoxDriver();
driver.get("https://www.selenium.dev");
File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);
File targetFile = new File("full_page_screenshot.png");
Files.move(screenshot.toPath(), targetFile.toPath());
// Verify the screenshot file exists
Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
Files.deleteIfExists(targetFile.toPath());
driver.quit();
}
@Test
public void setContext() {
driver = startFirefoxDriver();
((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
driver.executeScript("console.log('Inside Chrome context');");
// Verify the context is back to "content"
Assertions.assertEquals(
FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
"The context should be 'chrome'"
);
driver.quit();
}
@Test
public void firefoxProfile() {
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
profile.setPreference("javascript.enabled", "False");
options.setProfile(profile);
driver = new FirefoxDriver(options);
driver.quit();
}
}
options.add_argument("-headless")
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_arguments():
options = webdriver.FirefoxOptions()
options.add_argument("-headless")
driver = webdriver.Firefox(options=options)
driver.quit()
def test_set_browser_location(firefox_bin):
options = webdriver.FirefoxOptions()
options.binary_location = firefox_bin
driver = webdriver.Firefox(options=options)
driver.quit()
def test_log_to_file(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
driver.get("https://www.selenium.dev")
with open(log_path, 'r') as fp:
assert "geckodriver INFO Listening on" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.FirefoxService(log_output=subprocess.STDOUT)
driver = webdriver.Firefox(service=service)
out, err = capfd.readouterr()
assert "geckodriver INFO Listening on" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert '\tDEBUG' in f.read()
driver.quit()
def test_log_truncation(log_path):
service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert ' ... ' not in f.read()
driver.quit()
def test_profile_location(temp_dir):
service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])
driver = webdriver.Firefox(service=service)
profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]
assert profile_name in os.listdir(temp_dir)
driver.quit()
def test_install_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
driver.install_addon(addon_path_xpi)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
id = driver.install_addon(addon_path_xpi)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
driver = firefox_driver
driver.install_addon(addon_path_dir, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
driver = firefox_driver
driver.install_addon(addon_path_dir_slash, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_full_page_screenshot(firefox_driver):
driver = firefox_driver
driver.get("https://www.selenium.dev")
driver.save_full_page_screenshot("full_page_screenshot.png")
assert os.path.exists("full_page_screenshot.png")
driver.quit()
def test_set_context(firefox_driver):
driver = firefox_driver
with driver.context(driver.CONTEXT_CHROME):
driver.execute_script("console.log('Inside Chrome context');")
# Check if the context is back to content
assert driver.execute("GET_CONTEXT")["value"] == "content"
def test_firefox_profile():
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
options = Options()
firefox_profile = FirefoxProfile()
firefox_profile.set_preference("javascript.enabled", False)
options.profile = firefox_profile
driver = webdriver.Firefox(options=options)
driver.quit()
options.AddArgument("-headless");
Show full example
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class FirefoxTest
{
private FirefoxDriver driver;
private string _logLocation;
private string _tempPath;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
if (_tempPath != null && File.Exists(_tempPath))
{
File.Delete(_tempPath);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new FirefoxOptions();
options.AddArgument("-headless");
driver = new FirefoxDriver(options);
}
[TestMethod]
public void SetBinary()
{
var options = new FirefoxOptions();
options.BinaryLocation = GetFirefoxLocation();
driver = new FirefoxDriver(options);
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToFile()
{
var service = FirefoxDriverService.CreateDefaultService();
//service.LogFile = _logLocation
driver = new FirefoxDriver(service);
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("geckodriver INFO Listening on")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = FirefoxDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new FirefoxDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("geckodriver INFO Listening on"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("You can set it, just can't see it")]
public void LogsLevel()
{
var service = FirefoxDriverService.CreateDefaultService();
//service.LogFile = _logLocation
service.LogLevel = FirefoxDriverLogLevel.Debug;
driver = new FirefoxDriver(service);
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Marionette\tDEBUG")));
}
[TestMethod]
[Ignore("Not implemented")]
public void StopsTruncatingLogs()
{
var service = FirefoxDriverService.CreateDefaultService();
//service.TruncateLogs = false;
service.LogLevel = FirefoxDriverLogLevel.Debug;
driver = new FirefoxDriver(service);
var lines = File.ReadLines(GetLogLocation());
Assert.IsNull(lines.FirstOrDefault(line => line.Contains(" ... ")));
}
[TestMethod]
[Ignore("Not implemented")]
public void SetProfileLocation()
{
var service = FirefoxDriverService.CreateDefaultService();
// service.ProfileRoot = GetTempDirectory();
driver = new FirefoxDriver(service);
string profile = (string)driver.Capabilities.GetCapability("moz:profile");
string[] directories = profile.Split("/");
var dirName = directories.Last();
Assert.AreEqual(GetTempDirectory() + "/" + dirName, profile);
}
[TestMethod]
public void InstallAddon()
{
SetWaitingDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void UnInstallAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
string extensionId = driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.UninstallAddOn(extensionId);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
Assert.AreEqual(driver.FindElements(By.Id("webextensions-selenium-example")).Count, 0);
}
[TestMethod]
public void InstallUnsignedAddon()
{
SetWaitingDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionDirPath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example/");
driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
private string GetLogLocation()
{
if (_logLocation != null && !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private string GetTempDirectory()
{
if (_tempPath != null && !File.Exists(_tempPath))
{
_tempPath = Path.GetTempPath();
}
return _tempPath;
}
private void SetWaitingDriver()
{
driver = new FirefoxDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2);
}
private static string GetFirefoxLocation()
{
var options = new FirefoxOptions()
{
BrowserVersion = "stable"
};
return new DriverFinder(options).GetBrowserPath();
}
}
}
options.args << '-headless'
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox
options.args << '-headless'
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.firefox
options.binary = firefox_location
@driver = Selenium::WebDriver.for :firefox, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('geckodriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.rm_rf(root_directory)
end
it 'logs to file' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
end
it 'logs to console' do
service = Selenium::WebDriver::Service.firefox
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :firefox, service: service
}.to output(/geckodriver INFO Listening on/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
service.args += %w[--log debug]
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).to eq true
end
it 'stops truncating log lines' do
service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])
service.args << '--log-no-truncate'
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
end
it 'sets default profile location' do
service = Selenium::WebDriver::Service.firefox
service.args += ['--profile-root', root_directory]
@driver = Selenium::WebDriver.for :firefox, service: service
profile_location = Dir.new(@driver.capabilities['moz:profile'])
expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
end
end
describe 'Features' do
let(:driver) { start_firefox }
it 'installs addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'takes full page screenshot' do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
Dir.mktmpdir('screenshot_test') do |dir|
screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))
expect(screenshot).to be_a File
end
end
it 'sets the context' do
driver.context = 'content'
expect(driver.context).to eq 'content'
end
end
describe 'Profile' do
it 'creates a new profile' do
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.dir'] = '/tmp/webdriver-downloads'
options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
expect(options.profile).to eq(profile)
end
end
def driver_finder
options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
service = Selenium::WebDriver::Service.firefox
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['GECKODRIVER_BIN'] = finder.driver_path
ENV['FIREFOX_BIN'] = finder.browser_path
end
end
.setFirefoxOptions(options.addArguments('--headless'))
Show full example
const {Browser, By, Builder} = require('selenium-webdriver');
const Firefox = require('selenium-webdriver/firefox');
const options = new Firefox.Options();
const path = require('path');
const assert = require("assert");
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = new Builder()
.forBrowser(Browser.FIREFOX)
.setFirefoxOptions(options.addArguments('--headless'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Should be able to add extension', async function () {
const xpiPath = path.resolve('./test/resources/extensions/selenium-example.xpi')
let driver = new Builder()
.forBrowser(Browser.FIREFOX)
.build()
let id = await driver.installAddon(xpiPath);
await driver.uninstallAddon(id);
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
const ele = await driver.findElements(By.id("webextensions-selenium-example"));
assert.equal(ele.length, 0);
await driver.quit();
});
it('Should be able to install unsigned addon', async function () {
const xpiPath = path.resolve('./test/resources/extensions/selenium-example')
let driver = new Builder()
.forBrowser(Browser.FIREFOX)
.build()
let id = await driver.installAddon(xpiPath, true);
await driver.uninstallAddon(id);
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
const ele = await driver.findElements(By.id("webextensions-selenium-example"));
assert.equal(ele.length, 0);
await driver.quit();
});
});
Iniciar navegador numa localização específica
O parametro binary
é usado contendo o caminho para uma localização específica do navegador.
Como exemplo, pode usar este parametro para indicar ao geckodriver a versão Firefox Nightly ao invés da
versão de produção, quando ambas versões estão presentes no seu computador.
Adicionar uma localização:
options.setBinary(getFirefoxLocation());
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class FirefoxTest extends BaseTest {
private FirefoxDriver driver;
@AfterEach
public void clearProperties() {
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void arguments() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
@Test
@DisabledOnOs(OS.WINDOWS)
public void setBrowserLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBinary(getFirefoxLocation());
driver = new FirefoxDriver(options);
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogFile(logLocation).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogOutput(System.out).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
File logLocation = getTempFile("geckodriver-", "log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());
FirefoxDriverService service =
new GeckoDriverService.Builder().withTruncatedLogs(false).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() {
File profileDirectory = getTempDirectory("profile-");
FirefoxDriverService service =
new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = startFirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
private Path getFirefoxLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
return Path.of(finder.getBrowserPath());
}
@Test
public void fullPageScreenshot() throws Exception {
driver = startFirefoxDriver();
driver.get("https://www.selenium.dev");
File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);
File targetFile = new File("full_page_screenshot.png");
Files.move(screenshot.toPath(), targetFile.toPath());
// Verify the screenshot file exists
Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
Files.deleteIfExists(targetFile.toPath());
driver.quit();
}
@Test
public void setContext() {
driver = startFirefoxDriver();
((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
driver.executeScript("console.log('Inside Chrome context');");
// Verify the context is back to "content"
Assertions.assertEquals(
FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
"The context should be 'chrome'"
);
driver.quit();
}
@Test
public void firefoxProfile() {
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
profile.setPreference("javascript.enabled", "False");
options.setProfile(profile);
driver = new FirefoxDriver(options);
driver.quit();
}
}
options.binary_location = firefox_bin
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_arguments():
options = webdriver.FirefoxOptions()
options.add_argument("-headless")
driver = webdriver.Firefox(options=options)
driver.quit()
def test_set_browser_location(firefox_bin):
options = webdriver.FirefoxOptions()
options.binary_location = firefox_bin
driver = webdriver.Firefox(options=options)
driver.quit()
def test_log_to_file(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
driver.get("https://www.selenium.dev")
with open(log_path, 'r') as fp:
assert "geckodriver INFO Listening on" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.FirefoxService(log_output=subprocess.STDOUT)
driver = webdriver.Firefox(service=service)
out, err = capfd.readouterr()
assert "geckodriver INFO Listening on" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert '\tDEBUG' in f.read()
driver.quit()
def test_log_truncation(log_path):
service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert ' ... ' not in f.read()
driver.quit()
def test_profile_location(temp_dir):
service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])
driver = webdriver.Firefox(service=service)
profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]
assert profile_name in os.listdir(temp_dir)
driver.quit()
def test_install_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
driver.install_addon(addon_path_xpi)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
id = driver.install_addon(addon_path_xpi)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
driver = firefox_driver
driver.install_addon(addon_path_dir, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
driver = firefox_driver
driver.install_addon(addon_path_dir_slash, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_full_page_screenshot(firefox_driver):
driver = firefox_driver
driver.get("https://www.selenium.dev")
driver.save_full_page_screenshot("full_page_screenshot.png")
assert os.path.exists("full_page_screenshot.png")
driver.quit()
def test_set_context(firefox_driver):
driver = firefox_driver
with driver.context(driver.CONTEXT_CHROME):
driver.execute_script("console.log('Inside Chrome context');")
# Check if the context is back to content
assert driver.execute("GET_CONTEXT")["value"] == "content"
def test_firefox_profile():
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
options = Options()
firefox_profile = FirefoxProfile()
firefox_profile.set_preference("javascript.enabled", False)
options.profile = firefox_profile
driver = webdriver.Firefox(options=options)
driver.quit()
options.BinaryLocation = GetFirefoxLocation();
Show full example
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class FirefoxTest
{
private FirefoxDriver driver;
private string _logLocation;
private string _tempPath;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
if (_tempPath != null && File.Exists(_tempPath))
{
File.Delete(_tempPath);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new FirefoxOptions();
options.AddArgument("-headless");
driver = new FirefoxDriver(options);
}
[TestMethod]
public void SetBinary()
{
var options = new FirefoxOptions();
options.BinaryLocation = GetFirefoxLocation();
driver = new FirefoxDriver(options);
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToFile()
{
var service = FirefoxDriverService.CreateDefaultService();
//service.LogFile = _logLocation
driver = new FirefoxDriver(service);
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("geckodriver INFO Listening on")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = FirefoxDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new FirefoxDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("geckodriver INFO Listening on"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("You can set it, just can't see it")]
public void LogsLevel()
{
var service = FirefoxDriverService.CreateDefaultService();
//service.LogFile = _logLocation
service.LogLevel = FirefoxDriverLogLevel.Debug;
driver = new FirefoxDriver(service);
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Marionette\tDEBUG")));
}
[TestMethod]
[Ignore("Not implemented")]
public void StopsTruncatingLogs()
{
var service = FirefoxDriverService.CreateDefaultService();
//service.TruncateLogs = false;
service.LogLevel = FirefoxDriverLogLevel.Debug;
driver = new FirefoxDriver(service);
var lines = File.ReadLines(GetLogLocation());
Assert.IsNull(lines.FirstOrDefault(line => line.Contains(" ... ")));
}
[TestMethod]
[Ignore("Not implemented")]
public void SetProfileLocation()
{
var service = FirefoxDriverService.CreateDefaultService();
// service.ProfileRoot = GetTempDirectory();
driver = new FirefoxDriver(service);
string profile = (string)driver.Capabilities.GetCapability("moz:profile");
string[] directories = profile.Split("/");
var dirName = directories.Last();
Assert.AreEqual(GetTempDirectory() + "/" + dirName, profile);
}
[TestMethod]
public void InstallAddon()
{
SetWaitingDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void UnInstallAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
string extensionId = driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.UninstallAddOn(extensionId);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
Assert.AreEqual(driver.FindElements(By.Id("webextensions-selenium-example")).Count, 0);
}
[TestMethod]
public void InstallUnsignedAddon()
{
SetWaitingDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionDirPath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example/");
driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
private string GetLogLocation()
{
if (_logLocation != null && !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private string GetTempDirectory()
{
if (_tempPath != null && !File.Exists(_tempPath))
{
_tempPath = Path.GetTempPath();
}
return _tempPath;
}
private void SetWaitingDriver()
{
driver = new FirefoxDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2);
}
private static string GetFirefoxLocation()
{
var options = new FirefoxOptions()
{
BrowserVersion = "stable"
};
return new DriverFinder(options).GetBrowserPath();
}
}
}
options.binary = firefox_location
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox
options.args << '-headless'
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.firefox
options.binary = firefox_location
@driver = Selenium::WebDriver.for :firefox, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('geckodriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.rm_rf(root_directory)
end
it 'logs to file' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
end
it 'logs to console' do
service = Selenium::WebDriver::Service.firefox
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :firefox, service: service
}.to output(/geckodriver INFO Listening on/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
service.args += %w[--log debug]
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).to eq true
end
it 'stops truncating log lines' do
service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])
service.args << '--log-no-truncate'
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
end
it 'sets default profile location' do
service = Selenium::WebDriver::Service.firefox
service.args += ['--profile-root', root_directory]
@driver = Selenium::WebDriver.for :firefox, service: service
profile_location = Dir.new(@driver.capabilities['moz:profile'])
expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
end
end
describe 'Features' do
let(:driver) { start_firefox }
it 'installs addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'takes full page screenshot' do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
Dir.mktmpdir('screenshot_test') do |dir|
screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))
expect(screenshot).to be_a File
end
end
it 'sets the context' do
driver.context = 'content'
expect(driver.context).to eq 'content'
end
end
describe 'Profile' do
it 'creates a new profile' do
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.dir'] = '/tmp/webdriver-downloads'
options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
expect(options.profile).to eq(profile)
end
end
def driver_finder
options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
service = Selenium::WebDriver::Service.firefox
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['GECKODRIVER_BIN'] = finder.driver_path
ENV['FIREFOX_BIN'] = finder.browser_path
end
end
Perfis
Existem várias formas de trabalhar com perfis Firefox
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
profile.setPreference("javascript.enabled", "False");
options.setProfile(profile);
driver = new FirefoxDriver(options);
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class FirefoxTest extends BaseTest {
private FirefoxDriver driver;
@AfterEach
public void clearProperties() {
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void arguments() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
@Test
@DisabledOnOs(OS.WINDOWS)
public void setBrowserLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBinary(getFirefoxLocation());
driver = new FirefoxDriver(options);
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogFile(logLocation).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogOutput(System.out).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
File logLocation = getTempFile("geckodriver-", "log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());
FirefoxDriverService service =
new GeckoDriverService.Builder().withTruncatedLogs(false).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() {
File profileDirectory = getTempDirectory("profile-");
FirefoxDriverService service =
new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = startFirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
private Path getFirefoxLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
return Path.of(finder.getBrowserPath());
}
@Test
public void fullPageScreenshot() throws Exception {
driver = startFirefoxDriver();
driver.get("https://www.selenium.dev");
File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);
File targetFile = new File("full_page_screenshot.png");
Files.move(screenshot.toPath(), targetFile.toPath());
// Verify the screenshot file exists
Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
Files.deleteIfExists(targetFile.toPath());
driver.quit();
}
@Test
public void setContext() {
driver = startFirefoxDriver();
((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
driver.executeScript("console.log('Inside Chrome context');");
// Verify the context is back to "content"
Assertions.assertEquals(
FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
"The context should be 'chrome'"
);
driver.quit();
}
@Test
public void firefoxProfile() {
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
profile.setPreference("javascript.enabled", "False");
options.setProfile(profile);
driver = new FirefoxDriver(options);
driver.quit();
}
}
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
options = Options()
firefox_profile = FirefoxProfile()
firefox_profile.set_preference("javascript.enabled", False)
options.profile = firefox_profile
driver = webdriver.Firefox(options=options)
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_arguments():
options = webdriver.FirefoxOptions()
options.add_argument("-headless")
driver = webdriver.Firefox(options=options)
driver.quit()
def test_set_browser_location(firefox_bin):
options = webdriver.FirefoxOptions()
options.binary_location = firefox_bin
driver = webdriver.Firefox(options=options)
driver.quit()
def test_log_to_file(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
driver.get("https://www.selenium.dev")
with open(log_path, 'r') as fp:
assert "geckodriver INFO Listening on" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.FirefoxService(log_output=subprocess.STDOUT)
driver = webdriver.Firefox(service=service)
out, err = capfd.readouterr()
assert "geckodriver INFO Listening on" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert '\tDEBUG' in f.read()
driver.quit()
def test_log_truncation(log_path):
service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert ' ... ' not in f.read()
driver.quit()
def test_profile_location(temp_dir):
service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])
driver = webdriver.Firefox(service=service)
profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]
assert profile_name in os.listdir(temp_dir)
driver.quit()
def test_install_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
driver.install_addon(addon_path_xpi)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
id = driver.install_addon(addon_path_xpi)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
driver = firefox_driver
driver.install_addon(addon_path_dir, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
driver = firefox_driver
driver.install_addon(addon_path_dir_slash, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_full_page_screenshot(firefox_driver):
driver = firefox_driver
driver.get("https://www.selenium.dev")
driver.save_full_page_screenshot("full_page_screenshot.png")
assert os.path.exists("full_page_screenshot.png")
driver.quit()
def test_set_context(firefox_driver):
driver = firefox_driver
with driver.context(driver.CONTEXT_CHROME):
driver.execute_script("console.log('Inside Chrome context');")
# Check if the context is back to content
assert driver.execute("GET_CONTEXT")["value"] == "content"
def test_firefox_profile():
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
options = Options()
firefox_profile = FirefoxProfile()
firefox_profile.set_preference("javascript.enabled", False)
options.profile = firefox_profile
driver = webdriver.Firefox(options=options)
driver.quit()
var options = new FirefoxOptions();
var profile = new FirefoxProfile();
options.Profile = profile;
var driver = new RemoteWebDriver(options);
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.dir'] = '/tmp/webdriver-downloads'
options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox
options.args << '-headless'
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.firefox
options.binary = firefox_location
@driver = Selenium::WebDriver.for :firefox, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('geckodriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.rm_rf(root_directory)
end
it 'logs to file' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
end
it 'logs to console' do
service = Selenium::WebDriver::Service.firefox
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :firefox, service: service
}.to output(/geckodriver INFO Listening on/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
service.args += %w[--log debug]
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).to eq true
end
it 'stops truncating log lines' do
service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])
service.args << '--log-no-truncate'
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
end
it 'sets default profile location' do
service = Selenium::WebDriver::Service.firefox
service.args += ['--profile-root', root_directory]
@driver = Selenium::WebDriver.for :firefox, service: service
profile_location = Dir.new(@driver.capabilities['moz:profile'])
expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
end
end
describe 'Features' do
let(:driver) { start_firefox }
it 'installs addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'takes full page screenshot' do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
Dir.mktmpdir('screenshot_test') do |dir|
screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))
expect(screenshot).to be_a File
end
end
it 'sets the context' do
driver.context = 'content'
expect(driver.context).to eq 'content'
end
end
describe 'Profile' do
it 'creates a new profile' do
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.dir'] = '/tmp/webdriver-downloads'
options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
expect(options.profile).to eq(profile)
end
end
def driver_finder
options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
service = Selenium::WebDriver::Service.firefox
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['GECKODRIVER_BIN'] = finder.driver_path
ENV['FIREFOX_BIN'] = finder.browser_path
end
end
const { Builder } = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const options = new firefox.Options();
let profile = '/path to custom profile';
options.setProfile(profile);
const driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build();
val options = FirefoxOptions()
options.profile = FirefoxProfile()
driver = RemoteWebDriver(options)
Note: Whether you create an empty FirefoxProfile
or point it to the directory of your own profile, Selenium
will create a temporary directory to store either the data of the new profile or a copy of your existing one. Every
time you run your program, a different temporary directory will be created. These directories are not cleaned up
explicitly by Selenium, they should eventually get removed by the operating system. However, if you want to remove
the copy manually (e.g. if your profile is large in size), the path of the copy is exposed by the FirefoxProfile
object. Check the language specific implementation to see how to retrieve that location.
If you want to use an existing Firefox profile, you can pass in the path to that profile. Please refer to the official Firefox documentation for instructions on how to find the directory of your profile.
Service
Service settings common to all browsers are described on the Service page.
Log output
Getting driver logs can be helpful for debugging various issues. The Service class lets you direct where the logs will go. Logging output is ignored unless the user directs it somewhere.
File output
To change the logging output to save to a specific file:
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogFile(logLocation).build();
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class FirefoxTest extends BaseTest {
private FirefoxDriver driver;
@AfterEach
public void clearProperties() {
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void arguments() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
@Test
@DisabledOnOs(OS.WINDOWS)
public void setBrowserLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBinary(getFirefoxLocation());
driver = new FirefoxDriver(options);
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogFile(logLocation).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogOutput(System.out).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
File logLocation = getTempFile("geckodriver-", "log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());
FirefoxDriverService service =
new GeckoDriverService.Builder().withTruncatedLogs(false).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() {
File profileDirectory = getTempDirectory("profile-");
FirefoxDriverService service =
new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = startFirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
private Path getFirefoxLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
return Path.of(finder.getBrowserPath());
}
@Test
public void fullPageScreenshot() throws Exception {
driver = startFirefoxDriver();
driver.get("https://www.selenium.dev");
File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);
File targetFile = new File("full_page_screenshot.png");
Files.move(screenshot.toPath(), targetFile.toPath());
// Verify the screenshot file exists
Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
Files.deleteIfExists(targetFile.toPath());
driver.quit();
}
@Test
public void setContext() {
driver = startFirefoxDriver();
((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
driver.executeScript("console.log('Inside Chrome context');");
// Verify the context is back to "content"
Assertions.assertEquals(
FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
"The context should be 'chrome'"
);
driver.quit();
}
@Test
public void firefoxProfile() {
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
profile.setPreference("javascript.enabled", "False");
options.setProfile(profile);
driver = new FirefoxDriver(options);
driver.quit();
}
}
Note: Java also allows setting file output by System Property:
Property key: GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY
Property value: String representing path to log file
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_arguments():
options = webdriver.FirefoxOptions()
options.add_argument("-headless")
driver = webdriver.Firefox(options=options)
driver.quit()
def test_set_browser_location(firefox_bin):
options = webdriver.FirefoxOptions()
options.binary_location = firefox_bin
driver = webdriver.Firefox(options=options)
driver.quit()
def test_log_to_file(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
driver.get("https://www.selenium.dev")
with open(log_path, 'r') as fp:
assert "geckodriver INFO Listening on" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.FirefoxService(log_output=subprocess.STDOUT)
driver = webdriver.Firefox(service=service)
out, err = capfd.readouterr()
assert "geckodriver INFO Listening on" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert '\tDEBUG' in f.read()
driver.quit()
def test_log_truncation(log_path):
service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert ' ... ' not in f.read()
driver.quit()
def test_profile_location(temp_dir):
service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])
driver = webdriver.Firefox(service=service)
profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]
assert profile_name in os.listdir(temp_dir)
driver.quit()
def test_install_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
driver.install_addon(addon_path_xpi)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
id = driver.install_addon(addon_path_xpi)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
driver = firefox_driver
driver.install_addon(addon_path_dir, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
driver = firefox_driver
driver.install_addon(addon_path_dir_slash, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_full_page_screenshot(firefox_driver):
driver = firefox_driver
driver.get("https://www.selenium.dev")
driver.save_full_page_screenshot("full_page_screenshot.png")
assert os.path.exists("full_page_screenshot.png")
driver.quit()
def test_set_context(firefox_driver):
driver = firefox_driver
with driver.context(driver.CONTEXT_CHROME):
driver.execute_script("console.log('Inside Chrome context');")
# Check if the context is back to content
assert driver.execute("GET_CONTEXT")["value"] == "content"
def test_firefox_profile():
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
options = Options()
firefox_profile = FirefoxProfile()
firefox_profile.set_preference("javascript.enabled", False)
options.profile = firefox_profile
driver = webdriver.Firefox(options=options)
driver.quit()
service.log = file_name
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox
options.args << '-headless'
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.firefox
options.binary = firefox_location
@driver = Selenium::WebDriver.for :firefox, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('geckodriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.rm_rf(root_directory)
end
it 'logs to file' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
end
it 'logs to console' do
service = Selenium::WebDriver::Service.firefox
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :firefox, service: service
}.to output(/geckodriver INFO Listening on/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
service.args += %w[--log debug]
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).to eq true
end
it 'stops truncating log lines' do
service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])
service.args << '--log-no-truncate'
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
end
it 'sets default profile location' do
service = Selenium::WebDriver::Service.firefox
service.args += ['--profile-root', root_directory]
@driver = Selenium::WebDriver.for :firefox, service: service
profile_location = Dir.new(@driver.capabilities['moz:profile'])
expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
end
end
describe 'Features' do
let(:driver) { start_firefox }
it 'installs addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'takes full page screenshot' do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
Dir.mktmpdir('screenshot_test') do |dir|
screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))
expect(screenshot).to be_a File
end
end
it 'sets the context' do
driver.context = 'content'
expect(driver.context).to eq 'content'
end
end
describe 'Profile' do
it 'creates a new profile' do
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.dir'] = '/tmp/webdriver-downloads'
options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
expect(options.profile).to eq(profile)
end
end
def driver_finder
options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
service = Selenium::WebDriver::Service.firefox
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['GECKODRIVER_BIN'] = finder.driver_path
ENV['FIREFOX_BIN'] = finder.browser_path
end
end
Console output
To change the logging output to display in the console:
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogOutput(System.out).build();
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class FirefoxTest extends BaseTest {
private FirefoxDriver driver;
@AfterEach
public void clearProperties() {
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void arguments() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
@Test
@DisabledOnOs(OS.WINDOWS)
public void setBrowserLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBinary(getFirefoxLocation());
driver = new FirefoxDriver(options);
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogFile(logLocation).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogOutput(System.out).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
File logLocation = getTempFile("geckodriver-", "log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());
FirefoxDriverService service =
new GeckoDriverService.Builder().withTruncatedLogs(false).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() {
File profileDirectory = getTempDirectory("profile-");
FirefoxDriverService service =
new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = startFirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
private Path getFirefoxLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
return Path.of(finder.getBrowserPath());
}
@Test
public void fullPageScreenshot() throws Exception {
driver = startFirefoxDriver();
driver.get("https://www.selenium.dev");
File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);
File targetFile = new File("full_page_screenshot.png");
Files.move(screenshot.toPath(), targetFile.toPath());
// Verify the screenshot file exists
Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
Files.deleteIfExists(targetFile.toPath());
driver.quit();
}
@Test
public void setContext() {
driver = startFirefoxDriver();
((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
driver.executeScript("console.log('Inside Chrome context');");
// Verify the context is back to "content"
Assertions.assertEquals(
FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
"The context should be 'chrome'"
);
driver.quit();
}
@Test
public void firefoxProfile() {
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
profile.setPreference("javascript.enabled", "False");
options.setProfile(profile);
driver = new FirefoxDriver(options);
driver.quit();
}
}
Note: Java also allows setting console output by System Property;
Property key: GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY
Property value: DriverService.LOG_STDOUT
or DriverService.LOG_STDERR
service = webdriver.FirefoxService(log_output=subprocess.STDOUT)
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_arguments():
options = webdriver.FirefoxOptions()
options.add_argument("-headless")
driver = webdriver.Firefox(options=options)
driver.quit()
def test_set_browser_location(firefox_bin):
options = webdriver.FirefoxOptions()
options.binary_location = firefox_bin
driver = webdriver.Firefox(options=options)
driver.quit()
def test_log_to_file(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
driver.get("https://www.selenium.dev")
with open(log_path, 'r') as fp:
assert "geckodriver INFO Listening on" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.FirefoxService(log_output=subprocess.STDOUT)
driver = webdriver.Firefox(service=service)
out, err = capfd.readouterr()
assert "geckodriver INFO Listening on" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert '\tDEBUG' in f.read()
driver.quit()
def test_log_truncation(log_path):
service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert ' ... ' not in f.read()
driver.quit()
def test_profile_location(temp_dir):
service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])
driver = webdriver.Firefox(service=service)
profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]
assert profile_name in os.listdir(temp_dir)
driver.quit()
def test_install_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
driver.install_addon(addon_path_xpi)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
id = driver.install_addon(addon_path_xpi)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
driver = firefox_driver
driver.install_addon(addon_path_dir, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
driver = firefox_driver
driver.install_addon(addon_path_dir_slash, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_full_page_screenshot(firefox_driver):
driver = firefox_driver
driver.get("https://www.selenium.dev")
driver.save_full_page_screenshot("full_page_screenshot.png")
assert os.path.exists("full_page_screenshot.png")
driver.quit()
def test_set_context(firefox_driver):
driver = firefox_driver
with driver.context(driver.CONTEXT_CHROME):
driver.execute_script("console.log('Inside Chrome context');")
# Check if the context is back to content
assert driver.execute("GET_CONTEXT")["value"] == "content"
def test_firefox_profile():
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
options = Options()
firefox_profile = FirefoxProfile()
firefox_profile.set_preference("javascript.enabled", False)
options.profile = firefox_profile
driver = webdriver.Firefox(options=options)
driver.quit()
service.log = $stdout
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox
options.args << '-headless'
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.firefox
options.binary = firefox_location
@driver = Selenium::WebDriver.for :firefox, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('geckodriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.rm_rf(root_directory)
end
it 'logs to file' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
end
it 'logs to console' do
service = Selenium::WebDriver::Service.firefox
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :firefox, service: service
}.to output(/geckodriver INFO Listening on/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
service.args += %w[--log debug]
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).to eq true
end
it 'stops truncating log lines' do
service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])
service.args << '--log-no-truncate'
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
end
it 'sets default profile location' do
service = Selenium::WebDriver::Service.firefox
service.args += ['--profile-root', root_directory]
@driver = Selenium::WebDriver.for :firefox, service: service
profile_location = Dir.new(@driver.capabilities['moz:profile'])
expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
end
end
describe 'Features' do
let(:driver) { start_firefox }
it 'installs addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'takes full page screenshot' do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
Dir.mktmpdir('screenshot_test') do |dir|
screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))
expect(screenshot).to be_a File
end
end
it 'sets the context' do
driver.context = 'content'
expect(driver.context).to eq 'content'
end
end
describe 'Profile' do
it 'creates a new profile' do
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.dir'] = '/tmp/webdriver-downloads'
options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
expect(options.profile).to eq(profile)
end
end
def driver_finder
options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
service = Selenium::WebDriver::Service.firefox
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['GECKODRIVER_BIN'] = finder.driver_path
ENV['FIREFOX_BIN'] = finder.browser_path
end
end
Log level
There are 7 available log levels: fatal
, error
, warn
, info
, config
, debug
, trace
.
If logging is specified the level defaults to info
.
Note that -v
is equivalent to -log debug
and -vv
is equivalent to log trace
,
so this examples is just for setting the log level generically:
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class FirefoxTest extends BaseTest {
private FirefoxDriver driver;
@AfterEach
public void clearProperties() {
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void arguments() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
@Test
@DisabledOnOs(OS.WINDOWS)
public void setBrowserLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBinary(getFirefoxLocation());
driver = new FirefoxDriver(options);
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogFile(logLocation).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogOutput(System.out).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
File logLocation = getTempFile("geckodriver-", "log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());
FirefoxDriverService service =
new GeckoDriverService.Builder().withTruncatedLogs(false).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() {
File profileDirectory = getTempDirectory("profile-");
FirefoxDriverService service =
new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = startFirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
private Path getFirefoxLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
return Path.of(finder.getBrowserPath());
}
@Test
public void fullPageScreenshot() throws Exception {
driver = startFirefoxDriver();
driver.get("https://www.selenium.dev");
File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);
File targetFile = new File("full_page_screenshot.png");
Files.move(screenshot.toPath(), targetFile.toPath());
// Verify the screenshot file exists
Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
Files.deleteIfExists(targetFile.toPath());
driver.quit();
}
@Test
public void setContext() {
driver = startFirefoxDriver();
((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
driver.executeScript("console.log('Inside Chrome context');");
// Verify the context is back to "content"
Assertions.assertEquals(
FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
"The context should be 'chrome'"
);
driver.quit();
}
@Test
public void firefoxProfile() {
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
profile.setPreference("javascript.enabled", "False");
options.setProfile(profile);
driver = new FirefoxDriver(options);
driver.quit();
}
}
Note: Java also allows setting log level by System Property:
Property key: GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY
Property value: String representation of FirefoxDriverLogLevel
enum
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_arguments():
options = webdriver.FirefoxOptions()
options.add_argument("-headless")
driver = webdriver.Firefox(options=options)
driver.quit()
def test_set_browser_location(firefox_bin):
options = webdriver.FirefoxOptions()
options.binary_location = firefox_bin
driver = webdriver.Firefox(options=options)
driver.quit()
def test_log_to_file(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
driver.get("https://www.selenium.dev")
with open(log_path, 'r') as fp:
assert "geckodriver INFO Listening on" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.FirefoxService(log_output=subprocess.STDOUT)
driver = webdriver.Firefox(service=service)
out, err = capfd.readouterr()
assert "geckodriver INFO Listening on" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert '\tDEBUG' in f.read()
driver.quit()
def test_log_truncation(log_path):
service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert ' ... ' not in f.read()
driver.quit()
def test_profile_location(temp_dir):
service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])
driver = webdriver.Firefox(service=service)
profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]
assert profile_name in os.listdir(temp_dir)
driver.quit()
def test_install_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
driver.install_addon(addon_path_xpi)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
id = driver.install_addon(addon_path_xpi)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
driver = firefox_driver
driver.install_addon(addon_path_dir, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
driver = firefox_driver
driver.install_addon(addon_path_dir_slash, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_full_page_screenshot(firefox_driver):
driver = firefox_driver
driver.get("https://www.selenium.dev")
driver.save_full_page_screenshot("full_page_screenshot.png")
assert os.path.exists("full_page_screenshot.png")
driver.quit()
def test_set_context(firefox_driver):
driver = firefox_driver
with driver.context(driver.CONTEXT_CHROME):
driver.execute_script("console.log('Inside Chrome context');")
# Check if the context is back to content
assert driver.execute("GET_CONTEXT")["value"] == "content"
def test_firefox_profile():
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
options = Options()
firefox_profile = FirefoxProfile()
firefox_profile.set_preference("javascript.enabled", False)
options.profile = firefox_profile
driver = webdriver.Firefox(options=options)
driver.quit()
service.args += %w[--log debug]
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox
options.args << '-headless'
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.firefox
options.binary = firefox_location
@driver = Selenium::WebDriver.for :firefox, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('geckodriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.rm_rf(root_directory)
end
it 'logs to file' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
end
it 'logs to console' do
service = Selenium::WebDriver::Service.firefox
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :firefox, service: service
}.to output(/geckodriver INFO Listening on/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
service.args += %w[--log debug]
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).to eq true
end
it 'stops truncating log lines' do
service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])
service.args << '--log-no-truncate'
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
end
it 'sets default profile location' do
service = Selenium::WebDriver::Service.firefox
service.args += ['--profile-root', root_directory]
@driver = Selenium::WebDriver.for :firefox, service: service
profile_location = Dir.new(@driver.capabilities['moz:profile'])
expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
end
end
describe 'Features' do
let(:driver) { start_firefox }
it 'installs addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'takes full page screenshot' do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
Dir.mktmpdir('screenshot_test') do |dir|
screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))
expect(screenshot).to be_a File
end
end
it 'sets the context' do
driver.context = 'content'
expect(driver.context).to eq 'content'
end
end
describe 'Profile' do
it 'creates a new profile' do
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.dir'] = '/tmp/webdriver-downloads'
options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
expect(options.profile).to eq(profile)
end
end
def driver_finder
options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
service = Selenium::WebDriver::Service.firefox
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['GECKODRIVER_BIN'] = finder.driver_path
ENV['FIREFOX_BIN'] = finder.browser_path
end
end
Truncated Logs
The driver logs everything that gets sent to it, including string representations of large binaries, so Firefox truncates lines by default. To turn off truncation:
FirefoxDriverService service =
new GeckoDriverService.Builder().withTruncatedLogs(false).build();
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class FirefoxTest extends BaseTest {
private FirefoxDriver driver;
@AfterEach
public void clearProperties() {
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void arguments() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
@Test
@DisabledOnOs(OS.WINDOWS)
public void setBrowserLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBinary(getFirefoxLocation());
driver = new FirefoxDriver(options);
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogFile(logLocation).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogOutput(System.out).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
File logLocation = getTempFile("geckodriver-", "log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());
FirefoxDriverService service =
new GeckoDriverService.Builder().withTruncatedLogs(false).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() {
File profileDirectory = getTempDirectory("profile-");
FirefoxDriverService service =
new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = startFirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
private Path getFirefoxLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
return Path.of(finder.getBrowserPath());
}
@Test
public void fullPageScreenshot() throws Exception {
driver = startFirefoxDriver();
driver.get("https://www.selenium.dev");
File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);
File targetFile = new File("full_page_screenshot.png");
Files.move(screenshot.toPath(), targetFile.toPath());
// Verify the screenshot file exists
Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
Files.deleteIfExists(targetFile.toPath());
driver.quit();
}
@Test
public void setContext() {
driver = startFirefoxDriver();
((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
driver.executeScript("console.log('Inside Chrome context');");
// Verify the context is back to "content"
Assertions.assertEquals(
FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
"The context should be 'chrome'"
);
driver.quit();
}
@Test
public void firefoxProfile() {
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
profile.setPreference("javascript.enabled", "False");
options.setProfile(profile);
driver = new FirefoxDriver(options);
driver.quit();
}
}
Note: Java also allows setting log level by System Property:
Property key: GeckoDriverService.GECKO_DRIVER_LOG_NO_TRUNCATE
Property value: "true"
or "false"
service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_arguments():
options = webdriver.FirefoxOptions()
options.add_argument("-headless")
driver = webdriver.Firefox(options=options)
driver.quit()
def test_set_browser_location(firefox_bin):
options = webdriver.FirefoxOptions()
options.binary_location = firefox_bin
driver = webdriver.Firefox(options=options)
driver.quit()
def test_log_to_file(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
driver.get("https://www.selenium.dev")
with open(log_path, 'r') as fp:
assert "geckodriver INFO Listening on" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.FirefoxService(log_output=subprocess.STDOUT)
driver = webdriver.Firefox(service=service)
out, err = capfd.readouterr()
assert "geckodriver INFO Listening on" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert '\tDEBUG' in f.read()
driver.quit()
def test_log_truncation(log_path):
service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert ' ... ' not in f.read()
driver.quit()
def test_profile_location(temp_dir):
service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])
driver = webdriver.Firefox(service=service)
profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]
assert profile_name in os.listdir(temp_dir)
driver.quit()
def test_install_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
driver.install_addon(addon_path_xpi)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
id = driver.install_addon(addon_path_xpi)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
driver = firefox_driver
driver.install_addon(addon_path_dir, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
driver = firefox_driver
driver.install_addon(addon_path_dir_slash, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_full_page_screenshot(firefox_driver):
driver = firefox_driver
driver.get("https://www.selenium.dev")
driver.save_full_page_screenshot("full_page_screenshot.png")
assert os.path.exists("full_page_screenshot.png")
driver.quit()
def test_set_context(firefox_driver):
driver = firefox_driver
with driver.context(driver.CONTEXT_CHROME):
driver.execute_script("console.log('Inside Chrome context');")
# Check if the context is back to content
assert driver.execute("GET_CONTEXT")["value"] == "content"
def test_firefox_profile():
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
options = Options()
firefox_profile = FirefoxProfile()
firefox_profile.set_preference("javascript.enabled", False)
options.profile = firefox_profile
driver = webdriver.Firefox(options=options)
driver.quit()
service.args << '--log-no-truncate'
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox
options.args << '-headless'
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.firefox
options.binary = firefox_location
@driver = Selenium::WebDriver.for :firefox, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('geckodriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.rm_rf(root_directory)
end
it 'logs to file' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
end
it 'logs to console' do
service = Selenium::WebDriver::Service.firefox
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :firefox, service: service
}.to output(/geckodriver INFO Listening on/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
service.args += %w[--log debug]
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).to eq true
end
it 'stops truncating log lines' do
service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])
service.args << '--log-no-truncate'
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
end
it 'sets default profile location' do
service = Selenium::WebDriver::Service.firefox
service.args += ['--profile-root', root_directory]
@driver = Selenium::WebDriver.for :firefox, service: service
profile_location = Dir.new(@driver.capabilities['moz:profile'])
expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
end
end
describe 'Features' do
let(:driver) { start_firefox }
it 'installs addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'takes full page screenshot' do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
Dir.mktmpdir('screenshot_test') do |dir|
screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))
expect(screenshot).to be_a File
end
end
it 'sets the context' do
driver.context = 'content'
expect(driver.context).to eq 'content'
end
end
describe 'Profile' do
it 'creates a new profile' do
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.dir'] = '/tmp/webdriver-downloads'
options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
expect(options.profile).to eq(profile)
end
end
def driver_finder
options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
service = Selenium::WebDriver::Service.firefox
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['GECKODRIVER_BIN'] = finder.driver_path
ENV['FIREFOX_BIN'] = finder.browser_path
end
end
Profile Root
The default directory for profiles is the system temporary directory. If you do not have access to that directory, or want profiles to be created some place specific, you can change the profile root directory:
FirefoxDriverService service =
new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class FirefoxTest extends BaseTest {
private FirefoxDriver driver;
@AfterEach
public void clearProperties() {
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void arguments() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
@Test
@DisabledOnOs(OS.WINDOWS)
public void setBrowserLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBinary(getFirefoxLocation());
driver = new FirefoxDriver(options);
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogFile(logLocation).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogOutput(System.out).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
File logLocation = getTempFile("geckodriver-", "log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());
FirefoxDriverService service =
new GeckoDriverService.Builder().withTruncatedLogs(false).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() {
File profileDirectory = getTempDirectory("profile-");
FirefoxDriverService service =
new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = startFirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
private Path getFirefoxLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
return Path.of(finder.getBrowserPath());
}
@Test
public void fullPageScreenshot() throws Exception {
driver = startFirefoxDriver();
driver.get("https://www.selenium.dev");
File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);
File targetFile = new File("full_page_screenshot.png");
Files.move(screenshot.toPath(), targetFile.toPath());
// Verify the screenshot file exists
Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
Files.deleteIfExists(targetFile.toPath());
driver.quit();
}
@Test
public void setContext() {
driver = startFirefoxDriver();
((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
driver.executeScript("console.log('Inside Chrome context');");
// Verify the context is back to "content"
Assertions.assertEquals(
FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
"The context should be 'chrome'"
);
driver.quit();
}
@Test
public void firefoxProfile() {
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
profile.setPreference("javascript.enabled", "False");
options.setProfile(profile);
driver = new FirefoxDriver(options);
driver.quit();
}
}
Note: Java also allows setting log level by System Property:
Property key: GeckoDriverService.GECKO_DRIVER_PROFILE_ROOT
Property value: String representing path to profile root directory
service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_arguments():
options = webdriver.FirefoxOptions()
options.add_argument("-headless")
driver = webdriver.Firefox(options=options)
driver.quit()
def test_set_browser_location(firefox_bin):
options = webdriver.FirefoxOptions()
options.binary_location = firefox_bin
driver = webdriver.Firefox(options=options)
driver.quit()
def test_log_to_file(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
driver.get("https://www.selenium.dev")
with open(log_path, 'r') as fp:
assert "geckodriver INFO Listening on" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.FirefoxService(log_output=subprocess.STDOUT)
driver = webdriver.Firefox(service=service)
out, err = capfd.readouterr()
assert "geckodriver INFO Listening on" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert '\tDEBUG' in f.read()
driver.quit()
def test_log_truncation(log_path):
service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert ' ... ' not in f.read()
driver.quit()
def test_profile_location(temp_dir):
service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])
driver = webdriver.Firefox(service=service)
profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]
assert profile_name in os.listdir(temp_dir)
driver.quit()
def test_install_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
driver.install_addon(addon_path_xpi)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
id = driver.install_addon(addon_path_xpi)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
driver = firefox_driver
driver.install_addon(addon_path_dir, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
driver = firefox_driver
driver.install_addon(addon_path_dir_slash, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_full_page_screenshot(firefox_driver):
driver = firefox_driver
driver.get("https://www.selenium.dev")
driver.save_full_page_screenshot("full_page_screenshot.png")
assert os.path.exists("full_page_screenshot.png")
driver.quit()
def test_set_context(firefox_driver):
driver = firefox_driver
with driver.context(driver.CONTEXT_CHROME):
driver.execute_script("console.log('Inside Chrome context');")
# Check if the context is back to content
assert driver.execute("GET_CONTEXT")["value"] == "content"
def test_firefox_profile():
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
options = Options()
firefox_profile = FirefoxProfile()
firefox_profile.set_preference("javascript.enabled", False)
options.profile = firefox_profile
driver = webdriver.Firefox(options=options)
driver.quit()
service.args += ['--profile-root', root_directory]
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox
options.args << '-headless'
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.firefox
options.binary = firefox_location
@driver = Selenium::WebDriver.for :firefox, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('geckodriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.rm_rf(root_directory)
end
it 'logs to file' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
end
it 'logs to console' do
service = Selenium::WebDriver::Service.firefox
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :firefox, service: service
}.to output(/geckodriver INFO Listening on/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
service.args += %w[--log debug]
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).to eq true
end
it 'stops truncating log lines' do
service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])
service.args << '--log-no-truncate'
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
end
it 'sets default profile location' do
service = Selenium::WebDriver::Service.firefox
service.args += ['--profile-root', root_directory]
@driver = Selenium::WebDriver.for :firefox, service: service
profile_location = Dir.new(@driver.capabilities['moz:profile'])
expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
end
end
describe 'Features' do
let(:driver) { start_firefox }
it 'installs addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'takes full page screenshot' do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
Dir.mktmpdir('screenshot_test') do |dir|
screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))
expect(screenshot).to be_a File
end
end
it 'sets the context' do
driver.context = 'content'
expect(driver.context).to eq 'content'
end
end
describe 'Profile' do
it 'creates a new profile' do
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.dir'] = '/tmp/webdriver-downloads'
options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
expect(options.profile).to eq(profile)
end
end
def driver_finder
options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
service = Selenium::WebDriver::Service.firefox
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['GECKODRIVER_BIN'] = finder.driver_path
ENV['FIREFOX_BIN'] = finder.browser_path
end
end
Special Features
Extras
Ao invés do Chrome, os extras do Firefos não são adicionados como parte das capacidades, mas sim após iniciar o driver.
Unlike Chrome, Firefox extensions are not added as part of capabilities as mentioned in this issue, they are created after starting the driver.
The following examples are for local webdrivers. For remote webdrivers, please refer to the Remote WebDriver page.
Instalação
Um arquivo xpi que pode ser obtido da página Mozilla Extras
driver.installExtension(xpiPath);
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class FirefoxTest extends BaseTest {
private FirefoxDriver driver;
@AfterEach
public void clearProperties() {
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void arguments() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
@Test
@DisabledOnOs(OS.WINDOWS)
public void setBrowserLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBinary(getFirefoxLocation());
driver = new FirefoxDriver(options);
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogFile(logLocation).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogOutput(System.out).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
File logLocation = getTempFile("geckodriver-", "log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());
FirefoxDriverService service =
new GeckoDriverService.Builder().withTruncatedLogs(false).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() {
File profileDirectory = getTempDirectory("profile-");
FirefoxDriverService service =
new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = startFirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
private Path getFirefoxLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
return Path.of(finder.getBrowserPath());
}
@Test
public void fullPageScreenshot() throws Exception {
driver = startFirefoxDriver();
driver.get("https://www.selenium.dev");
File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);
File targetFile = new File("full_page_screenshot.png");
Files.move(screenshot.toPath(), targetFile.toPath());
// Verify the screenshot file exists
Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
Files.deleteIfExists(targetFile.toPath());
driver.quit();
}
@Test
public void setContext() {
driver = startFirefoxDriver();
((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
driver.executeScript("console.log('Inside Chrome context');");
// Verify the context is back to "content"
Assertions.assertEquals(
FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
"The context should be 'chrome'"
);
driver.quit();
}
@Test
public void firefoxProfile() {
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
profile.setPreference("javascript.enabled", "False");
options.setProfile(profile);
driver = new FirefoxDriver(options);
driver.quit();
}
}
driver.install_addon(addon_path_xpi)
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_arguments():
options = webdriver.FirefoxOptions()
options.add_argument("-headless")
driver = webdriver.Firefox(options=options)
driver.quit()
def test_set_browser_location(firefox_bin):
options = webdriver.FirefoxOptions()
options.binary_location = firefox_bin
driver = webdriver.Firefox(options=options)
driver.quit()
def test_log_to_file(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
driver.get("https://www.selenium.dev")
with open(log_path, 'r') as fp:
assert "geckodriver INFO Listening on" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.FirefoxService(log_output=subprocess.STDOUT)
driver = webdriver.Firefox(service=service)
out, err = capfd.readouterr()
assert "geckodriver INFO Listening on" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert '\tDEBUG' in f.read()
driver.quit()
def test_log_truncation(log_path):
service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert ' ... ' not in f.read()
driver.quit()
def test_profile_location(temp_dir):
service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])
driver = webdriver.Firefox(service=service)
profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]
assert profile_name in os.listdir(temp_dir)
driver.quit()
def test_install_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
driver.install_addon(addon_path_xpi)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
id = driver.install_addon(addon_path_xpi)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
driver = firefox_driver
driver.install_addon(addon_path_dir, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
driver = firefox_driver
driver.install_addon(addon_path_dir_slash, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_full_page_screenshot(firefox_driver):
driver = firefox_driver
driver.get("https://www.selenium.dev")
driver.save_full_page_screenshot("full_page_screenshot.png")
assert os.path.exists("full_page_screenshot.png")
driver.quit()
def test_set_context(firefox_driver):
driver = firefox_driver
with driver.context(driver.CONTEXT_CHROME):
driver.execute_script("console.log('Inside Chrome context');")
# Check if the context is back to content
assert driver.execute("GET_CONTEXT")["value"] == "content"
def test_firefox_profile():
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
options = Options()
firefox_profile = FirefoxProfile()
firefox_profile.set_preference("javascript.enabled", False)
options.profile = firefox_profile
driver = webdriver.Firefox(options=options)
driver.quit()
driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
Show full example
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class FirefoxTest
{
private FirefoxDriver driver;
private string _logLocation;
private string _tempPath;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
if (_tempPath != null && File.Exists(_tempPath))
{
File.Delete(_tempPath);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new FirefoxOptions();
options.AddArgument("-headless");
driver = new FirefoxDriver(options);
}
[TestMethod]
public void SetBinary()
{
var options = new FirefoxOptions();
options.BinaryLocation = GetFirefoxLocation();
driver = new FirefoxDriver(options);
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToFile()
{
var service = FirefoxDriverService.CreateDefaultService();
//service.LogFile = _logLocation
driver = new FirefoxDriver(service);
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("geckodriver INFO Listening on")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = FirefoxDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new FirefoxDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("geckodriver INFO Listening on"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("You can set it, just can't see it")]
public void LogsLevel()
{
var service = FirefoxDriverService.CreateDefaultService();
//service.LogFile = _logLocation
service.LogLevel = FirefoxDriverLogLevel.Debug;
driver = new FirefoxDriver(service);
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Marionette\tDEBUG")));
}
[TestMethod]
[Ignore("Not implemented")]
public void StopsTruncatingLogs()
{
var service = FirefoxDriverService.CreateDefaultService();
//service.TruncateLogs = false;
service.LogLevel = FirefoxDriverLogLevel.Debug;
driver = new FirefoxDriver(service);
var lines = File.ReadLines(GetLogLocation());
Assert.IsNull(lines.FirstOrDefault(line => line.Contains(" ... ")));
}
[TestMethod]
[Ignore("Not implemented")]
public void SetProfileLocation()
{
var service = FirefoxDriverService.CreateDefaultService();
// service.ProfileRoot = GetTempDirectory();
driver = new FirefoxDriver(service);
string profile = (string)driver.Capabilities.GetCapability("moz:profile");
string[] directories = profile.Split("/");
var dirName = directories.Last();
Assert.AreEqual(GetTempDirectory() + "/" + dirName, profile);
}
[TestMethod]
public void InstallAddon()
{
SetWaitingDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void UnInstallAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
string extensionId = driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.UninstallAddOn(extensionId);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
Assert.AreEqual(driver.FindElements(By.Id("webextensions-selenium-example")).Count, 0);
}
[TestMethod]
public void InstallUnsignedAddon()
{
SetWaitingDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionDirPath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example/");
driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
private string GetLogLocation()
{
if (_logLocation != null && !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private string GetTempDirectory()
{
if (_tempPath != null && !File.Exists(_tempPath))
{
_tempPath = Path.GetTempPath();
}
return _tempPath;
}
private void SetWaitingDriver()
{
driver = new FirefoxDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2);
}
private static string GetFirefoxLocation()
{
var options = new FirefoxOptions()
{
BrowserVersion = "stable"
};
return new DriverFinder(options).GetBrowserPath();
}
}
}
driver.install_addon(extension_file_path)
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox
options.args << '-headless'
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.firefox
options.binary = firefox_location
@driver = Selenium::WebDriver.for :firefox, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('geckodriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.rm_rf(root_directory)
end
it 'logs to file' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
end
it 'logs to console' do
service = Selenium::WebDriver::Service.firefox
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :firefox, service: service
}.to output(/geckodriver INFO Listening on/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
service.args += %w[--log debug]
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).to eq true
end
it 'stops truncating log lines' do
service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])
service.args << '--log-no-truncate'
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
end
it 'sets default profile location' do
service = Selenium::WebDriver::Service.firefox
service.args += ['--profile-root', root_directory]
@driver = Selenium::WebDriver.for :firefox, service: service
profile_location = Dir.new(@driver.capabilities['moz:profile'])
expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
end
end
describe 'Features' do
let(:driver) { start_firefox }
it 'installs addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'takes full page screenshot' do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
Dir.mktmpdir('screenshot_test') do |dir|
screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))
expect(screenshot).to be_a File
end
end
it 'sets the context' do
driver.context = 'content'
expect(driver.context).to eq 'content'
end
end
describe 'Profile' do
it 'creates a new profile' do
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.dir'] = '/tmp/webdriver-downloads'
options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
expect(options.profile).to eq(profile)
end
end
def driver_finder
options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
service = Selenium::WebDriver::Service.firefox
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['GECKODRIVER_BIN'] = finder.driver_path
ENV['FIREFOX_BIN'] = finder.browser_path
end
end
let id = await driver.installAddon(xpiPath);
Show full example
const {Browser, By, Builder} = require('selenium-webdriver');
const Firefox = require('selenium-webdriver/firefox');
const options = new Firefox.Options();
const path = require('path');
const assert = require("assert");
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = new Builder()
.forBrowser(Browser.FIREFOX)
.setFirefoxOptions(options.addArguments('--headless'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Should be able to add extension', async function () {
const xpiPath = path.resolve('./test/resources/extensions/selenium-example.xpi')
let driver = new Builder()
.forBrowser(Browser.FIREFOX)
.build()
let id = await driver.installAddon(xpiPath);
await driver.uninstallAddon(id);
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
const ele = await driver.findElements(By.id("webextensions-selenium-example"));
assert.equal(ele.length, 0);
await driver.quit();
});
it('Should be able to install unsigned addon', async function () {
const xpiPath = path.resolve('./test/resources/extensions/selenium-example')
let driver = new Builder()
.forBrowser(Browser.FIREFOX)
.build()
let id = await driver.installAddon(xpiPath, true);
await driver.uninstallAddon(id);
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
const ele = await driver.findElements(By.id("webextensions-selenium-example"));
assert.equal(ele.length, 0);
await driver.quit();
});
});
Desinstalação
Desinstalar uma extensão implica saber o seu id que pode ser obtido como valor de retorno durante a instalação.
driver.uninstallExtension(id);
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class FirefoxTest extends BaseTest {
private FirefoxDriver driver;
@AfterEach
public void clearProperties() {
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void arguments() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
@Test
@DisabledOnOs(OS.WINDOWS)
public void setBrowserLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBinary(getFirefoxLocation());
driver = new FirefoxDriver(options);
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogFile(logLocation).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogOutput(System.out).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
File logLocation = getTempFile("geckodriver-", "log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());
FirefoxDriverService service =
new GeckoDriverService.Builder().withTruncatedLogs(false).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() {
File profileDirectory = getTempDirectory("profile-");
FirefoxDriverService service =
new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = startFirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
private Path getFirefoxLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
return Path.of(finder.getBrowserPath());
}
@Test
public void fullPageScreenshot() throws Exception {
driver = startFirefoxDriver();
driver.get("https://www.selenium.dev");
File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);
File targetFile = new File("full_page_screenshot.png");
Files.move(screenshot.toPath(), targetFile.toPath());
// Verify the screenshot file exists
Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
Files.deleteIfExists(targetFile.toPath());
driver.quit();
}
@Test
public void setContext() {
driver = startFirefoxDriver();
((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
driver.executeScript("console.log('Inside Chrome context');");
// Verify the context is back to "content"
Assertions.assertEquals(
FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
"The context should be 'chrome'"
);
driver.quit();
}
@Test
public void firefoxProfile() {
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
profile.setPreference("javascript.enabled", "False");
options.setProfile(profile);
driver = new FirefoxDriver(options);
driver.quit();
}
}
driver.uninstall_addon(id)
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_arguments():
options = webdriver.FirefoxOptions()
options.add_argument("-headless")
driver = webdriver.Firefox(options=options)
driver.quit()
def test_set_browser_location(firefox_bin):
options = webdriver.FirefoxOptions()
options.binary_location = firefox_bin
driver = webdriver.Firefox(options=options)
driver.quit()
def test_log_to_file(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
driver.get("https://www.selenium.dev")
with open(log_path, 'r') as fp:
assert "geckodriver INFO Listening on" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.FirefoxService(log_output=subprocess.STDOUT)
driver = webdriver.Firefox(service=service)
out, err = capfd.readouterr()
assert "geckodriver INFO Listening on" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert '\tDEBUG' in f.read()
driver.quit()
def test_log_truncation(log_path):
service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert ' ... ' not in f.read()
driver.quit()
def test_profile_location(temp_dir):
service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])
driver = webdriver.Firefox(service=service)
profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]
assert profile_name in os.listdir(temp_dir)
driver.quit()
def test_install_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
driver.install_addon(addon_path_xpi)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
id = driver.install_addon(addon_path_xpi)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
driver = firefox_driver
driver.install_addon(addon_path_dir, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
driver = firefox_driver
driver.install_addon(addon_path_dir_slash, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_full_page_screenshot(firefox_driver):
driver = firefox_driver
driver.get("https://www.selenium.dev")
driver.save_full_page_screenshot("full_page_screenshot.png")
assert os.path.exists("full_page_screenshot.png")
driver.quit()
def test_set_context(firefox_driver):
driver = firefox_driver
with driver.context(driver.CONTEXT_CHROME):
driver.execute_script("console.log('Inside Chrome context');")
# Check if the context is back to content
assert driver.execute("GET_CONTEXT")["value"] == "content"
def test_firefox_profile():
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
options = Options()
firefox_profile = FirefoxProfile()
firefox_profile.set_preference("javascript.enabled", False)
options.profile = firefox_profile
driver = webdriver.Firefox(options=options)
driver.quit()
driver.UninstallAddOn(extensionId);
Show full example
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class FirefoxTest
{
private FirefoxDriver driver;
private string _logLocation;
private string _tempPath;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
if (_tempPath != null && File.Exists(_tempPath))
{
File.Delete(_tempPath);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new FirefoxOptions();
options.AddArgument("-headless");
driver = new FirefoxDriver(options);
}
[TestMethod]
public void SetBinary()
{
var options = new FirefoxOptions();
options.BinaryLocation = GetFirefoxLocation();
driver = new FirefoxDriver(options);
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToFile()
{
var service = FirefoxDriverService.CreateDefaultService();
//service.LogFile = _logLocation
driver = new FirefoxDriver(service);
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("geckodriver INFO Listening on")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = FirefoxDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new FirefoxDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("geckodriver INFO Listening on"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("You can set it, just can't see it")]
public void LogsLevel()
{
var service = FirefoxDriverService.CreateDefaultService();
//service.LogFile = _logLocation
service.LogLevel = FirefoxDriverLogLevel.Debug;
driver = new FirefoxDriver(service);
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Marionette\tDEBUG")));
}
[TestMethod]
[Ignore("Not implemented")]
public void StopsTruncatingLogs()
{
var service = FirefoxDriverService.CreateDefaultService();
//service.TruncateLogs = false;
service.LogLevel = FirefoxDriverLogLevel.Debug;
driver = new FirefoxDriver(service);
var lines = File.ReadLines(GetLogLocation());
Assert.IsNull(lines.FirstOrDefault(line => line.Contains(" ... ")));
}
[TestMethod]
[Ignore("Not implemented")]
public void SetProfileLocation()
{
var service = FirefoxDriverService.CreateDefaultService();
// service.ProfileRoot = GetTempDirectory();
driver = new FirefoxDriver(service);
string profile = (string)driver.Capabilities.GetCapability("moz:profile");
string[] directories = profile.Split("/");
var dirName = directories.Last();
Assert.AreEqual(GetTempDirectory() + "/" + dirName, profile);
}
[TestMethod]
public void InstallAddon()
{
SetWaitingDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void UnInstallAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
string extensionId = driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.UninstallAddOn(extensionId);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
Assert.AreEqual(driver.FindElements(By.Id("webextensions-selenium-example")).Count, 0);
}
[TestMethod]
public void InstallUnsignedAddon()
{
SetWaitingDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionDirPath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example/");
driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
private string GetLogLocation()
{
if (_logLocation != null && !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private string GetTempDirectory()
{
if (_tempPath != null && !File.Exists(_tempPath))
{
_tempPath = Path.GetTempPath();
}
return _tempPath;
}
private void SetWaitingDriver()
{
driver = new FirefoxDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2);
}
private static string GetFirefoxLocation()
{
var options = new FirefoxOptions()
{
BrowserVersion = "stable"
};
return new DriverFinder(options).GetBrowserPath();
}
}
}
driver.uninstall_addon(extension_id)
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox
options.args << '-headless'
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.firefox
options.binary = firefox_location
@driver = Selenium::WebDriver.for :firefox, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('geckodriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.rm_rf(root_directory)
end
it 'logs to file' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
end
it 'logs to console' do
service = Selenium::WebDriver::Service.firefox
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :firefox, service: service
}.to output(/geckodriver INFO Listening on/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
service.args += %w[--log debug]
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).to eq true
end
it 'stops truncating log lines' do
service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])
service.args << '--log-no-truncate'
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
end
it 'sets default profile location' do
service = Selenium::WebDriver::Service.firefox
service.args += ['--profile-root', root_directory]
@driver = Selenium::WebDriver.for :firefox, service: service
profile_location = Dir.new(@driver.capabilities['moz:profile'])
expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
end
end
describe 'Features' do
let(:driver) { start_firefox }
it 'installs addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'takes full page screenshot' do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
Dir.mktmpdir('screenshot_test') do |dir|
screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))
expect(screenshot).to be_a File
end
end
it 'sets the context' do
driver.context = 'content'
expect(driver.context).to eq 'content'
end
end
describe 'Profile' do
it 'creates a new profile' do
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.dir'] = '/tmp/webdriver-downloads'
options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
expect(options.profile).to eq(profile)
end
end
def driver_finder
options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
service = Selenium::WebDriver::Service.firefox
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['GECKODRIVER_BIN'] = finder.driver_path
ENV['FIREFOX_BIN'] = finder.browser_path
end
end
await driver.uninstallAddon(id);
Show full example
const {Browser, By, Builder} = require('selenium-webdriver');
const Firefox = require('selenium-webdriver/firefox');
const options = new Firefox.Options();
const path = require('path');
const assert = require("assert");
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = new Builder()
.forBrowser(Browser.FIREFOX)
.setFirefoxOptions(options.addArguments('--headless'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Should be able to add extension', async function () {
const xpiPath = path.resolve('./test/resources/extensions/selenium-example.xpi')
let driver = new Builder()
.forBrowser(Browser.FIREFOX)
.build()
let id = await driver.installAddon(xpiPath);
await driver.uninstallAddon(id);
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
const ele = await driver.findElements(By.id("webextensions-selenium-example"));
assert.equal(ele.length, 0);
await driver.quit();
});
it('Should be able to install unsigned addon', async function () {
const xpiPath = path.resolve('./test/resources/extensions/selenium-example')
let driver = new Builder()
.forBrowser(Browser.FIREFOX)
.build()
let id = await driver.installAddon(xpiPath, true);
await driver.uninstallAddon(id);
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
const ele = await driver.findElements(By.id("webextensions-selenium-example"));
assert.equal(ele.length, 0);
await driver.quit();
});
});
Instalação de extensões não assinadas
Quando trabalhar em uma extensão não terminada ou não publicada, provavelmente ela não estará assinada. Desta forma, só pode ser instalada como “temporária”. Isto pode ser feito passando uma arquivo ZIP ou uma pasta, este é um exemplo com uma pasta:
driver.installExtension(path, true);
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class FirefoxTest extends BaseTest {
private FirefoxDriver driver;
@AfterEach
public void clearProperties() {
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void arguments() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
@Test
@DisabledOnOs(OS.WINDOWS)
public void setBrowserLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBinary(getFirefoxLocation());
driver = new FirefoxDriver(options);
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogFile(logLocation).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogOutput(System.out).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
File logLocation = getTempFile("geckodriver-", "log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());
FirefoxDriverService service =
new GeckoDriverService.Builder().withTruncatedLogs(false).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() {
File profileDirectory = getTempDirectory("profile-");
FirefoxDriverService service =
new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = startFirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
private Path getFirefoxLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
return Path.of(finder.getBrowserPath());
}
@Test
public void fullPageScreenshot() throws Exception {
driver = startFirefoxDriver();
driver.get("https://www.selenium.dev");
File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);
File targetFile = new File("full_page_screenshot.png");
Files.move(screenshot.toPath(), targetFile.toPath());
// Verify the screenshot file exists
Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
Files.deleteIfExists(targetFile.toPath());
driver.quit();
}
@Test
public void setContext() {
driver = startFirefoxDriver();
((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
driver.executeScript("console.log('Inside Chrome context');");
// Verify the context is back to "content"
Assertions.assertEquals(
FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
"The context should be 'chrome'"
);
driver.quit();
}
@Test
public void firefoxProfile() {
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
profile.setPreference("javascript.enabled", "False");
options.setProfile(profile);
driver = new FirefoxDriver(options);
driver.quit();
}
}
driver.install_addon(addon_path_dir, temporary=True)
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_arguments():
options = webdriver.FirefoxOptions()
options.add_argument("-headless")
driver = webdriver.Firefox(options=options)
driver.quit()
def test_set_browser_location(firefox_bin):
options = webdriver.FirefoxOptions()
options.binary_location = firefox_bin
driver = webdriver.Firefox(options=options)
driver.quit()
def test_log_to_file(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
driver.get("https://www.selenium.dev")
with open(log_path, 'r') as fp:
assert "geckodriver INFO Listening on" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.FirefoxService(log_output=subprocess.STDOUT)
driver = webdriver.Firefox(service=service)
out, err = capfd.readouterr()
assert "geckodriver INFO Listening on" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert '\tDEBUG' in f.read()
driver.quit()
def test_log_truncation(log_path):
service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert ' ... ' not in f.read()
driver.quit()
def test_profile_location(temp_dir):
service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])
driver = webdriver.Firefox(service=service)
profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]
assert profile_name in os.listdir(temp_dir)
driver.quit()
def test_install_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
driver.install_addon(addon_path_xpi)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
id = driver.install_addon(addon_path_xpi)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
driver = firefox_driver
driver.install_addon(addon_path_dir, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
driver = firefox_driver
driver.install_addon(addon_path_dir_slash, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_full_page_screenshot(firefox_driver):
driver = firefox_driver
driver.get("https://www.selenium.dev")
driver.save_full_page_screenshot("full_page_screenshot.png")
assert os.path.exists("full_page_screenshot.png")
driver.quit()
def test_set_context(firefox_driver):
driver = firefox_driver
with driver.context(driver.CONTEXT_CHROME):
driver.execute_script("console.log('Inside Chrome context');")
# Check if the context is back to content
assert driver.execute("GET_CONTEXT")["value"] == "content"
def test_firefox_profile():
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
options = Options()
firefox_profile = FirefoxProfile()
firefox_profile.set_preference("javascript.enabled", False)
options.profile = firefox_profile
driver = webdriver.Firefox(options=options)
driver.quit()
driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);
Show full example
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class FirefoxTest
{
private FirefoxDriver driver;
private string _logLocation;
private string _tempPath;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
if (_tempPath != null && File.Exists(_tempPath))
{
File.Delete(_tempPath);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new FirefoxOptions();
options.AddArgument("-headless");
driver = new FirefoxDriver(options);
}
[TestMethod]
public void SetBinary()
{
var options = new FirefoxOptions();
options.BinaryLocation = GetFirefoxLocation();
driver = new FirefoxDriver(options);
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToFile()
{
var service = FirefoxDriverService.CreateDefaultService();
//service.LogFile = _logLocation
driver = new FirefoxDriver(service);
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("geckodriver INFO Listening on")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = FirefoxDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new FirefoxDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("geckodriver INFO Listening on"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("You can set it, just can't see it")]
public void LogsLevel()
{
var service = FirefoxDriverService.CreateDefaultService();
//service.LogFile = _logLocation
service.LogLevel = FirefoxDriverLogLevel.Debug;
driver = new FirefoxDriver(service);
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Marionette\tDEBUG")));
}
[TestMethod]
[Ignore("Not implemented")]
public void StopsTruncatingLogs()
{
var service = FirefoxDriverService.CreateDefaultService();
//service.TruncateLogs = false;
service.LogLevel = FirefoxDriverLogLevel.Debug;
driver = new FirefoxDriver(service);
var lines = File.ReadLines(GetLogLocation());
Assert.IsNull(lines.FirstOrDefault(line => line.Contains(" ... ")));
}
[TestMethod]
[Ignore("Not implemented")]
public void SetProfileLocation()
{
var service = FirefoxDriverService.CreateDefaultService();
// service.ProfileRoot = GetTempDirectory();
driver = new FirefoxDriver(service);
string profile = (string)driver.Capabilities.GetCapability("moz:profile");
string[] directories = profile.Split("/");
var dirName = directories.Last();
Assert.AreEqual(GetTempDirectory() + "/" + dirName, profile);
}
[TestMethod]
public void InstallAddon()
{
SetWaitingDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void UnInstallAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
string extensionId = driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.UninstallAddOn(extensionId);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
Assert.AreEqual(driver.FindElements(By.Id("webextensions-selenium-example")).Count, 0);
}
[TestMethod]
public void InstallUnsignedAddon()
{
SetWaitingDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionDirPath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example/");
driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
private string GetLogLocation()
{
if (_logLocation != null && !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private string GetTempDirectory()
{
if (_tempPath != null && !File.Exists(_tempPath))
{
_tempPath = Path.GetTempPath();
}
return _tempPath;
}
private void SetWaitingDriver()
{
driver = new FirefoxDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2);
}
private static string GetFirefoxLocation()
{
var options = new FirefoxOptions()
{
BrowserVersion = "stable"
};
return new DriverFinder(options).GetBrowserPath();
}
}
}
driver.install_addon(extension_dir_path, true)
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox
options.args << '-headless'
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.firefox
options.binary = firefox_location
@driver = Selenium::WebDriver.for :firefox, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('geckodriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.rm_rf(root_directory)
end
it 'logs to file' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
end
it 'logs to console' do
service = Selenium::WebDriver::Service.firefox
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :firefox, service: service
}.to output(/geckodriver INFO Listening on/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
service.args += %w[--log debug]
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).to eq true
end
it 'stops truncating log lines' do
service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])
service.args << '--log-no-truncate'
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
end
it 'sets default profile location' do
service = Selenium::WebDriver::Service.firefox
service.args += ['--profile-root', root_directory]
@driver = Selenium::WebDriver.for :firefox, service: service
profile_location = Dir.new(@driver.capabilities['moz:profile'])
expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
end
end
describe 'Features' do
let(:driver) { start_firefox }
it 'installs addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'takes full page screenshot' do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
Dir.mktmpdir('screenshot_test') do |dir|
screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))
expect(screenshot).to be_a File
end
end
it 'sets the context' do
driver.context = 'content'
expect(driver.context).to eq 'content'
end
end
describe 'Profile' do
it 'creates a new profile' do
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.dir'] = '/tmp/webdriver-downloads'
options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
expect(options.profile).to eq(profile)
end
end
def driver_finder
options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
service = Selenium::WebDriver::Service.firefox
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['GECKODRIVER_BIN'] = finder.driver_path
ENV['FIREFOX_BIN'] = finder.browser_path
end
end
let id = await driver.installAddon(xpiPath, true);
Show full example
const {Browser, By, Builder} = require('selenium-webdriver');
const Firefox = require('selenium-webdriver/firefox');
const options = new Firefox.Options();
const path = require('path');
const assert = require("assert");
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = new Builder()
.forBrowser(Browser.FIREFOX)
.setFirefoxOptions(options.addArguments('--headless'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Should be able to add extension', async function () {
const xpiPath = path.resolve('./test/resources/extensions/selenium-example.xpi')
let driver = new Builder()
.forBrowser(Browser.FIREFOX)
.build()
let id = await driver.installAddon(xpiPath);
await driver.uninstallAddon(id);
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
const ele = await driver.findElements(By.id("webextensions-selenium-example"));
assert.equal(ele.length, 0);
await driver.quit();
});
it('Should be able to install unsigned addon', async function () {
const xpiPath = path.resolve('./test/resources/extensions/selenium-example')
let driver = new Builder()
.forBrowser(Browser.FIREFOX)
.build()
let id = await driver.installAddon(xpiPath, true);
await driver.uninstallAddon(id);
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
const ele = await driver.findElements(By.id("webextensions-selenium-example"));
assert.equal(ele.length, 0);
await driver.quit();
});
});
Captura de tela inteira
The following examples are for local webdrivers. For remote webdrivers, please refer to the Remote WebDriver page.
File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class FirefoxTest extends BaseTest {
private FirefoxDriver driver;
@AfterEach
public void clearProperties() {
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void arguments() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
@Test
@DisabledOnOs(OS.WINDOWS)
public void setBrowserLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBinary(getFirefoxLocation());
driver = new FirefoxDriver(options);
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogFile(logLocation).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogOutput(System.out).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
File logLocation = getTempFile("geckodriver-", "log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());
FirefoxDriverService service =
new GeckoDriverService.Builder().withTruncatedLogs(false).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() {
File profileDirectory = getTempDirectory("profile-");
FirefoxDriverService service =
new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = startFirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
private Path getFirefoxLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
return Path.of(finder.getBrowserPath());
}
@Test
public void fullPageScreenshot() throws Exception {
driver = startFirefoxDriver();
driver.get("https://www.selenium.dev");
File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);
File targetFile = new File("full_page_screenshot.png");
Files.move(screenshot.toPath(), targetFile.toPath());
// Verify the screenshot file exists
Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
Files.deleteIfExists(targetFile.toPath());
driver.quit();
}
@Test
public void setContext() {
driver = startFirefoxDriver();
((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
driver.executeScript("console.log('Inside Chrome context');");
// Verify the context is back to "content"
Assertions.assertEquals(
FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
"The context should be 'chrome'"
);
driver.quit();
}
@Test
public void firefoxProfile() {
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
profile.setPreference("javascript.enabled", "False");
options.setProfile(profile);
driver = new FirefoxDriver(options);
driver.quit();
}
}
driver.save_full_page_screenshot("full_page_screenshot.png")
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_arguments():
options = webdriver.FirefoxOptions()
options.add_argument("-headless")
driver = webdriver.Firefox(options=options)
driver.quit()
def test_set_browser_location(firefox_bin):
options = webdriver.FirefoxOptions()
options.binary_location = firefox_bin
driver = webdriver.Firefox(options=options)
driver.quit()
def test_log_to_file(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
driver.get("https://www.selenium.dev")
with open(log_path, 'r') as fp:
assert "geckodriver INFO Listening on" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.FirefoxService(log_output=subprocess.STDOUT)
driver = webdriver.Firefox(service=service)
out, err = capfd.readouterr()
assert "geckodriver INFO Listening on" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert '\tDEBUG' in f.read()
driver.quit()
def test_log_truncation(log_path):
service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert ' ... ' not in f.read()
driver.quit()
def test_profile_location(temp_dir):
service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])
driver = webdriver.Firefox(service=service)
profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]
assert profile_name in os.listdir(temp_dir)
driver.quit()
def test_install_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
driver.install_addon(addon_path_xpi)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
id = driver.install_addon(addon_path_xpi)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
driver = firefox_driver
driver.install_addon(addon_path_dir, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
driver = firefox_driver
driver.install_addon(addon_path_dir_slash, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_full_page_screenshot(firefox_driver):
driver = firefox_driver
driver.get("https://www.selenium.dev")
driver.save_full_page_screenshot("full_page_screenshot.png")
assert os.path.exists("full_page_screenshot.png")
driver.quit()
def test_set_context(firefox_driver):
driver = firefox_driver
with driver.context(driver.CONTEXT_CHROME):
driver.execute_script("console.log('Inside Chrome context');")
# Check if the context is back to content
assert driver.execute("GET_CONTEXT")["value"] == "content"
def test_firefox_profile():
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
options = Options()
firefox_profile = FirefoxProfile()
firefox_profile.set_preference("javascript.enabled", False)
options.profile = firefox_profile
driver = webdriver.Firefox(options=options)
driver.quit()
screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox
options.args << '-headless'
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.firefox
options.binary = firefox_location
@driver = Selenium::WebDriver.for :firefox, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('geckodriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.rm_rf(root_directory)
end
it 'logs to file' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
end
it 'logs to console' do
service = Selenium::WebDriver::Service.firefox
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :firefox, service: service
}.to output(/geckodriver INFO Listening on/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
service.args += %w[--log debug]
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).to eq true
end
it 'stops truncating log lines' do
service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])
service.args << '--log-no-truncate'
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
end
it 'sets default profile location' do
service = Selenium::WebDriver::Service.firefox
service.args += ['--profile-root', root_directory]
@driver = Selenium::WebDriver.for :firefox, service: service
profile_location = Dir.new(@driver.capabilities['moz:profile'])
expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
end
end
describe 'Features' do
let(:driver) { start_firefox }
it 'installs addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'takes full page screenshot' do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
Dir.mktmpdir('screenshot_test') do |dir|
screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))
expect(screenshot).to be_a File
end
end
it 'sets the context' do
driver.context = 'content'
expect(driver.context).to eq 'content'
end
end
describe 'Profile' do
it 'creates a new profile' do
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.dir'] = '/tmp/webdriver-downloads'
options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
expect(options.profile).to eq(profile)
end
end
def driver_finder
options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
service = Selenium::WebDriver::Service.firefox
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['GECKODRIVER_BIN'] = finder.driver_path
ENV['FIREFOX_BIN'] = finder.browser_path
end
end
Contexto
The following examples are for local webdrivers. For remote webdrivers, please refer to the Remote WebDriver page.
((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
driver.executeScript("console.log('Inside Chrome context');");
Show full example
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;
public class FirefoxTest extends BaseTest {
private FirefoxDriver driver;
@AfterEach
public void clearProperties() {
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void arguments() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
@Test
@DisabledOnOs(OS.WINDOWS)
public void setBrowserLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBinary(getFirefoxLocation());
driver = new FirefoxDriver(options);
}
@Test
public void logsToFile() throws IOException {
File logLocation = getTempFile("logsToFile", ".log");
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogFile(logLocation).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
File logLocation = getTempFile("logsToConsole", ".log");
System.setOut(new PrintStream(logLocation));
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogOutput(System.out).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
File logLocation = getTempFile("logsWithLevel", ".log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
File logLocation = getTempFile("geckodriver-", "log");
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
System.setProperty(
GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());
FirefoxDriverService service =
new GeckoDriverService.Builder().withTruncatedLogs(false).build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() {
File profileDirectory = getTempDirectory("profile-");
FirefoxDriverService service =
new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = startFirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = startFirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals(
"Content injected by webextensions-selenium-example", injected.getText());
}
private Path getFirefoxLocation() {
FirefoxOptions options = new FirefoxOptions();
options.setBrowserVersion("stable");
DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
return Path.of(finder.getBrowserPath());
}
@Test
public void fullPageScreenshot() throws Exception {
driver = startFirefoxDriver();
driver.get("https://www.selenium.dev");
File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);
File targetFile = new File("full_page_screenshot.png");
Files.move(screenshot.toPath(), targetFile.toPath());
// Verify the screenshot file exists
Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
Files.deleteIfExists(targetFile.toPath());
driver.quit();
}
@Test
public void setContext() {
driver = startFirefoxDriver();
((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
driver.executeScript("console.log('Inside Chrome context');");
// Verify the context is back to "content"
Assertions.assertEquals(
FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
"The context should be 'chrome'"
);
driver.quit();
}
@Test
public void firefoxProfile() {
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
profile.setPreference("javascript.enabled", "False");
options.setProfile(profile);
driver = new FirefoxDriver(options);
driver.quit();
}
}
with driver.context(driver.CONTEXT_CHROME):
driver.execute_script("console.log('Inside Chrome context');")
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_arguments():
options = webdriver.FirefoxOptions()
options.add_argument("-headless")
driver = webdriver.Firefox(options=options)
driver.quit()
def test_set_browser_location(firefox_bin):
options = webdriver.FirefoxOptions()
options.binary_location = firefox_bin
driver = webdriver.Firefox(options=options)
driver.quit()
def test_log_to_file(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
driver.get("https://www.selenium.dev")
with open(log_path, 'r') as fp:
assert "geckodriver INFO Listening on" in fp.readline()
driver.quit()
def test_log_to_stdout(capfd):
service = webdriver.FirefoxService(log_output=subprocess.STDOUT)
driver = webdriver.Firefox(service=service)
out, err = capfd.readouterr()
assert "geckodriver INFO Listening on" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert '\tDEBUG' in f.read()
driver.quit()
def test_log_truncation(log_path):
service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert ' ... ' not in f.read()
driver.quit()
def test_profile_location(temp_dir):
service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])
driver = webdriver.Firefox(service=service)
profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]
assert profile_name in os.listdir(temp_dir)
driver.quit()
def test_install_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
driver.install_addon(addon_path_xpi)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver, addon_path_xpi):
driver = firefox_driver
id = driver.install_addon(addon_path_xpi)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
driver = firefox_driver
driver.install_addon(addon_path_dir, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
driver = firefox_driver
driver.install_addon(addon_path_dir_slash, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_full_page_screenshot(firefox_driver):
driver = firefox_driver
driver.get("https://www.selenium.dev")
driver.save_full_page_screenshot("full_page_screenshot.png")
assert os.path.exists("full_page_screenshot.png")
driver.quit()
def test_set_context(firefox_driver):
driver = firefox_driver
with driver.context(driver.CONTEXT_CHROME):
driver.execute_script("console.log('Inside Chrome context');")
# Check if the context is back to content
assert driver.execute("GET_CONTEXT")["value"] == "content"
def test_firefox_profile():
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
options = Options()
firefox_profile = FirefoxProfile()
firefox_profile.set_preference("javascript.enabled", False)
options.profile = firefox_profile
driver = webdriver.Firefox(options=options)
driver.quit()
driver.context = 'content'
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox
options.args << '-headless'
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'sets location of binary' do
options = Selenium::WebDriver::Options.firefox
options.binary = firefox_location
@driver = Selenium::WebDriver.for :firefox, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('geckodriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.rm_rf(root_directory)
end
it 'logs to file' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
end
it 'logs to console' do
service = Selenium::WebDriver::Service.firefox
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :firefox, service: service
}.to output(/geckodriver INFO Listening on/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
service.args += %w[--log debug]
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).to eq true
end
it 'stops truncating log lines' do
service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])
service.args << '--log-no-truncate'
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
end
it 'sets default profile location' do
service = Selenium::WebDriver::Service.firefox
service.args += ['--profile-root', root_directory]
@driver = Selenium::WebDriver.for :firefox, service: service
profile_location = Dir.new(@driver.capabilities['moz:profile'])
expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
end
end
describe 'Features' do
let(:driver) { start_firefox }
it 'installs addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'takes full page screenshot' do
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
Dir.mktmpdir('screenshot_test') do |dir|
screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))
expect(screenshot).to be_a File
end
end
it 'sets the context' do
driver.context = 'content'
expect(driver.context).to eq 'content'
end
end
describe 'Profile' do
it 'creates a new profile' do
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.dir'] = '/tmp/webdriver-downloads'
options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
expect(options.profile).to eq(profile)
end
end
def driver_finder
options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
service = Selenium::WebDriver::Service.firefox
finder = Selenium::WebDriver::DriverFinder.new(options, service)
ENV['GECKODRIVER_BIN'] = finder.driver_path
ENV['FIREFOX_BIN'] = finder.browser_path
end
end
Note: As of Firefox 138, geckodriver needs to be started with the argument --allow-system-access
to switch the context to CHROME
.
4 - Funcionalidade específica do IE
Desde Junho de 2022, o Projecto Selenium deixou de suportar oficialmente o navegador Internet Explorer. O driver Internet Explorer continua a suportar a execução do Microsoft Edge no modo “IE Compatibility Mode.”
Considerações especiais
O IE Driver é o único driver mantido directamente pelo Projecto Selenium. Embora existam binários para as versões de 32 e 64 bits, existem algumas limitações conhecidas com o driver de 64 bits. Desta forma, recomenda-se a utilização do driver de 32 bits.
Informação adicional sobre como usar o Internet Explorer pode ser encontrada na página IE Driver Server
Opções
Este é um exemplo de como iniciar o navegador Microsoft Edge em modo compatibilidade Internet Explorer usando um conjunto de opções básicas:
InternetExplorerOptions options = new InternetExplorerOptions();
options.attachToEdgeChrome();
options.withEdgeExecutablePath(getEdgeLocation());
driver = new InternetExplorerDriver(options);
Show full example
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
public InternetExplorerDriver driver;
private File logLocation;
private File tempDirectory;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
if (tempDirectory != null && tempDirectory.exists()) {
tempDirectory.delete();
}
driver.quit();
}
@Test
public void basicOptionsWin10() {
InternetExplorerOptions options = new InternetExplorerOptions();
options.attachToEdgeChrome();
options.withEdgeExecutablePath(getEdgeLocation());
driver = new InternetExplorerDriver(options);
}
@Test
public void basicOptionsWin11() {
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
@Test
public void logsToFile() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,
getLogLocation().getAbsolutePath());
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogLevel(InternetExplorerDriverLogLevel.WARN)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));
}
@Test
public void supportingFilesLocation() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withExtractPath(getTempDirectory())
.build();
driver = new InternetExplorerDriver(service);
Assertions.assertTrue(new File(getTempDirectory() + "/IEDriver.tmp").exists());
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("iedriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("supporting-").toFile();
}
return tempDirectory;
}
private String getEdgeLocation() {
return System.getenv("EDGE_BIN");
}
}
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = edge_bin
driver = webdriver.Ie(options=options)
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = edge_bin
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
options = webdriver.IeOptions()
options.file_upload_timeout = 2000
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
options = webdriver.IeOptions()
options.ensure_clean_session = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
options = webdriver.IeOptions()
options.ignore_zoom_level = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
options = webdriver.IeOptions()
options.ignore_protected_mode_settings = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
service = webdriver.IeService(service_args=["--silent"])
driver = webdriver.Ie(service=service)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
options = webdriver.IeOptions()
options.add_argument("-private")
driver = webdriver.Ie(options=options)
driver.quit()
# Skipping this as it fails on Windows because the value of registry setting in
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0'
@pytest.mark.skip
def test_force_create_process_api():
options = webdriver.IeOptions()
options.force_create_process_api = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.IeService(log_output=log_path, log_level="INFO")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
service = webdriver.IeService(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.IeService(log_output=log_path, log_level="WARN")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
var options = new InternetExplorerOptions();
options.AttachToEdgeChrome = true;
options.EdgeExecutablePath = GetEdgeLocation();
_driver = new InternetExplorerDriver(options);
Show full example
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.IE;
using SeleniumDocs.TestSupport;
namespace SeleniumDocs.Browsers
{
[TestClassCustom]
[EnabledOnOs("WINDOWS")]
public class InternetExplorerTest
{
private InternetExplorerDriver _driver;
private string _logLocation;
private string _tempPath;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
if (_tempPath != null && File.Exists(_tempPath))
{
File.Delete(_tempPath);
}
_driver.Quit();
}
[TestMethod]
public void BasicOptionsWin10()
{
var options = new InternetExplorerOptions();
options.AttachToEdgeChrome = true;
options.EdgeExecutablePath = GetEdgeLocation();
_driver = new InternetExplorerDriver(options);
}
[TestMethod]
public void BasicOptionsWin11()
{
var options = new InternetExplorerOptions();
_driver = new InternetExplorerDriver(options);
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToFile()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LogFile = GetLogLocation();
_driver = new InternetExplorerDriver(service);
_driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Console.WriteLine("Lines: {0}", lines);
Assert.IsTrue(lines.Contains("Started InternetExplorerDriver server"));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = InternetExplorerDriverService.CreateDefaultService();
//service.LogToConsole = true;
_driver = new InternetExplorerDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("geckodriver INFO Listening on"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
public void LogsLevel()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LogFile = GetLogLocation();
service.LoggingLevel = InternetExplorerDriverLogLevel.Warn;
_driver = new InternetExplorerDriver(service);
_driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Invalid capability setting: timeouts is type null")));
}
[TestMethod]
public void SupportingFilesLocation()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LibraryExtractionPath = GetTempDirectory();
_driver = new InternetExplorerDriver(service);
Assert.IsTrue(File.Exists(GetTempDirectory() + "/IEDriver.tmp"));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private string GetTempDirectory()
{
if (_tempPath == null || !File.Exists(_tempPath))
{
_tempPath = Path.GetTempPath();
}
return _tempPath;
}
private string GetEdgeLocation()
{
return Environment.GetEnvironmentVariable("EDGE_BIN");
}
}
}
options = Selenium::WebDriver::IE::Options.new
options.attach_to_edge_chrome = true
options.edge_executable_path = edge_location
@driver = Selenium::WebDriver.for :ie, options: options
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
let(:url) { 'https://www.selenium.dev/selenium/web/' }
before do
@options = Selenium::WebDriver::IE::Options.new
@options.attach_to_edge_chrome = true
@options.edge_executable_path = edge_location
end
it 'basic options Win10' do
options = Selenium::WebDriver::IE::Options.new
options.attach_to_edge_chrome = true
options.edge_executable_path = edge_location
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'sets the file upload dialog timeout' do
@options.file_upload_dialog_timeout = 2000
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ensures a clean session' do
@options.ensure_clean_session = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the zoom setting' do
@options.ignore_zoom_level = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the protected mode settings' do
@options.ignore_protected_mode_settings = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
@options.silent = true
expect(@options.silent).to be_truthy
end
it 'sets the command line options' do
@options.add_argument('-k')
Selenium::WebDriver.for(:ie, options: @options)
end
it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
@options.force_create_process_api = true
Selenium::WebDriver.for(:ie, options: @options)
expect(@options.instance_variable_get(:@options)['force_create_process_api'])
.to eq({force_create_process_api: true})
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
A partir do driver versão v4.5.0:
- Se o IE não estiver presente no sistema (ausente por omissão no Windows 11), não necessita usar os parametros “attachToEdgeChrome” e “withEdgeExecutablePath”, pois o IE Driver irá encontrar e usar o Edge automaticamente.
- Se o IE e o Edge estiverem ambos presentes no sistema, use o parametro “attachToEdgeChrome”, o IE Driver irá encontrar e usar o Edge automaticamente.
So, if IE is not on the system, you only need:
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
Show full example
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
public InternetExplorerDriver driver;
private File logLocation;
private File tempDirectory;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
if (tempDirectory != null && tempDirectory.exists()) {
tempDirectory.delete();
}
driver.quit();
}
@Test
public void basicOptionsWin10() {
InternetExplorerOptions options = new InternetExplorerOptions();
options.attachToEdgeChrome();
options.withEdgeExecutablePath(getEdgeLocation());
driver = new InternetExplorerDriver(options);
}
@Test
public void basicOptionsWin11() {
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
@Test
public void logsToFile() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,
getLogLocation().getAbsolutePath());
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogLevel(InternetExplorerDriverLogLevel.WARN)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));
}
@Test
public void supportingFilesLocation() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withExtractPath(getTempDirectory())
.build();
driver = new InternetExplorerDriver(service);
Assertions.assertTrue(new File(getTempDirectory() + "/IEDriver.tmp").exists());
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("iedriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("supporting-").toFile();
}
return tempDirectory;
}
private String getEdgeLocation() {
return System.getenv("EDGE_BIN");
}
}
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = edge_bin
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
options = webdriver.IeOptions()
options.file_upload_timeout = 2000
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
options = webdriver.IeOptions()
options.ensure_clean_session = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
options = webdriver.IeOptions()
options.ignore_zoom_level = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
options = webdriver.IeOptions()
options.ignore_protected_mode_settings = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
service = webdriver.IeService(service_args=["--silent"])
driver = webdriver.Ie(service=service)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
options = webdriver.IeOptions()
options.add_argument("-private")
driver = webdriver.Ie(options=options)
driver.quit()
# Skipping this as it fails on Windows because the value of registry setting in
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0'
@pytest.mark.skip
def test_force_create_process_api():
options = webdriver.IeOptions()
options.force_create_process_api = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.IeService(log_output=log_path, log_level="INFO")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
service = webdriver.IeService(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.IeService(log_output=log_path, log_level="WARN")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
var options = new InternetExplorerOptions();
_driver = new InternetExplorerDriver(options);
Show full example
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.IE;
using SeleniumDocs.TestSupport;
namespace SeleniumDocs.Browsers
{
[TestClassCustom]
[EnabledOnOs("WINDOWS")]
public class InternetExplorerTest
{
private InternetExplorerDriver _driver;
private string _logLocation;
private string _tempPath;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
if (_tempPath != null && File.Exists(_tempPath))
{
File.Delete(_tempPath);
}
_driver.Quit();
}
[TestMethod]
public void BasicOptionsWin10()
{
var options = new InternetExplorerOptions();
options.AttachToEdgeChrome = true;
options.EdgeExecutablePath = GetEdgeLocation();
_driver = new InternetExplorerDriver(options);
}
[TestMethod]
public void BasicOptionsWin11()
{
var options = new InternetExplorerOptions();
_driver = new InternetExplorerDriver(options);
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToFile()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LogFile = GetLogLocation();
_driver = new InternetExplorerDriver(service);
_driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Console.WriteLine("Lines: {0}", lines);
Assert.IsTrue(lines.Contains("Started InternetExplorerDriver server"));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = InternetExplorerDriverService.CreateDefaultService();
//service.LogToConsole = true;
_driver = new InternetExplorerDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("geckodriver INFO Listening on"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
public void LogsLevel()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LogFile = GetLogLocation();
service.LoggingLevel = InternetExplorerDriverLogLevel.Warn;
_driver = new InternetExplorerDriver(service);
_driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Invalid capability setting: timeouts is type null")));
}
[TestMethod]
public void SupportingFilesLocation()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LibraryExtractionPath = GetTempDirectory();
_driver = new InternetExplorerDriver(service);
Assert.IsTrue(File.Exists(GetTempDirectory() + "/IEDriver.tmp"));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private string GetTempDirectory()
{
if (_tempPath == null || !File.Exists(_tempPath))
{
_tempPath = Path.GetTempPath();
}
return _tempPath;
}
private string GetEdgeLocation()
{
return Environment.GetEnvironmentVariable("EDGE_BIN");
}
}
}
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
let(:url) { 'https://www.selenium.dev/selenium/web/' }
before do
@options = Selenium::WebDriver::IE::Options.new
@options.attach_to_edge_chrome = true
@options.edge_executable_path = edge_location
end
it 'basic options Win10' do
options = Selenium::WebDriver::IE::Options.new
options.attach_to_edge_chrome = true
options.edge_executable_path = edge_location
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'sets the file upload dialog timeout' do
@options.file_upload_dialog_timeout = 2000
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ensures a clean session' do
@options.ensure_clean_session = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the zoom setting' do
@options.ignore_zoom_level = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the protected mode settings' do
@options.ignore_protected_mode_settings = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
@options.silent = true
expect(@options.silent).to be_truthy
end
it 'sets the command line options' do
@options.add_argument('-k')
Selenium::WebDriver.for(:ie, options: @options)
end
it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
@options.force_create_process_api = true
Selenium::WebDriver.for(:ie, options: @options)
expect(@options.instance_variable_get(:@options)['force_create_process_api'])
.to eq({force_create_process_api: true})
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
let driver = await new Builder()
.forBrowser('internet explorer')
.setIEOptions(options)
.build();
<p><a href=/documentation/about/contributing/#moving-examples>
<span class="selenium-badge-code" data-bs-toggle="tooltip" data-bs-placement="right"
title="One or more of these examples need to be implemented in the examples directory; click for details in the contribution guide">Move Code</span></a></p>
val options = InternetExplorerOptions()
val driver = InternetExplorerDriver(options)
Aqui pode ver alguns exemplos de utilização com capacidades diferentes:
fileUploadDialogTimeout
Em alguns ambientes, o Internet Explorer pode expirar ao abrir a Caixa de Diálogo de upload de arquivo. O IEDriver tem um tempo limite padrão de 1000 ms, mas você pode aumentar o tempo limite usando o recurso fileUploadDialogTimeout.
InternetExplorerOptions options = new InternetExplorerOptions();
options.waitForUploadDialogUpTo(Duration.ofSeconds(2));
WebDriver driver = new RemoteWebDriver(options);
options = webdriver.IeOptions()
options.file_upload_timeout = 2000
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = edge_bin
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
options = webdriver.IeOptions()
options.file_upload_timeout = 2000
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
options = webdriver.IeOptions()
options.ensure_clean_session = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
options = webdriver.IeOptions()
options.ignore_zoom_level = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
options = webdriver.IeOptions()
options.ignore_protected_mode_settings = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
service = webdriver.IeService(service_args=["--silent"])
driver = webdriver.Ie(service=service)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
options = webdriver.IeOptions()
options.add_argument("-private")
driver = webdriver.Ie(options=options)
driver.quit()
# Skipping this as it fails on Windows because the value of registry setting in
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0'
@pytest.mark.skip
def test_force_create_process_api():
options = webdriver.IeOptions()
options.force_create_process_api = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.IeService(log_output=log_path, log_level="INFO")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
service = webdriver.IeService(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.IeService(log_output=log_path, log_level="WARN")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
var options = new InternetExplorerOptions();
options.FileUploadDialogTimeout = TimeSpan.FromMilliseconds(2000);
var driver = new RemoteWebDriver(options);
@options.file_upload_dialog_timeout = 2000
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
let(:url) { 'https://www.selenium.dev/selenium/web/' }
before do
@options = Selenium::WebDriver::IE::Options.new
@options.attach_to_edge_chrome = true
@options.edge_executable_path = edge_location
end
it 'basic options Win10' do
options = Selenium::WebDriver::IE::Options.new
options.attach_to_edge_chrome = true
options.edge_executable_path = edge_location
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'sets the file upload dialog timeout' do
@options.file_upload_dialog_timeout = 2000
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ensures a clean session' do
@options.ensure_clean_session = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the zoom setting' do
@options.ignore_zoom_level = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the protected mode settings' do
@options.ignore_protected_mode_settings = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
@options.silent = true
expect(@options.silent).to be_truthy
end
it 'sets the command line options' do
@options.add_argument('-k')
Selenium::WebDriver.for(:ie, options: @options)
end
it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
@options.force_create_process_api = true
Selenium::WebDriver.for(:ie, options: @options)
expect(@options.instance_variable_get(:@options)['force_create_process_api'])
.to eq({force_create_process_api: true})
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().fileUploadDialogTimeout(2000);
let driver = await Builder()
.setIeOptions(options)
.build();
val options = InternetExplorerOptions()
options.waitForUploadDialogUpTo(Duration.ofSeconds(2))
val driver = RemoteWebDriver(options)
ensureCleanSession
Quando definido como true
, este recurso limpa o Cache,
Histórico do navegador e cookies para todas as instâncias em execução
do InternetExplorer, incluindo aquelas iniciadas manualmente
ou pelo driver. Por padrão, é definido como false
.
Usar este recurso causará queda de desempenho quando iniciar o navegador, pois o driver irá esperar até que o cache seja limpo antes de iniciar o navegador IE.
Esse recurso aceita um valor booleano como parâmetro.
InternetExplorerOptions options = new InternetExplorerOptions();
options.destructivelyEnsureCleanSession();
WebDriver driver = new RemoteWebDriver(options);
options = webdriver.IeOptions()
options.ensure_clean_session = True
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = edge_bin
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
options = webdriver.IeOptions()
options.file_upload_timeout = 2000
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
options = webdriver.IeOptions()
options.ensure_clean_session = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
options = webdriver.IeOptions()
options.ignore_zoom_level = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
options = webdriver.IeOptions()
options.ignore_protected_mode_settings = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
service = webdriver.IeService(service_args=["--silent"])
driver = webdriver.Ie(service=service)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
options = webdriver.IeOptions()
options.add_argument("-private")
driver = webdriver.Ie(options=options)
driver.quit()
# Skipping this as it fails on Windows because the value of registry setting in
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0'
@pytest.mark.skip
def test_force_create_process_api():
options = webdriver.IeOptions()
options.force_create_process_api = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.IeService(log_output=log_path, log_level="INFO")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
service = webdriver.IeService(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.IeService(log_output=log_path, log_level="WARN")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
var options = new InternetExplorerOptions();
options.EnsureCleanSession = true;
var driver = new RemoteWebDriver(options);
@options.ensure_clean_session = true
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
let(:url) { 'https://www.selenium.dev/selenium/web/' }
before do
@options = Selenium::WebDriver::IE::Options.new
@options.attach_to_edge_chrome = true
@options.edge_executable_path = edge_location
end
it 'basic options Win10' do
options = Selenium::WebDriver::IE::Options.new
options.attach_to_edge_chrome = true
options.edge_executable_path = edge_location
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'sets the file upload dialog timeout' do
@options.file_upload_dialog_timeout = 2000
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ensures a clean session' do
@options.ensure_clean_session = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the zoom setting' do
@options.ignore_zoom_level = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the protected mode settings' do
@options.ignore_protected_mode_settings = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
@options.silent = true
expect(@options.silent).to be_truthy
end
it 'sets the command line options' do
@options.add_argument('-k')
Selenium::WebDriver.for(:ie, options: @options)
end
it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
@options.force_create_process_api = true
Selenium::WebDriver.for(:ie, options: @options)
expect(@options.instance_variable_get(:@options)['force_create_process_api'])
.to eq({force_create_process_api: true})
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().ensureCleanSession(true);
let driver = await Builder()
.setIeOptions(options)
.build();
val options = InternetExplorerOptions()
options.destructivelyEnsureCleanSession()
val driver = RemoteWebDriver(options)
ignoreZoomSetting
O driver do InternetExplorer espera que o nível de zoom do navegador seja de 100%, caso contrário, o driver lançará uma exceção. Este comportamento padrão pode ser desativado definindo ignoreZoomSetting como true.
Esse recurso aceita um valor booleano como parâmetro.
InternetExplorerOptions options = new InternetExplorerOptions();
options.ignoreZoomSettings();
WebDriver driver = new RemoteWebDriver(options);
options = webdriver.IeOptions()
options.ignore_zoom_level = True
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = edge_bin
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
options = webdriver.IeOptions()
options.file_upload_timeout = 2000
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
options = webdriver.IeOptions()
options.ensure_clean_session = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
options = webdriver.IeOptions()
options.ignore_zoom_level = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
options = webdriver.IeOptions()
options.ignore_protected_mode_settings = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
service = webdriver.IeService(service_args=["--silent"])
driver = webdriver.Ie(service=service)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
options = webdriver.IeOptions()
options.add_argument("-private")
driver = webdriver.Ie(options=options)
driver.quit()
# Skipping this as it fails on Windows because the value of registry setting in
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0'
@pytest.mark.skip
def test_force_create_process_api():
options = webdriver.IeOptions()
options.force_create_process_api = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.IeService(log_output=log_path, log_level="INFO")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
service = webdriver.IeService(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.IeService(log_output=log_path, log_level="WARN")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
var options = new InternetExplorerOptions();
options.IgnoreZoomLevel = true;
var driver = new RemoteWebDriver(options);
@options.ignore_zoom_level = true
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
let(:url) { 'https://www.selenium.dev/selenium/web/' }
before do
@options = Selenium::WebDriver::IE::Options.new
@options.attach_to_edge_chrome = true
@options.edge_executable_path = edge_location
end
it 'basic options Win10' do
options = Selenium::WebDriver::IE::Options.new
options.attach_to_edge_chrome = true
options.edge_executable_path = edge_location
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'sets the file upload dialog timeout' do
@options.file_upload_dialog_timeout = 2000
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ensures a clean session' do
@options.ensure_clean_session = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the zoom setting' do
@options.ignore_zoom_level = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the protected mode settings' do
@options.ignore_protected_mode_settings = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
@options.silent = true
expect(@options.silent).to be_truthy
end
it 'sets the command line options' do
@options.add_argument('-k')
Selenium::WebDriver.for(:ie, options: @options)
end
it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
@options.force_create_process_api = true
Selenium::WebDriver.for(:ie, options: @options)
expect(@options.instance_variable_get(:@options)['force_create_process_api'])
.to eq({force_create_process_api: true})
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().ignoreZoomSetting(true);
let driver = await Builder()
.setIeOptions(options)
.build();
val options = InternetExplorerOptions()
options.ignoreZoomSettings()
val driver = RemoteWebDriver(options)
ignoreProtectedModeSettings
Se deve ignorar a verificação do Modo protegido durante o lançamento uma nova sessão do IE.
Se não for definido e as configurações do Modo protegido não forem iguais para todas as zonas, uma exceção será lançada pelo driver.
Se a capacidade for definida como true
, os testes podem
tornar-se instáveis, não responderem ou os navegadores podem travar.
No entanto, esta ainda é de longe a segunda melhor escolha,
e a primeira escolha sempre deve ser
definir as configurações do Modo protegido de cada zona manualmente.
Se um usuário estiver usando esta propriedade,
apenas um “melhor esforço” no suporte será dado.
Esse recurso aceita um valor booleano como parâmetro.
InternetExplorerOptions options = new InternetExplorerOptions();
options.introduceFlakinessByIgnoringSecurityDomains();
WebDriver driver = new RemoteWebDriver(options);
options = webdriver.IeOptions()
options.ignore_protected_mode_settings = True
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = edge_bin
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
options = webdriver.IeOptions()
options.file_upload_timeout = 2000
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
options = webdriver.IeOptions()
options.ensure_clean_session = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
options = webdriver.IeOptions()
options.ignore_zoom_level = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
options = webdriver.IeOptions()
options.ignore_protected_mode_settings = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
service = webdriver.IeService(service_args=["--silent"])
driver = webdriver.Ie(service=service)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
options = webdriver.IeOptions()
options.add_argument("-private")
driver = webdriver.Ie(options=options)
driver.quit()
# Skipping this as it fails on Windows because the value of registry setting in
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0'
@pytest.mark.skip
def test_force_create_process_api():
options = webdriver.IeOptions()
options.force_create_process_api = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.IeService(log_output=log_path, log_level="INFO")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
service = webdriver.IeService(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.IeService(log_output=log_path, log_level="WARN")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
var options = new InternetExplorerOptions();
options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
var driver = new RemoteWebDriver(options);
@options.ignore_protected_mode_settings = true
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
let(:url) { 'https://www.selenium.dev/selenium/web/' }
before do
@options = Selenium::WebDriver::IE::Options.new
@options.attach_to_edge_chrome = true
@options.edge_executable_path = edge_location
end
it 'basic options Win10' do
options = Selenium::WebDriver::IE::Options.new
options.attach_to_edge_chrome = true
options.edge_executable_path = edge_location
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'sets the file upload dialog timeout' do
@options.file_upload_dialog_timeout = 2000
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ensures a clean session' do
@options.ensure_clean_session = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the zoom setting' do
@options.ignore_zoom_level = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the protected mode settings' do
@options.ignore_protected_mode_settings = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
@options.silent = true
expect(@options.silent).to be_truthy
end
it 'sets the command line options' do
@options.add_argument('-k')
Selenium::WebDriver.for(:ie, options: @options)
end
it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
@options.force_create_process_api = true
Selenium::WebDriver.for(:ie, options: @options)
expect(@options.instance_variable_get(:@options)['force_create_process_api'])
.to eq({force_create_process_api: true})
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().introduceFlakinessByIgnoringProtectedModeSettings(true);
let driver = await Builder()
.setIeOptions(options)
.build();
val options = InternetExplorerOptions()
options.introduceFlakinessByIgnoringSecurityDomains()
val driver = RemoteWebDriver(options)
silent
Quando definido como true
, esse recurso suprime a
saída de diagnóstico do IEDriverServer.
Esse recurso aceita um valor booleano como parâmetro.
InternetExplorerOptions options = new InternetExplorerOptions();
options.setCapability("silent", true);
WebDriver driver = new InternetExplorerDriver(options);
service = webdriver.IeService(service_args=["--silent"])
driver = webdriver.Ie(service=service)
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = edge_bin
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
options = webdriver.IeOptions()
options.file_upload_timeout = 2000
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
options = webdriver.IeOptions()
options.ensure_clean_session = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
options = webdriver.IeOptions()
options.ignore_zoom_level = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
options = webdriver.IeOptions()
options.ignore_protected_mode_settings = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
service = webdriver.IeService(service_args=["--silent"])
driver = webdriver.Ie(service=service)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
options = webdriver.IeOptions()
options.add_argument("-private")
driver = webdriver.Ie(options=options)
driver.quit()
# Skipping this as it fails on Windows because the value of registry setting in
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0'
@pytest.mark.skip
def test_force_create_process_api():
options = webdriver.IeOptions()
options.force_create_process_api = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.IeService(log_output=log_path, log_level="INFO")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
service = webdriver.IeService(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.IeService(log_output=log_path, log_level="WARN")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
InternetExplorerOptions options = new InternetExplorerOptions();
options.AddAdditionalInternetExplorerOption("silent", true);
IWebDriver driver = new InternetExplorerDriver(options);
@options.silent = true
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
let(:url) { 'https://www.selenium.dev/selenium/web/' }
before do
@options = Selenium::WebDriver::IE::Options.new
@options.attach_to_edge_chrome = true
@options.edge_executable_path = edge_location
end
it 'basic options Win10' do
options = Selenium::WebDriver::IE::Options.new
options.attach_to_edge_chrome = true
options.edge_executable_path = edge_location
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'sets the file upload dialog timeout' do
@options.file_upload_dialog_timeout = 2000
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ensures a clean session' do
@options.ensure_clean_session = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the zoom setting' do
@options.ignore_zoom_level = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the protected mode settings' do
@options.ignore_protected_mode_settings = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
@options.silent = true
expect(@options.silent).to be_truthy
end
it 'sets the command line options' do
@options.add_argument('-k')
Selenium::WebDriver.for(:ie, options: @options)
end
it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
@options.force_create_process_api = true
Selenium::WebDriver.for(:ie, options: @options)
expect(@options.instance_variable_get(:@options)['force_create_process_api'])
.to eq({force_create_process_api: true})
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
const {Builder,By, Capabilities} = require('selenium-webdriver');
let caps = Capabilities.ie();
caps.set('silent', true);
(async function example() {
let driver = await new Builder()
.forBrowser('internet explorer')
.withCapabilities(caps)
.build();
try {
await driver.get('http://www.google.com/ncr');
}
finally {
await driver.quit();
}
})();
import org.openqa.selenium.Capabilities
import org.openqa.selenium.ie.InternetExplorerDriver
import org.openqa.selenium.ie.InternetExplorerOptions
fun main() {
val options = InternetExplorerOptions()
options.setCapability("silent", true)
val driver = InternetExplorerDriver(options)
try {
driver.get("https://google.com/ncr")
val caps = driver.getCapabilities()
println(caps)
} finally {
driver.quit()
}
}
Opções de linha de comando do IE
O Internet Explorer inclui várias opções de linha de comando que permitem solucionar problemas e configurar o navegador.
Os seguintes pontos descrevem algumas opções de linha de comando com suporte
-private: Usado para iniciar o IE no modo de navegação privada. Isso funciona para o IE 8 e versões posteriores.
-k: Inicia o Internet Explorer no modo quiosque. O navegador é aberto em uma janela maximizada que não exibe a barra de endereço, os botões de navegação ou a barra de status.
-extoff: Inicia o IE no modo sem add-on. Esta opção é usada especificamente para solucionar problemas com complementos do navegador. Funciona no IE 7 e versões posteriores.
Nota: forceCreateProcessApi deve ser habilitado para que os argumentos da linha de comando funcionem.
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
public class ieTest {
public static void main(String[] args) {
InternetExplorerOptions options = new InternetExplorerOptions();
options.useCreateProcessApiToLaunchIe();
options.addCommandSwitches("-k");
InternetExplorerDriver driver = new InternetExplorerDriver(options);
try {
driver.get("https://google.com/ncr");
Capabilities caps = driver.getCapabilities();
System.out.println(caps);
} finally {
driver.quit();
}
}
}
options = webdriver.IeOptions()
options.add_argument("-private")
driver = webdriver.Ie(options=options)
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = edge_bin
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
options = webdriver.IeOptions()
options.file_upload_timeout = 2000
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
options = webdriver.IeOptions()
options.ensure_clean_session = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
options = webdriver.IeOptions()
options.ignore_zoom_level = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
options = webdriver.IeOptions()
options.ignore_protected_mode_settings = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
service = webdriver.IeService(service_args=["--silent"])
driver = webdriver.Ie(service=service)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
options = webdriver.IeOptions()
options.add_argument("-private")
driver = webdriver.Ie(options=options)
driver.quit()
# Skipping this as it fails on Windows because the value of registry setting in
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0'
@pytest.mark.skip
def test_force_create_process_api():
options = webdriver.IeOptions()
options.force_create_process_api = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.IeService(log_output=log_path, log_level="INFO")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
service = webdriver.IeService(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.IeService(log_output=log_path, log_level="WARN")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
namespace ieTest {
class Program {
static void Main(string[] args) {
InternetExplorerOptions options = new InternetExplorerOptions();
options.ForceCreateProcessApi = true;
options.BrowserCommandLineArguments = "-k";
IWebDriver driver = new InternetExplorerDriver(options);
driver.Url = "https://google.com/ncr";
}
}
}
@options.add_argument('-k')
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
let(:url) { 'https://www.selenium.dev/selenium/web/' }
before do
@options = Selenium::WebDriver::IE::Options.new
@options.attach_to_edge_chrome = true
@options.edge_executable_path = edge_location
end
it 'basic options Win10' do
options = Selenium::WebDriver::IE::Options.new
options.attach_to_edge_chrome = true
options.edge_executable_path = edge_location
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'sets the file upload dialog timeout' do
@options.file_upload_dialog_timeout = 2000
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ensures a clean session' do
@options.ensure_clean_session = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the zoom setting' do
@options.ignore_zoom_level = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the protected mode settings' do
@options.ignore_protected_mode_settings = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
@options.silent = true
expect(@options.silent).to be_truthy
end
it 'sets the command line options' do
@options.add_argument('-k')
Selenium::WebDriver.for(:ie, options: @options)
end
it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
@options.force_create_process_api = true
Selenium::WebDriver.for(:ie, options: @options)
expect(@options.instance_variable_get(:@options)['force_create_process_api'])
.to eq({force_create_process_api: true})
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options();
options.addBrowserCommandSwitches('-k');
options.addBrowserCommandSwitches('-private');
options.forceCreateProcessApi(true);
driver = await env.builder()
.setIeOptions(options)
.build();
import org.openqa.selenium.Capabilities
import org.openqa.selenium.ie.InternetExplorerDriver
import org.openqa.selenium.ie.InternetExplorerOptions
fun main() {
val options = InternetExplorerOptions()
options.useCreateProcessApiToLaunchIe()
options.addCommandSwitches("-k")
val driver = InternetExplorerDriver(options)
try {
driver.get("https://google.com/ncr")
val caps = driver.getCapabilities()
println(caps)
} finally {
driver.quit()
}
}
forceCreateProcessApi
Força a inicialização do Internet Explorer usando a API CreateProcess. O valor padrão é falso.
Para IE 8 e superior, esta opção requer que o valor de registro “TabProcGrowth” seja definido como 0.
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
public class ieTest {
public static void main(String[] args) {
InternetExplorerOptions options = new InternetExplorerOptions();
options.useCreateProcessApiToLaunchIe();
InternetExplorerDriver driver = new InternetExplorerDriver(options);
try {
driver.get("https://google.com/ncr");
Capabilities caps = driver.getCapabilities();
System.out.println(caps);
} finally {
driver.quit();
}
}
}
options = webdriver.IeOptions()
options.force_create_process_api = True
driver = webdriver.Ie(options=options)
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = edge_bin
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
options = webdriver.IeOptions()
options.file_upload_timeout = 2000
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
options = webdriver.IeOptions()
options.ensure_clean_session = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
options = webdriver.IeOptions()
options.ignore_zoom_level = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
options = webdriver.IeOptions()
options.ignore_protected_mode_settings = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
service = webdriver.IeService(service_args=["--silent"])
driver = webdriver.Ie(service=service)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
options = webdriver.IeOptions()
options.add_argument("-private")
driver = webdriver.Ie(options=options)
driver.quit()
# Skipping this as it fails on Windows because the value of registry setting in
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0'
@pytest.mark.skip
def test_force_create_process_api():
options = webdriver.IeOptions()
options.force_create_process_api = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.IeService(log_output=log_path, log_level="INFO")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
service = webdriver.IeService(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.IeService(log_output=log_path, log_level="WARN")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
namespace ieTest {
class Program {
static void Main(string[] args) {
InternetExplorerOptions options = new InternetExplorerOptions();
options.ForceCreateProcessApi = true;
IWebDriver driver = new InternetExplorerDriver(options);
driver.Url = "https://google.com/ncr";
}
}
}
@options.force_create_process_api = true
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
let(:url) { 'https://www.selenium.dev/selenium/web/' }
before do
@options = Selenium::WebDriver::IE::Options.new
@options.attach_to_edge_chrome = true
@options.edge_executable_path = edge_location
end
it 'basic options Win10' do
options = Selenium::WebDriver::IE::Options.new
options.attach_to_edge_chrome = true
options.edge_executable_path = edge_location
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'sets the file upload dialog timeout' do
@options.file_upload_dialog_timeout = 2000
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ensures a clean session' do
@options.ensure_clean_session = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the zoom setting' do
@options.ignore_zoom_level = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the protected mode settings' do
@options.ignore_protected_mode_settings = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
@options.silent = true
expect(@options.silent).to be_truthy
end
it 'sets the command line options' do
@options.add_argument('-k')
Selenium::WebDriver.for(:ie, options: @options)
end
it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
@options.force_create_process_api = true
Selenium::WebDriver.for(:ie, options: @options)
expect(@options.instance_variable_get(:@options)['force_create_process_api'])
.to eq({force_create_process_api: true})
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options();
options.forceCreateProcessApi(true);
driver = await env.builder()
.setIeOptions(options)
.build();
import org.openqa.selenium.Capabilities
import org.openqa.selenium.ie.InternetExplorerDriver
import org.openqa.selenium.ie.InternetExplorerOptions
fun main() {
val options = InternetExplorerOptions()
options.useCreateProcessApiToLaunchIe()
val driver = InternetExplorerDriver(options)
try {
driver.get("https://google.com/ncr")
val caps = driver.getCapabilities()
println(caps)
} finally {
driver.quit()
}
}
Service
Service settings common to all browsers are described on the Service page.
Log output
Getting driver logs can be helpful for debugging various issues. The Service class lets you direct where the logs will go. Logging output is ignored unless the user directs it somewhere.
File output
To change the logging output to save to a specific file:
.withLogFile(getLogLocation())
Show full example
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
public InternetExplorerDriver driver;
private File logLocation;
private File tempDirectory;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
if (tempDirectory != null && tempDirectory.exists()) {
tempDirectory.delete();
}
driver.quit();
}
@Test
public void basicOptionsWin10() {
InternetExplorerOptions options = new InternetExplorerOptions();
options.attachToEdgeChrome();
options.withEdgeExecutablePath(getEdgeLocation());
driver = new InternetExplorerDriver(options);
}
@Test
public void basicOptionsWin11() {
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
@Test
public void logsToFile() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,
getLogLocation().getAbsolutePath());
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogLevel(InternetExplorerDriverLogLevel.WARN)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));
}
@Test
public void supportingFilesLocation() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withExtractPath(getTempDirectory())
.build();
driver = new InternetExplorerDriver(service);
Assertions.assertTrue(new File(getTempDirectory() + "/IEDriver.tmp").exists());
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("iedriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("supporting-").toFile();
}
return tempDirectory;
}
private String getEdgeLocation() {
return System.getenv("EDGE_BIN");
}
}
Note: Java also allows setting file output by System Property:
Property key: InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY
Property value: String representing path to log file
service = webdriver.IeService(log_output=log_path, log_level="INFO")
driver = webdriver.Ie(service=service)
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = edge_bin
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
options = webdriver.IeOptions()
options.file_upload_timeout = 2000
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
options = webdriver.IeOptions()
options.ensure_clean_session = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
options = webdriver.IeOptions()
options.ignore_zoom_level = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
options = webdriver.IeOptions()
options.ignore_protected_mode_settings = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
service = webdriver.IeService(service_args=["--silent"])
driver = webdriver.Ie(service=service)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
options = webdriver.IeOptions()
options.add_argument("-private")
driver = webdriver.Ie(options=options)
driver.quit()
# Skipping this as it fails on Windows because the value of registry setting in
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0'
@pytest.mark.skip
def test_force_create_process_api():
options = webdriver.IeOptions()
options.force_create_process_api = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.IeService(log_output=log_path, log_level="INFO")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
service = webdriver.IeService(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.IeService(log_output=log_path, log_level="WARN")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
service.log = file_name
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
let(:url) { 'https://www.selenium.dev/selenium/web/' }
before do
@options = Selenium::WebDriver::IE::Options.new
@options.attach_to_edge_chrome = true
@options.edge_executable_path = edge_location
end
it 'basic options Win10' do
options = Selenium::WebDriver::IE::Options.new
options.attach_to_edge_chrome = true
options.edge_executable_path = edge_location
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'sets the file upload dialog timeout' do
@options.file_upload_dialog_timeout = 2000
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ensures a clean session' do
@options.ensure_clean_session = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the zoom setting' do
@options.ignore_zoom_level = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the protected mode settings' do
@options.ignore_protected_mode_settings = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
@options.silent = true
expect(@options.silent).to be_truthy
end
it 'sets the command line options' do
@options.add_argument('-k')
Selenium::WebDriver.for(:ie, options: @options)
end
it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
@options.force_create_process_api = true
Selenium::WebDriver.for(:ie, options: @options)
expect(@options.instance_variable_get(:@options)['force_create_process_api'])
.to eq({force_create_process_api: true})
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
Console output
To change the logging output to display in the console as STDOUT:
.withLogOutput(System.out)
Show full example
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
public InternetExplorerDriver driver;
private File logLocation;
private File tempDirectory;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
if (tempDirectory != null && tempDirectory.exists()) {
tempDirectory.delete();
}
driver.quit();
}
@Test
public void basicOptionsWin10() {
InternetExplorerOptions options = new InternetExplorerOptions();
options.attachToEdgeChrome();
options.withEdgeExecutablePath(getEdgeLocation());
driver = new InternetExplorerDriver(options);
}
@Test
public void basicOptionsWin11() {
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
@Test
public void logsToFile() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,
getLogLocation().getAbsolutePath());
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogLevel(InternetExplorerDriverLogLevel.WARN)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));
}
@Test
public void supportingFilesLocation() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withExtractPath(getTempDirectory())
.build();
driver = new InternetExplorerDriver(service);
Assertions.assertTrue(new File(getTempDirectory() + "/IEDriver.tmp").exists());
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("iedriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("supporting-").toFile();
}
return tempDirectory;
}
private String getEdgeLocation() {
return System.getenv("EDGE_BIN");
}
}
Note: Java also allows setting console output by System Property;
Property key: InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY
Property value: DriverService.LOG_STDOUT
or DriverService.LOG_STDERR
service = webdriver.IeService(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = edge_bin
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
options = webdriver.IeOptions()
options.file_upload_timeout = 2000
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
options = webdriver.IeOptions()
options.ensure_clean_session = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
options = webdriver.IeOptions()
options.ignore_zoom_level = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
options = webdriver.IeOptions()
options.ignore_protected_mode_settings = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
service = webdriver.IeService(service_args=["--silent"])
driver = webdriver.Ie(service=service)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
options = webdriver.IeOptions()
options.add_argument("-private")
driver = webdriver.Ie(options=options)
driver.quit()
# Skipping this as it fails on Windows because the value of registry setting in
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0'
@pytest.mark.skip
def test_force_create_process_api():
options = webdriver.IeOptions()
options.force_create_process_api = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.IeService(log_output=log_path, log_level="INFO")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
service = webdriver.IeService(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.IeService(log_output=log_path, log_level="WARN")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
service.log = $stdout
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
let(:url) { 'https://www.selenium.dev/selenium/web/' }
before do
@options = Selenium::WebDriver::IE::Options.new
@options.attach_to_edge_chrome = true
@options.edge_executable_path = edge_location
end
it 'basic options Win10' do
options = Selenium::WebDriver::IE::Options.new
options.attach_to_edge_chrome = true
options.edge_executable_path = edge_location
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'sets the file upload dialog timeout' do
@options.file_upload_dialog_timeout = 2000
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ensures a clean session' do
@options.ensure_clean_session = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the zoom setting' do
@options.ignore_zoom_level = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the protected mode settings' do
@options.ignore_protected_mode_settings = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
@options.silent = true
expect(@options.silent).to be_truthy
end
it 'sets the command line options' do
@options.add_argument('-k')
Selenium::WebDriver.for(:ie, options: @options)
end
it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
@options.force_create_process_api = true
Selenium::WebDriver.for(:ie, options: @options)
expect(@options.instance_variable_get(:@options)['force_create_process_api'])
.to eq({force_create_process_api: true})
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
Log Level
There are 6 available log levels: FATAL
, ERROR
, WARN
, INFO
, DEBUG
, and TRACE
If logging output is specified, the default level is FATAL
.withLogLevel(InternetExplorerDriverLogLevel.WARN)
Show full example
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
public InternetExplorerDriver driver;
private File logLocation;
private File tempDirectory;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
if (tempDirectory != null && tempDirectory.exists()) {
tempDirectory.delete();
}
driver.quit();
}
@Test
public void basicOptionsWin10() {
InternetExplorerOptions options = new InternetExplorerOptions();
options.attachToEdgeChrome();
options.withEdgeExecutablePath(getEdgeLocation());
driver = new InternetExplorerDriver(options);
}
@Test
public void basicOptionsWin11() {
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
@Test
public void logsToFile() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,
getLogLocation().getAbsolutePath());
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogLevel(InternetExplorerDriverLogLevel.WARN)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));
}
@Test
public void supportingFilesLocation() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withExtractPath(getTempDirectory())
.build();
driver = new InternetExplorerDriver(service);
Assertions.assertTrue(new File(getTempDirectory() + "/IEDriver.tmp").exists());
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("iedriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("supporting-").toFile();
}
return tempDirectory;
}
private String getEdgeLocation() {
return System.getenv("EDGE_BIN");
}
}
Note: Java also allows setting log level by System Property:
Property key: InternetExplorerDriverService.IE_DRIVER_LOGLEVEL_PROPERTY
Property value: String representation of InternetExplorerDriverLogLevel.DEBUG.toString()
enum
service = webdriver.IeService(log_output=log_path, log_level="WARN")
driver = webdriver.Ie(service=service)
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = edge_bin
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
options = webdriver.IeOptions()
options.file_upload_timeout = 2000
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
options = webdriver.IeOptions()
options.ensure_clean_session = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
options = webdriver.IeOptions()
options.ignore_zoom_level = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
options = webdriver.IeOptions()
options.ignore_protected_mode_settings = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
service = webdriver.IeService(service_args=["--silent"])
driver = webdriver.Ie(service=service)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
options = webdriver.IeOptions()
options.add_argument("-private")
driver = webdriver.Ie(options=options)
driver.quit()
# Skipping this as it fails on Windows because the value of registry setting in
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0'
@pytest.mark.skip
def test_force_create_process_api():
options = webdriver.IeOptions()
options.force_create_process_api = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.IeService(log_output=log_path, log_level="INFO")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
service = webdriver.IeService(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.IeService(log_output=log_path, log_level="WARN")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
Show full example
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.IE;
using SeleniumDocs.TestSupport;
namespace SeleniumDocs.Browsers
{
[TestClassCustom]
[EnabledOnOs("WINDOWS")]
public class InternetExplorerTest
{
private InternetExplorerDriver _driver;
private string _logLocation;
private string _tempPath;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
if (_tempPath != null && File.Exists(_tempPath))
{
File.Delete(_tempPath);
}
_driver.Quit();
}
[TestMethod]
public void BasicOptionsWin10()
{
var options = new InternetExplorerOptions();
options.AttachToEdgeChrome = true;
options.EdgeExecutablePath = GetEdgeLocation();
_driver = new InternetExplorerDriver(options);
}
[TestMethod]
public void BasicOptionsWin11()
{
var options = new InternetExplorerOptions();
_driver = new InternetExplorerDriver(options);
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToFile()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LogFile = GetLogLocation();
_driver = new InternetExplorerDriver(service);
_driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Console.WriteLine("Lines: {0}", lines);
Assert.IsTrue(lines.Contains("Started InternetExplorerDriver server"));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = InternetExplorerDriverService.CreateDefaultService();
//service.LogToConsole = true;
_driver = new InternetExplorerDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("geckodriver INFO Listening on"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
public void LogsLevel()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LogFile = GetLogLocation();
service.LoggingLevel = InternetExplorerDriverLogLevel.Warn;
_driver = new InternetExplorerDriver(service);
_driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Invalid capability setting: timeouts is type null")));
}
[TestMethod]
public void SupportingFilesLocation()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LibraryExtractionPath = GetTempDirectory();
_driver = new InternetExplorerDriver(service);
Assert.IsTrue(File.Exists(GetTempDirectory() + "/IEDriver.tmp"));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private string GetTempDirectory()
{
if (_tempPath == null || !File.Exists(_tempPath))
{
_tempPath = Path.GetTempPath();
}
return _tempPath;
}
private string GetEdgeLocation()
{
return Environment.GetEnvironmentVariable("EDGE_BIN");
}
}
}
service.args << '-log-level=WARN'
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
let(:url) { 'https://www.selenium.dev/selenium/web/' }
before do
@options = Selenium::WebDriver::IE::Options.new
@options.attach_to_edge_chrome = true
@options.edge_executable_path = edge_location
end
it 'basic options Win10' do
options = Selenium::WebDriver::IE::Options.new
options.attach_to_edge_chrome = true
options.edge_executable_path = edge_location
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'sets the file upload dialog timeout' do
@options.file_upload_dialog_timeout = 2000
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ensures a clean session' do
@options.ensure_clean_session = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the zoom setting' do
@options.ignore_zoom_level = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the protected mode settings' do
@options.ignore_protected_mode_settings = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
@options.silent = true
expect(@options.silent).to be_truthy
end
it 'sets the command line options' do
@options.add_argument('-k')
Selenium::WebDriver.for(:ie, options: @options)
end
it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
@options.force_create_process_api = true
Selenium::WebDriver.for(:ie, options: @options)
expect(@options.instance_variable_get(:@options)['force_create_process_api'])
.to eq({force_create_process_api: true})
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
Supporting Files Path
.withExtractPath(getTempDirectory())
Show full example
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
public InternetExplorerDriver driver;
private File logLocation;
private File tempDirectory;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
if (tempDirectory != null && tempDirectory.exists()) {
tempDirectory.delete();
}
driver.quit();
}
@Test
public void basicOptionsWin10() {
InternetExplorerOptions options = new InternetExplorerOptions();
options.attachToEdgeChrome();
options.withEdgeExecutablePath(getEdgeLocation());
driver = new InternetExplorerDriver(options);
}
@Test
public void basicOptionsWin11() {
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
@Test
public void logsToFile() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,
getLogLocation().getAbsolutePath());
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogLevel(InternetExplorerDriverLogLevel.WARN)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));
}
@Test
public void supportingFilesLocation() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withExtractPath(getTempDirectory())
.build();
driver = new InternetExplorerDriver(service);
Assertions.assertTrue(new File(getTempDirectory() + "/IEDriver.tmp").exists());
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("iedriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("supporting-").toFile();
}
return tempDirectory;
}
private String getEdgeLocation() {
return System.getenv("EDGE_BIN");
}
}
service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])
driver = webdriver.Ie(service=service)
Show full example
import os
import subprocess
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = edge_bin
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
options = webdriver.IeOptions()
options.file_upload_timeout = 2000
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
options = webdriver.IeOptions()
options.ensure_clean_session = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
options = webdriver.IeOptions()
options.ignore_zoom_level = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
options = webdriver.IeOptions()
options.ignore_protected_mode_settings = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
service = webdriver.IeService(service_args=["--silent"])
driver = webdriver.Ie(service=service)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
options = webdriver.IeOptions()
options.add_argument("-private")
driver = webdriver.Ie(options=options)
driver.quit()
# Skipping this as it fails on Windows because the value of registry setting in
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0'
@pytest.mark.skip
def test_force_create_process_api():
options = webdriver.IeOptions()
options.force_create_process_api = True
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.IeService(log_output=log_path, log_level="INFO")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
service = webdriver.IeService(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.IeService(log_output=log_path, log_level="WARN")
driver = webdriver.Ie(service=service)
with open(log_path, "r") as fp:
assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
Show full example
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.IE;
using SeleniumDocs.TestSupport;
namespace SeleniumDocs.Browsers
{
[TestClassCustom]
[EnabledOnOs("WINDOWS")]
public class InternetExplorerTest
{
private InternetExplorerDriver _driver;
private string _logLocation;
private string _tempPath;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
if (_tempPath != null && File.Exists(_tempPath))
{
File.Delete(_tempPath);
}
_driver.Quit();
}
[TestMethod]
public void BasicOptionsWin10()
{
var options = new InternetExplorerOptions();
options.AttachToEdgeChrome = true;
options.EdgeExecutablePath = GetEdgeLocation();
_driver = new InternetExplorerDriver(options);
}
[TestMethod]
public void BasicOptionsWin11()
{
var options = new InternetExplorerOptions();
_driver = new InternetExplorerDriver(options);
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToFile()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LogFile = GetLogLocation();
_driver = new InternetExplorerDriver(service);
_driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Console.WriteLine("Lines: {0}", lines);
Assert.IsTrue(lines.Contains("Started InternetExplorerDriver server"));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = InternetExplorerDriverService.CreateDefaultService();
//service.LogToConsole = true;
_driver = new InternetExplorerDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("geckodriver INFO Listening on"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
public void LogsLevel()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LogFile = GetLogLocation();
service.LoggingLevel = InternetExplorerDriverLogLevel.Warn;
_driver = new InternetExplorerDriver(service);
_driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Invalid capability setting: timeouts is type null")));
}
[TestMethod]
public void SupportingFilesLocation()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LibraryExtractionPath = GetTempDirectory();
_driver = new InternetExplorerDriver(service);
Assert.IsTrue(File.Exists(GetTempDirectory() + "/IEDriver.tmp"));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private string GetTempDirectory()
{
if (_tempPath == null || !File.Exists(_tempPath))
{
_tempPath = Path.GetTempPath();
}
return _tempPath;
}
private string GetEdgeLocation()
{
return Environment.GetEnvironmentVariable("EDGE_BIN");
}
}
}
service.args << "–extract-path=#{root_directory}"
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
let(:url) { 'https://www.selenium.dev/selenium/web/' }
before do
@options = Selenium::WebDriver::IE::Options.new
@options.attach_to_edge_chrome = true
@options.edge_executable_path = edge_location
end
it 'basic options Win10' do
options = Selenium::WebDriver::IE::Options.new
options.attach_to_edge_chrome = true
options.edge_executable_path = edge_location
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'sets the file upload dialog timeout' do
@options.file_upload_dialog_timeout = 2000
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ensures a clean session' do
@options.ensure_clean_session = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the zoom setting' do
@options.ignore_zoom_level = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'ignores the protected mode settings' do
@options.ignore_protected_mode_settings = true
driver = Selenium::WebDriver.for(:ie, options: @options)
driver.quit
end
it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
@options.silent = true
expect(@options.silent).to be_truthy
end
it 'sets the command line options' do
@options.add_argument('-k')
Selenium::WebDriver.for(:ie, options: @options)
end
it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
@options.force_create_process_api = true
Selenium::WebDriver.for(:ie, options: @options)
expect(@options.instance_variable_get(:@options)['force_create_process_api'])
.to eq({force_create_process_api: true})
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
5 - Funcionalidade específica do Safari
Ao invés dos drivers para Chromium e Firefox, o safaridriver faz parte to sistema Operativo. Para activar a automação no Safari, execute o seguinte comando no terminal:
safaridriver --enable
Opções
Capacidades comuns a todos os navegadores estão descritas na página Opções.
Capacidades únicas ao Safari podem ser encontradas na página da Apple WebDriver para Safari
Este é um exemplo de como iniciar uma sessão Safari com um conjunto de opções básicas::
SafariOptions options = new SafariOptions();
driver = new SafariDriver(options);
Show full example
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.safari.SafariDriverService;
import org.openqa.selenium.safari.SafariOptions;
@EnabledOnOs(OS.MAC)
public class SafariTest {
public SafariDriver driver;
@AfterEach
public void quit() {
if (driver != null) {
driver.quit();
}
}
@Test
public void basicOptions() {
SafariOptions options = new SafariOptions();
driver = new SafariDriver(options);
}
@Test
public void enableLogs() {
SafariDriverService service = new SafariDriverService.Builder()
.withLogging(true)
.build();
driver = new SafariDriver(service);
}
public void safariTechnologyPreview() {
SafariOptions options = new SafariOptions();
options.setUseTechnologyPreview(true);
driver = new SafariDriver(options);
}
}
options = webdriver.SafariOptions()
driver = webdriver.Safari(options=options)
Show full example
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_basic_options():
options = webdriver.SafariOptions()
driver = webdriver.Safari(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_enable_logging():
service = webdriver.SafariService(enable_logging=True)
driver = webdriver.Safari(service=service)
driver.quit()
@pytest.mark.skip(reason="Not installed on Mac GitHub Actions Runner Image")
def test_technology_preview():
options = webdriver.SafariOptions()
options.use_technology_preview = True
service = webdriver.SafariService(
executable_path='/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver'
)
driver = webdriver.Safari(options=options, service=service)
driver.quit()
var options = new SafariOptions();
driver = new SafariDriver(options);
Show full example
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Safari;
using SeleniumDocs.TestSupport;
namespace SeleniumDocs.Browsers
{
[TestClassCustom]
[EnabledOnOs("OSX")]
public class SafariTest
{
private SafariDriver driver;
[TestCleanup]
public void QuitDriver()
{
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new SafariOptions();
driver = new SafariDriver(options);
}
[TestMethod]
[Ignore("Not implemented")]
public void EnableLogs()
{
var service = SafariDriverService.CreateDefaultService();
//service.EnableLogging = true;
driver = new SafariDriver(service);
}
}
}
options = Selenium::WebDriver::Options.safari
@driver = Selenium::WebDriver.for :safari, options: options
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Safari', exclusive: {platform: :macosx} do
describe 'Options' do
it 'basic options' do
options = Selenium::WebDriver::Options.safari
@driver = Selenium::WebDriver.for :safari, options: options
end
end
describe 'Service' do
let(:directory) { "#{Dir.home}/Library/Logs/com.apple.WebDriver/*" }
it 'enables logs' do
original_count = Dir[directory].length
service = Selenium::WebDriver::Service.safari
service.args << '--diagnose'
@driver = Selenium::WebDriver.for :safari, service: service
expect(Dir[directory].length - original_count).to eq 1
end
it 'does not set log output' do
service = Selenium::WebDriver::Service.safari
expect {
service.log = $stdout
}.to raise_error(Selenium::WebDriver::Error::WebDriverError, /Safari Service does not support setting log output/)
end
end
end
RSpec.describe 'Safari Technology Preview', skip: "This test is being skipped as GitHub Actions have no support for Safari Technology Preview" do
it 'sets the technology preview' do
Selenium::WebDriver::Safari.technology_preview!
local_driver = Selenium::WebDriver.for :safari
expect(local_driver.capabilities.browser_name).to eq 'Safari Technology Preview'
end
end
let driver = new Builder()
.forBrowser(Browser.SAFARI)
.setSafariOptions(options)
.build();
Show full example
const safari = require('selenium-webdriver/safari');
const {Browser, Builder} = require("selenium-webdriver");
const options = new safari.Options();
const process = require('node:process');
describe('Should be able to Test Command line arguments', function () {
(process.platform === 'darwin' ? it : it.skip)('headless', async function () {
let driver = new Builder()
.forBrowser(Browser.SAFARI)
.setSafariOptions(options)
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
});
val options = SafariOptions()
val driver = SafariDriver(options)
Mobile (celular)
Se pretende automatizar Safari em iOS, deve olhar para o Projecto Appium.
Service
Service settings common to all browsers are described on the Service page.
Logging
Unlike other browsers, Safari doesn’t let you choose where logs are output, or change levels. The one option
available is to turn logs off or on. If logs are toggled on, they can be found at:~/Library/Logs/com.apple.WebDriver/
.
.withLogging(true)
Show full example
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.safari.SafariDriverService;
import org.openqa.selenium.safari.SafariOptions;
@EnabledOnOs(OS.MAC)
public class SafariTest {
public SafariDriver driver;
@AfterEach
public void quit() {
if (driver != null) {
driver.quit();
}
}
@Test
public void basicOptions() {
SafariOptions options = new SafariOptions();
driver = new SafariDriver(options);
}
@Test
public void enableLogs() {
SafariDriverService service = new SafariDriverService.Builder()
.withLogging(true)
.build();
driver = new SafariDriver(service);
}
public void safariTechnologyPreview() {
SafariOptions options = new SafariOptions();
options.setUseTechnologyPreview(true);
driver = new SafariDriver(options);
}
}
Note: Java also allows setting console output by System Property;
Property key: SafariDriverService.SAFARI_DRIVER_LOGGING
Property value: "true"
or "false"
service = webdriver.SafariService(enable_logging=True)
Show full example
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_basic_options():
options = webdriver.SafariOptions()
driver = webdriver.Safari(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_enable_logging():
service = webdriver.SafariService(enable_logging=True)
driver = webdriver.Safari(service=service)
driver.quit()
@pytest.mark.skip(reason="Not installed on Mac GitHub Actions Runner Image")
def test_technology_preview():
options = webdriver.SafariOptions()
options.use_technology_preview = True
service = webdriver.SafariService(
executable_path='/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver'
)
driver = webdriver.Safari(options=options, service=service)
driver.quit()
service.args << '--diagnose'
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Safari', exclusive: {platform: :macosx} do
describe 'Options' do
it 'basic options' do
options = Selenium::WebDriver::Options.safari
@driver = Selenium::WebDriver.for :safari, options: options
end
end
describe 'Service' do
let(:directory) { "#{Dir.home}/Library/Logs/com.apple.WebDriver/*" }
it 'enables logs' do
original_count = Dir[directory].length
service = Selenium::WebDriver::Service.safari
service.args << '--diagnose'
@driver = Selenium::WebDriver.for :safari, service: service
expect(Dir[directory].length - original_count).to eq 1
end
it 'does not set log output' do
service = Selenium::WebDriver::Service.safari
expect {
service.log = $stdout
}.to raise_error(Selenium::WebDriver::Error::WebDriverError, /Safari Service does not support setting log output/)
end
end
end
RSpec.describe 'Safari Technology Preview', skip: "This test is being skipped as GitHub Actions have no support for Safari Technology Preview" do
it 'sets the technology preview' do
Selenium::WebDriver::Safari.technology_preview!
local_driver = Selenium::WebDriver.for :safari
expect(local_driver.capabilities.browser_name).to eq 'Safari Technology Preview'
end
end
Safari Technology Preview
Apple provides a development version of their browser — Safari Technology Preview To use this version in your code:
options.setUseTechnologyPreview(true);
driver = new SafariDriver(options);
Show full example
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.safari.SafariDriverService;
import org.openqa.selenium.safari.SafariOptions;
@EnabledOnOs(OS.MAC)
public class SafariTest {
public SafariDriver driver;
@AfterEach
public void quit() {
if (driver != null) {
driver.quit();
}
}
@Test
public void basicOptions() {
SafariOptions options = new SafariOptions();
driver = new SafariDriver(options);
}
@Test
public void enableLogs() {
SafariDriverService service = new SafariDriverService.Builder()
.withLogging(true)
.build();
driver = new SafariDriver(service);
}
public void safariTechnologyPreview() {
SafariOptions options = new SafariOptions();
options.setUseTechnologyPreview(true);
driver = new SafariDriver(options);
}
}
options = webdriver.SafariOptions()
options.use_technology_preview = True
service = webdriver.SafariService(
executable_path='/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver'
)
driver = webdriver.Safari(options=options, service=service)
Show full example
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_basic_options():
options = webdriver.SafariOptions()
driver = webdriver.Safari(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_enable_logging():
service = webdriver.SafariService(enable_logging=True)
driver = webdriver.Safari(service=service)
driver.quit()
@pytest.mark.skip(reason="Not installed on Mac GitHub Actions Runner Image")
def test_technology_preview():
options = webdriver.SafariOptions()
options.use_technology_preview = True
service = webdriver.SafariService(
executable_path='/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver'
)
driver = webdriver.Safari(options=options, service=service)
driver.quit()
Selenium::WebDriver::Safari.technology_preview!
local_driver = Selenium::WebDriver.for :safari
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Safari', exclusive: {platform: :macosx} do
describe 'Options' do
it 'basic options' do
options = Selenium::WebDriver::Options.safari
@driver = Selenium::WebDriver.for :safari, options: options
end
end
describe 'Service' do
let(:directory) { "#{Dir.home}/Library/Logs/com.apple.WebDriver/*" }
it 'enables logs' do
original_count = Dir[directory].length
service = Selenium::WebDriver::Service.safari
service.args << '--diagnose'
@driver = Selenium::WebDriver.for :safari, service: service
expect(Dir[directory].length - original_count).to eq 1
end
it 'does not set log output' do
service = Selenium::WebDriver::Service.safari
expect {
service.log = $stdout
}.to raise_error(Selenium::WebDriver::Error::WebDriverError, /Safari Service does not support setting log output/)
end
end
end
RSpec.describe 'Safari Technology Preview', skip: "This test is being skipped as GitHub Actions have no support for Safari Technology Preview" do
it 'sets the technology preview' do
Selenium::WebDriver::Safari.technology_preview!
local_driver = Selenium::WebDriver.for :safari
expect(local_driver.capabilities.browser_name).to eq 'Safari Technology Preview'
end
end