Tune in for the Selenium Community Live scheduled for April 25th, 2025.
Join us!
Edge specific functionality
These are capabilities and features specific to Microsoft Edge browsers.
Microsoft Edge is implemented with Chromium, with the earliest supported version of v79. Similar to Chrome,
the major version number of edgedriver must match the major version of the Edge browser.
Options
Capabilities common to all browsers are described on the Options page.
Starting an Edge session with basic defined options looks like this:
3740
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("--start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((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();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("–start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_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()deftest_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()deftest_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()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_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"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['–log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['–append-log','–readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_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"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":20001024/8,# 2000 kbps"upload_throughput":20001024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_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);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks: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()deftest_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 messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("–no-sandbox")returnoptions
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_edge.py#L9-L10" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
2932
Show full example
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Edge;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassEdgeTest{privateEdgeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newEdgeOptions();driver=newEdgeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newEdgeOptions();options.AddArgument("--start-maximized");driver=newEdgeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newEdgeOptions();options.BinaryLocation=GetEdgeLocation();driver=newEdgeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newEdgeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newEdgeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newEdgeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newEdgeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting Microsoft Edge WebDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=EdgeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newEdgeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetEdgeLocation(){varoptions=newEdgeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.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).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'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')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
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:
4547
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("--start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((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();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("–start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_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()deftest_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()deftest_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()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_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"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['–log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['–append-log','–readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_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"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":20001024/8,# 2000 kbps"upload_throughput":20001024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_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);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks: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()deftest_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 messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("–no-sandbox")returnoptions
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_edge.py#L18" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
3840
Show full example
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Edge;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassEdgeTest{privateEdgeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newEdgeOptions();driver=newEdgeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newEdgeOptions();options.AddArgument("--start-maximized");driver=newEdgeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newEdgeOptions();options.BinaryLocation=GetEdgeLocation();driver=newEdgeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newEdgeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newEdgeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newEdgeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newEdgeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting Microsoft Edge WebDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=EdgeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newEdgeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetEdgeLocation(){varoptions=newEdgeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.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).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'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')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
const{Browser,By,Builder}=require('selenium-webdriver');constedge=require('selenium-webdriver/edge');constoptions=newedge.Options();constassert=require("assert");describe('Should be able to Test Command line arguments',function(){it('headless',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.addArguments('--headless=new')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('exclude switches',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.excludeSwitches('enable-automation')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Keep browser open - set detach to true ',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.detachDriver(true)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// As tests runs in ci, quitting the driver instance to avoid any failures
awaitdriver.quit();});it('Basic edge test',asyncfunction(){constOptions=newedge.Options();letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(Options).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Add Extension',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx'])).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');letinjected=awaitdriver.findElement(By.id('webextensions-selenium-example'));assert.equal(awaitinjected.getText(),`Content injected by webextensions-selenium-example`)awaitdriver.quit();});});
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:
5456
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("--start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((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();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("–start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_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()deftest_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()deftest_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()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_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"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['–log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['–append-log','–readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_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"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":20001024/8,# 2000 kbps"upload_throughput":20001024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_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);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks: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()deftest_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 messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("–no-sandbox")returnoptions
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_edge.py#L29" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
4850
Show full example
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Edge;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassEdgeTest{privateEdgeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newEdgeOptions();driver=newEdgeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newEdgeOptions();options.AddArgument("--start-maximized");driver=newEdgeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newEdgeOptions();options.BinaryLocation=GetEdgeLocation();driver=newEdgeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newEdgeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newEdgeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newEdgeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newEdgeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting Microsoft Edge WebDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=EdgeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newEdgeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetEdgeLocation(){varoptions=newEdgeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.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).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'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')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
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:
6567
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("--start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((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();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("–start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_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()deftest_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()deftest_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()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_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"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['–log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['–append-log','–readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_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"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":20001024/8,# 2000 kbps"upload_throughput":20001024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_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);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks: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()deftest_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 messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("–no-sandbox")returnoptions
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_edge.py#L40" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
6062
Show full example
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Edge;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassEdgeTest{privateEdgeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newEdgeOptions();driver=newEdgeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newEdgeOptions();options.AddArgument("--start-maximized");driver=newEdgeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newEdgeOptions();options.BinaryLocation=GetEdgeLocation();driver=newEdgeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newEdgeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newEdgeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newEdgeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newEdgeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting Microsoft Edge WebDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=EdgeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newEdgeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetEdgeLocation(){varoptions=newEdgeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.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).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'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')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
const{Browser,By,Builder}=require('selenium-webdriver');constedge=require('selenium-webdriver/edge');constoptions=newedge.Options();constassert=require("assert");describe('Should be able to Test Command line arguments',function(){it('headless',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.addArguments('--headless=new')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('exclude switches',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.excludeSwitches('enable-automation')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Keep browser open - set detach to true ',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.detachDriver(true)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// As tests runs in ci, quitting the driver instance to avoid any failures
awaitdriver.quit();});it('Basic edge test',asyncfunction(){constOptions=newedge.Options();letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(Options).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Add Extension',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx'])).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');letinjected=awaitdriver.findElement(By.id('webextensions-selenium-example'));assert.equal(awaitinjected.getText(),`Content injected by webextensions-selenium-example`)awaitdriver.quit();});});
importreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("–start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_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()deftest_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()deftest_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()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_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"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['–log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['–append-log','–readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_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"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":20001024/8,# 2000 kbps"upload_throughput":20001024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_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);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks: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()deftest_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 messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("–no-sandbox")returnoptions
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_edge.py#L51" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
Note: This is already the default behavior in .NET.
4446
Show full example
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.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).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'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')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
const{Browser,By,Builder}=require('selenium-webdriver');constedge=require('selenium-webdriver/edge');constoptions=newedge.Options();constassert=require("assert");describe('Should be able to Test Command line arguments',function(){it('headless',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.addArguments('--headless=new')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('exclude switches',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.excludeSwitches('enable-automation')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Keep browser open - set detach to true ',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.detachDriver(true)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// As tests runs in ci, quitting the driver instance to avoid any failures
awaitdriver.quit();});it('Basic edge test',asyncfunction(){constOptions=newedge.Options();letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(Options).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Add Extension',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx'])).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');letinjected=awaitdriver.findElement(By.id('webextensions-selenium-example'));assert.equal(awaitinjected.getText(),`Content injected by webextensions-selenium-example`)awaitdriver.quit();});});
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:
7880
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("--start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((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();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("–start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_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()deftest_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()deftest_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()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_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"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['–log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['–append-log','–readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_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"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":20001024/8,# 2000 kbps"upload_throughput":20001024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_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);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks: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()deftest_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 messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("–no-sandbox")returnoptions
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_edge.py#L62" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
7577
Show full example
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Edge;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassEdgeTest{privateEdgeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newEdgeOptions();driver=newEdgeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newEdgeOptions();options.AddArgument("--start-maximized");driver=newEdgeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newEdgeOptions();options.BinaryLocation=GetEdgeLocation();driver=newEdgeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newEdgeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newEdgeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newEdgeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newEdgeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting Microsoft Edge WebDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=EdgeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newEdgeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetEdgeLocation(){varoptions=newEdgeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.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).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'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')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
const{Browser,By,Builder}=require('selenium-webdriver');constedge=require('selenium-webdriver/edge');constoptions=newedge.Options();constassert=require("assert");describe('Should be able to Test Command line arguments',function(){it('headless',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.addArguments('--headless=new')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('exclude switches',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.excludeSwitches('enable-automation')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Keep browser open - set detach to true ',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.detachDriver(true)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// As tests runs in ci, quitting the driver instance to avoid any failures
awaitdriver.quit();});it('Basic edge test',asyncfunction(){constOptions=newedge.Options();letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(Options).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Add Extension',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx'])).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');letinjected=awaitdriver.findElement(By.id('webextensions-selenium-example'));assert.equal(awaitinjected.getText(),`Content injected by webextensions-selenium-example`)awaitdriver.quit();});});
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:
importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("–start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\[\d\d-\d\d-\d\d\d\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(20001024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((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();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java#L101" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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
7072
Show full example
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("--start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_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()deftest_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()deftest_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()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_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"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['--log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_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"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_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 setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_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);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks: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()deftest_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 messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("--no-sandbox")returnoptions
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Edge;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassEdgeTest{privateEdgeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newEdgeOptions();driver=newEdgeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newEdgeOptions();options.AddArgument("--start-maximized");driver=newEdgeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newEdgeOptions();options.BinaryLocation=GetEdgeLocation();driver=newEdgeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newEdgeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newEdgeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newEdgeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newEdgeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting Microsoft Edge WebDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=EdgeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newEdgeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetEdgeLocation(){varoptions=newEdgeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.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).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'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')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("–start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\[\d\d-\d\d-\d\d\d\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(20001024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((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();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java#L114" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("--start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_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()deftest_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()deftest_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()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_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"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['--log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_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"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_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 setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_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);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks: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()deftest_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 messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("--no-sandbox")returnoptions
require'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'–start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',dir)options=Selenium::WebDriver::Options.edgeoptions.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).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'–log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/[DEBUG]:/).any?).toeqtrueendit'sets log features'doargs=["–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:serviceexpect(File.readlines(file_name).grep(/[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['–verbose']service.args<<'–disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/[WARNING]: You are using an unsupported command-line switch: –disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'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')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'</span>
'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/ruby/spec/browsers/edge_spec.rb#L76" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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:
importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("–start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\[\d\d-\d\d-\d\d\d\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(20001024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((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();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java#L127-L128" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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
9294
Show full example
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("--start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_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()deftest_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()deftest_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()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_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"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['--log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_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"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_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 setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_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);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks: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()deftest_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 messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("--no-sandbox")returnoptions
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.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).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'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')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
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.
importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("–start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\[\d\d-\d\d-\d\d\d\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(20001024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((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();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java#L143-L144" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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"
103105
Show full example
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("--start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_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()deftest_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()deftest_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()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_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"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['--log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_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"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_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 setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_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);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks: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()deftest_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 messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("--no-sandbox")returnoptions
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.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).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'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')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
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.
importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("–start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\[\d\d-\d\d-\d\d\d\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(20001024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((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();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java#L161-L162" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
Note: Java also allows disabling build checks by System Property: Property key: EdgeDriverService.EDGE_DRIVER_DISABLE_BUILD_CHECK Property value: "true" or "false"
114116
Show full example
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("--start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_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()deftest_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()deftest_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()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_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"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['--log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_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"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_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 setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_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);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks: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()deftest_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 messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("--no-sandbox")returnoptions
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Edge;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassEdgeTest{privateEdgeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newEdgeOptions();driver=newEdgeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newEdgeOptions();options.AddArgument("--start-maximized");driver=newEdgeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newEdgeOptions();options.BinaryLocation=GetEdgeLocation();driver=newEdgeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newEdgeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newEdgeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newEdgeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newEdgeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting Microsoft Edge WebDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=EdgeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newEdgeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetEdgeLocation(){varoptions=newEdgeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.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).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'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')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
Microsoft Edge can be driven in “Internet Explorer Compatibility Mode”, which uses
the Internet Explorer Driver classes in conjunction with Microsoft Edge.
Read the Internet Explorer page for more details.
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
224231
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("--start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((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();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("--start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_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()deftest_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()deftest_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()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_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"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['--log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_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"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_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 setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_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);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks: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()deftest_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 messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("--no-sandbox")returnoptions
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.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).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'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')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("--start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((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();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("--start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_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()deftest_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()deftest_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()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_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"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['--log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_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"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_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 setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_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);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks: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()deftest_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 messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("--no-sandbox")returnoptions
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.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).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'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')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("--start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((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();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("--start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_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()deftest_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()deftest_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()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_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"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['--log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_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"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_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 setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_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);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks: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()deftest_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 messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("--no-sandbox")returnoptions
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.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).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'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')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("--start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((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();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("--start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_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()deftest_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()deftest_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()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_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"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['--log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_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"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_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 setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_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);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks: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()deftest_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 messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("--no-sandbox")returnoptions
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.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).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'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')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend