packagedev.selenium.interactions;importdev.selenium.BaseChromeTest;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.Cookie;importjava.util.Set;publicclassInteractionsTestextendsBaseChromeTest{@TestpublicvoidgetTitle(){try{driver.get("https://www.selenium.dev/");// get titleStringtitle=driver.getTitle();Assertions.assertEquals(title,"Selenium");}finally{driver.quit();}}@TestpublicvoidgetCurrentUrl(){try{driver.get("https://www.selenium.dev/");// get current urlStringurl=driver.getCurrentUrl();Assertions.assertEquals(url,"https://www.selenium.dev/");}finally{driver.quit();}}}
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocumentation.SeleniumInteractions{ [TestClass]publicclassInteractionsTest{ [TestMethod]publicvoidTestInteractions(){WebDriverdriver=newChromeDriver();driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromMilliseconds(500);// Navigate to Urldriver.Url="https://www.selenium.dev/";//GetTitleStringtitle=driver.Title;Assert.AreEqual(title,"Selenium");//GetCurrentURLStringurl=driver.Url;Assert.AreEqual(url,"https://www.selenium.dev/");//quitting driverdriver.Quit();//close all windows}}}
require'spec_helper'RSpec.describe'Browser'dolet(:driver){start_session}it'gets the current title'dodriver.navigate.to'https://www.selenium.dev/'current_title=driver.titleexpect(current_title).toeq'Selenium'endit'gets the current url'dodriver.navigate.to'https://www.selenium.dev/'current_url=driver.current_urlexpect(current_url).toeq'https://www.selenium.dev/'endend
const{Builder}=require('selenium-webdriver');constassert=require("node:assert");describe('Interactions',function(){letdriver;before(asyncfunction(){driver=newBuilder().forBrowser('chrome').build();});after(async()=>awaitdriver.quit());it('Should be able to get title and current url',asyncfunction(){consturl='https://www.selenium.dev/';awaitdriver.get(url);//Get Current title
lettitle=awaitdriver.getTitle();assert.equal(title,"Selenium");//Get Current url
letcurrentUrl=awaitdriver.getCurrentUrl();assert.equal(currentUrl,url);});});
packagedev.selenium.interactions;importdev.selenium.BaseChromeTest;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.Cookie;importjava.util.Set;publicclassInteractionsTestextendsBaseChromeTest{@TestpublicvoidgetTitle(){try{driver.get("https://www.selenium.dev/");// get titleStringtitle=driver.getTitle();Assertions.assertEquals(title,"Selenium");}finally{driver.quit();}}@TestpublicvoidgetCurrentUrl(){try{driver.get("https://www.selenium.dev/");// get current urlStringurl=driver.getCurrentUrl();Assertions.assertEquals(url,"https://www.selenium.dev/");}finally{driver.quit();}}}
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocumentation.SeleniumInteractions{ [TestClass]publicclassInteractionsTest{ [TestMethod]publicvoidTestInteractions(){WebDriverdriver=newChromeDriver();driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromMilliseconds(500);// Navigate to Urldriver.Url="https://www.selenium.dev/";//GetTitleStringtitle=driver.Title;Assert.AreEqual(title,"Selenium");//GetCurrentURLStringurl=driver.Url;Assert.AreEqual(url,"https://www.selenium.dev/");//quitting driverdriver.Quit();//close all windows}}}
require'spec_helper'RSpec.describe'Browser'dolet(:driver){start_session}it'gets the current title'dodriver.navigate.to'https://www.selenium.dev/'current_title=driver.titleexpect(current_title).toeq'Selenium'endit'gets the current url'dodriver.navigate.to'https://www.selenium.dev/'current_url=driver.current_urlexpect(current_url).toeq'https://www.selenium.dev/'endend
const{Builder}=require('selenium-webdriver');constassert=require("node:assert");describe('Interactions',function(){letdriver;before(asyncfunction(){driver=newBuilder().forBrowser('chrome').build();});after(async()=>awaitdriver.quit());it('Should be able to get title and current url',asyncfunction(){consturl='https://www.selenium.dev/';awaitdriver.get(url);//Get Current title
lettitle=awaitdriver.getTitle();assert.equal(title,"Selenium");//Get Current url
letcurrentUrl=awaitdriver.getCurrentUrl();assert.equal(currentUrl,url);});});
fromseleniumimportwebdriverdriver=webdriver.Chrome()driver.get("https://www.selenium.dev")driver.get("https://www.selenium.dev/selenium/web/index.html")title=driver.titleasserttitle=="Index of Available Pages"driver.back()title=driver.titleasserttitle=="Selenium"driver.forward()title=driver.titleasserttitle=="Index of Available Pages"driver.refresh()title=driver.titleasserttitle=="Index of Available Pages"driver.quit()
usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocumentation.SeleniumInteractions{ [TestClass]publicclassNavigationTest{ [TestMethod]publicvoidTestNavigationCommands(){IWebDriverdriver=newChromeDriver();driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromMilliseconds(500);//Convenientdriver.Url="https://selenium.dev";//Longerdriver.Navigate().GoToUrl("https://selenium.dev");vartitle=driver.Title;Assert.AreEqual("Selenium",title);//Backdriver.Navigate().Back();title=driver.Title;Assert.AreEqual("Selenium",title);//Forwarddriver.Navigate().Forward();title=driver.Title;Assert.AreEqual("Selenium",title);//Refreshdriver.Navigate().Refresh();title=driver.Title;Assert.AreEqual("Selenium",title);//Quit the browserdriver.Quit();}}}
require'spec_helper'RSpec.describe'Browser'dolet(:driver){start_session}it'navigates to a page'dodriver.navigate.to'https://www.selenium.dev/'driver.get'https://www.selenium.dev/'expect(driver.current_url).toeq'https://www.selenium.dev/'endit'navigates back'dodriver.navigate.to'https://www.selenium.dev/'driver.navigate.to'https://www.selenium.dev/selenium/web/inputs.html'driver.navigate.backexpect(driver.current_url).toeq'https://www.selenium.dev/'endit'navigates forward'dodriver.navigate.to'https://www.selenium.dev/'driver.navigate.to'https://www.selenium.dev/selenium/web/inputs.html'driver.navigate.backdriver.navigate.forwardexpect(driver.current_url).toeq'https://www.selenium.dev/selenium/web/inputs.html'endit'refreshes the page'dodriver.navigate.to'https://www.selenium.dev/'driver.navigate.refreshexpect(driver.current_url).toeq'https://www.selenium.dev/'endend
//Convenient
awaitdriver.get('https://www.selenium.dev');//Longer way
awaitdriver.navigate().to("https://www.selenium.dev/selenium/web/index.html");
Show full example
const{Builder}=require('selenium-webdriver');constassert=require("node:assert");describe('Interactions - Navigation',function(){letdriver;before(asyncfunction(){driver=newBuilder().forBrowser('chrome').build();});after(async()=>awaitdriver.quit());it('Browser navigation test',asyncfunction(){//Convenient
awaitdriver.get('https://www.selenium.dev');//Longer way
awaitdriver.navigate().to("https://www.selenium.dev/selenium/web/index.html");lettitle=awaitdriver.getTitle();assert.equal(title,"Index of Available Pages");//Back
awaitdriver.navigate().back();title=awaitdriver.getTitle();assert.equal(title,"Selenium");//Forward
awaitdriver.navigate().forward();title=awaitdriver.getTitle();assert.equal(title,"Index of Available Pages");//Refresh
awaitdriver.navigate().refresh();title=awaitdriver.getTitle();assert.equal(title,"Index of Available Pages");});});
fromseleniumimportwebdriverdriver=webdriver.Chrome()driver.get("https://www.selenium.dev")driver.get("https://www.selenium.dev/selenium/web/index.html")title=driver.titleasserttitle=="Index of Available Pages"driver.back()title=driver.titleasserttitle=="Selenium"driver.forward()title=driver.titleasserttitle=="Index of Available Pages"driver.refresh()title=driver.titleasserttitle=="Index of Available Pages"driver.quit()
usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocumentation.SeleniumInteractions{ [TestClass]publicclassNavigationTest{ [TestMethod]publicvoidTestNavigationCommands(){IWebDriverdriver=newChromeDriver();driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromMilliseconds(500);//Convenientdriver.Url="https://selenium.dev";//Longerdriver.Navigate().GoToUrl("https://selenium.dev");vartitle=driver.Title;Assert.AreEqual("Selenium",title);//Backdriver.Navigate().Back();title=driver.Title;Assert.AreEqual("Selenium",title);//Forwarddriver.Navigate().Forward();title=driver.Title;Assert.AreEqual("Selenium",title);//Refreshdriver.Navigate().Refresh();title=driver.Title;Assert.AreEqual("Selenium",title);//Quit the browserdriver.Quit();}}}
require'spec_helper'RSpec.describe'Browser'dolet(:driver){start_session}it'navigates to a page'dodriver.navigate.to'https://www.selenium.dev/'driver.get'https://www.selenium.dev/'expect(driver.current_url).toeq'https://www.selenium.dev/'endit'navigates back'dodriver.navigate.to'https://www.selenium.dev/'driver.navigate.to'https://www.selenium.dev/selenium/web/inputs.html'driver.navigate.backexpect(driver.current_url).toeq'https://www.selenium.dev/'endit'navigates forward'dodriver.navigate.to'https://www.selenium.dev/'driver.navigate.to'https://www.selenium.dev/selenium/web/inputs.html'driver.navigate.backdriver.navigate.forwardexpect(driver.current_url).toeq'https://www.selenium.dev/selenium/web/inputs.html'endit'refreshes the page'dodriver.navigate.to'https://www.selenium.dev/'driver.navigate.refreshexpect(driver.current_url).toeq'https://www.selenium.dev/'endend
const{Builder}=require('selenium-webdriver');constassert=require("node:assert");describe('Interactions - Navigation',function(){letdriver;before(asyncfunction(){driver=newBuilder().forBrowser('chrome').build();});after(async()=>awaitdriver.quit());it('Browser navigation test',asyncfunction(){//Convenient
awaitdriver.get('https://www.selenium.dev');//Longer way
awaitdriver.navigate().to("https://www.selenium.dev/selenium/web/index.html");lettitle=awaitdriver.getTitle();assert.equal(title,"Index of Available Pages");//Back
awaitdriver.navigate().back();title=awaitdriver.getTitle();assert.equal(title,"Selenium");//Forward
awaitdriver.navigate().forward();title=awaitdriver.getTitle();assert.equal(title,"Index of Available Pages");//Refresh
awaitdriver.navigate().refresh();title=awaitdriver.getTitle();assert.equal(title,"Index of Available Pages");});});
fromseleniumimportwebdriverdriver=webdriver.Chrome()driver.get("https://www.selenium.dev")driver.get("https://www.selenium.dev/selenium/web/index.html")title=driver.titleasserttitle=="Index of Available Pages"driver.back()title=driver.titleasserttitle=="Selenium"driver.forward()title=driver.titleasserttitle=="Index of Available Pages"driver.refresh()title=driver.titleasserttitle=="Index of Available Pages"driver.quit()
usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocumentation.SeleniumInteractions{ [TestClass]publicclassNavigationTest{ [TestMethod]publicvoidTestNavigationCommands(){IWebDriverdriver=newChromeDriver();driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromMilliseconds(500);//Convenientdriver.Url="https://selenium.dev";//Longerdriver.Navigate().GoToUrl("https://selenium.dev");vartitle=driver.Title;Assert.AreEqual("Selenium",title);//Backdriver.Navigate().Back();title=driver.Title;Assert.AreEqual("Selenium",title);//Forwarddriver.Navigate().Forward();title=driver.Title;Assert.AreEqual("Selenium",title);//Refreshdriver.Navigate().Refresh();title=driver.Title;Assert.AreEqual("Selenium",title);//Quit the browserdriver.Quit();}}}
require'spec_helper'RSpec.describe'Browser'dolet(:driver){start_session}it'navigates to a page'dodriver.navigate.to'https://www.selenium.dev/'driver.get'https://www.selenium.dev/'expect(driver.current_url).toeq'https://www.selenium.dev/'endit'navigates back'dodriver.navigate.to'https://www.selenium.dev/'driver.navigate.to'https://www.selenium.dev/selenium/web/inputs.html'driver.navigate.backexpect(driver.current_url).toeq'https://www.selenium.dev/'endit'navigates forward'dodriver.navigate.to'https://www.selenium.dev/'driver.navigate.to'https://www.selenium.dev/selenium/web/inputs.html'driver.navigate.backdriver.navigate.forwardexpect(driver.current_url).toeq'https://www.selenium.dev/selenium/web/inputs.html'endit'refreshes the page'dodriver.navigate.to'https://www.selenium.dev/'driver.navigate.refreshexpect(driver.current_url).toeq'https://www.selenium.dev/'endend
const{Builder}=require('selenium-webdriver');constassert=require("node:assert");describe('Interactions - Navigation',function(){letdriver;before(asyncfunction(){driver=newBuilder().forBrowser('chrome').build();});after(async()=>awaitdriver.quit());it('Browser navigation test',asyncfunction(){//Convenient
awaitdriver.get('https://www.selenium.dev');//Longer way
awaitdriver.navigate().to("https://www.selenium.dev/selenium/web/index.html");lettitle=awaitdriver.getTitle();assert.equal(title,"Index of Available Pages");//Back
awaitdriver.navigate().back();title=awaitdriver.getTitle();assert.equal(title,"Selenium");//Forward
awaitdriver.navigate().forward();title=awaitdriver.getTitle();assert.equal(title,"Index of Available Pages");//Refresh
awaitdriver.navigate().refresh();title=awaitdriver.getTitle();assert.equal(title,"Index of Available Pages");});});
fromseleniumimportwebdriverdriver=webdriver.Chrome()driver.get("https://www.selenium.dev")driver.get("https://www.selenium.dev/selenium/web/index.html")title=driver.titleasserttitle=="Index of Available Pages"driver.back()title=driver.titleasserttitle=="Selenium"driver.forward()title=driver.titleasserttitle=="Index of Available Pages"driver.refresh()title=driver.titleasserttitle=="Index of Available Pages"driver.quit()
usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocumentation.SeleniumInteractions{ [TestClass]publicclassNavigationTest{ [TestMethod]publicvoidTestNavigationCommands(){IWebDriverdriver=newChromeDriver();driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromMilliseconds(500);//Convenientdriver.Url="https://selenium.dev";//Longerdriver.Navigate().GoToUrl("https://selenium.dev");vartitle=driver.Title;Assert.AreEqual("Selenium",title);//Backdriver.Navigate().Back();title=driver.Title;Assert.AreEqual("Selenium",title);//Forwarddriver.Navigate().Forward();title=driver.Title;Assert.AreEqual("Selenium",title);//Refreshdriver.Navigate().Refresh();title=driver.Title;Assert.AreEqual("Selenium",title);//Quit the browserdriver.Quit();}}}
require'spec_helper'RSpec.describe'Browser'dolet(:driver){start_session}it'navigates to a page'dodriver.navigate.to'https://www.selenium.dev/'driver.get'https://www.selenium.dev/'expect(driver.current_url).toeq'https://www.selenium.dev/'endit'navigates back'dodriver.navigate.to'https://www.selenium.dev/'driver.navigate.to'https://www.selenium.dev/selenium/web/inputs.html'driver.navigate.backexpect(driver.current_url).toeq'https://www.selenium.dev/'endit'navigates forward'dodriver.navigate.to'https://www.selenium.dev/'driver.navigate.to'https://www.selenium.dev/selenium/web/inputs.html'driver.navigate.backdriver.navigate.forwardexpect(driver.current_url).toeq'https://www.selenium.dev/selenium/web/inputs.html'endit'refreshes the page'dodriver.navigate.to'https://www.selenium.dev/'driver.navigate.refreshexpect(driver.current_url).toeq'https://www.selenium.dev/'endend
const{Builder}=require('selenium-webdriver');constassert=require("node:assert");describe('Interactions - Navigation',function(){letdriver;before(asyncfunction(){driver=newBuilder().forBrowser('chrome').build();});after(async()=>awaitdriver.quit());it('Browser navigation test',asyncfunction(){//Convenient
awaitdriver.get('https://www.selenium.dev');//Longer way
awaitdriver.navigate().to("https://www.selenium.dev/selenium/web/index.html");lettitle=awaitdriver.getTitle();assert.equal(title,"Index of Available Pages");//Back
awaitdriver.navigate().back();title=awaitdriver.getTitle();assert.equal(title,"Selenium");//Forward
awaitdriver.navigate().forward();title=awaitdriver.getTitle();assert.equal(title,"Index of Available Pages");//Refresh
awaitdriver.navigate().refresh();title=awaitdriver.getTitle();assert.equal(title,"Index of Available Pages");});});
wait.until(ExpectedConditions.alertIsPresent());Alertalert=driver.switchTo().alert();//Store the alert text in a variable and verify itStringtext=alert.getText();assertEquals(text,"Sample Alert");//PresstheOKbutton
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.importdev.selenium.BaseTest;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.support.ui.ExpectedConditions;importorg.openqa.selenium.support.ui.WebDriverWait;importjava.time.Duration;import staticorg.junit.jupiter.api.Assertions.assertEquals;publicclassAlertsTestextendsBaseTest{@TestpublicvoidtestForAlerts()throwsException{ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.addArguments("disable-search-engine-choice-screen");WebDriverdriver=newChromeDriver(chromeOptions);driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));driver.manage().window().maximize();//Navigate to Urldriver.get("https://www.selenium.dev/documentation/webdriver/interactions/alerts/");//Simple Alert//Click the link to activate the alertJavascriptExecutorjs=(JavascriptExecutor)driver;//execute js for alertjs.executeScript("alert('Sample Alert');");WebDriverWaitwait=newWebDriverWait(driver,Duration.ofSeconds(30));//Wait for the alert to be displayed and store it in a variablewait.until(ExpectedConditions.alertIsPresent());Alertalert=driver.switchTo().alert();//Store the alert text in a variable and verify itStringtext=alert.getText();assertEquals(text,"Sample Alert");//Press the OK buttonalert.accept();//Confirm//execute js for confirmjs.executeScript("confirm('Are you sure?');");//Wait for the alert to be displayedwait=newWebDriverWait(driver,Duration.ofSeconds(30));wait.until(ExpectedConditions.alertIsPresent());alert=driver.switchTo().alert();//Store the alert text in a variable and verify ittext=alert.getText();assertEquals(text,"Are you sure?");//Press the Cancel buttonalert.dismiss();//Prompt//execute js for promptjs.executeScript("prompt('What is your name?');");//Wait for the alert to be displayed and store it in a variablewait=newWebDriverWait(driver,Duration.ofSeconds(30));wait.until(ExpectedConditions.alertIsPresent());alert=driver.switchTo().alert();//Store the alert text in a variable and verify ittext=alert.getText();assertEquals(text,"What is your name?");//Type your messagealert.sendKeys("Selenium");//Press the OK buttonalert.accept();//quit the browserdriver.quit();}}
element=driver.find_element(By.LINK_TEXT,"See an example alert")element.click()wait=WebDriverWait(driver,timeout=2)alert=wait.until(lambdad:d.switch_to.alert)text=alert.textalert.accept()
Show full example
fromseleniumimportwebdriverfromselenium.webdriver.common.byimportByfromselenium.webdriver.support.uiimportWebDriverWaitglobalurlurl="https://www.selenium.dev/documentation/webdriver/interactions/alerts/"deftest_alert_popup():driver=webdriver.Chrome()driver.get(url)element=driver.find_element(By.LINK_TEXT,"See an example alert")element.click()wait=WebDriverWait(driver,timeout=2)alert=wait.until(lambdad:d.switch_to.alert)text=alert.textalert.accept()asserttext=="Sample alert"driver.quit()deftest_confirm_popup():driver=webdriver.Chrome()driver.get(url)element=driver.find_element(By.LINK_TEXT,"See a sample confirm")driver.execute_script("arguments[0].click();",element)wait=WebDriverWait(driver,timeout=2)alert=wait.until(lambdad:d.switch_to.alert)text=alert.textalert.dismiss()asserttext=="Are you sure?"driver.quit()deftest_prompt_popup():driver=webdriver.Chrome()driver.get(url)element=driver.find_element(By.LINK_TEXT,"See a sample prompt")driver.execute_script("arguments[0].click();",element)wait=WebDriverWait(driver,timeout=2)alert=wait.until(lambdad:d.switch_to.alert)alert.send_keys("Selenium")text=alert.textalert.accept()asserttext=="What is your tool of choice?"driver.quit()
//Click the link to activate the alertdriver.FindElement(By.LinkText("See an example alert")).Click();//Wait for the alert to be displayed and store it in a variableIAlertalert=wait.Until(ExpectedConditions.AlertIsPresent());//Store the alert text in a variablestringtext=alert.Text;//Press the OK buttonalert.Accept();
# Store the alert reference in a variablealert=driver.switch_to.alert# Get the text of the alertalert.text# Press on Cancel buttonalert.dismiss
Show full example
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Alerts'dolet(:driver){start_session}beforedodriver.navigate.to'https://selenium.dev'endit'interacts with an alert'dodriver.execute_script'alert("Hello, World!")'# Store the alert reference in a variablealert=driver.switch_to.alert# Get the text of the alertalert.text# Press on Cancel buttonalert.dismissendit'interacts with a confirm'dodriver.execute_script'confirm("Are you sure?")'# Store the alert reference in a variablealert=driver.switch_to.alert# Get the text of the alertalert.text# Press on Cancel buttonalert.dismissendit'interacts with a prompt'dodriver.execute_script'prompt("What is your name?")'# Store the alert reference in a variablealert=driver.switch_to.alert# Type a messagealert.send_keys('selenium')# Press on Ok buttonalert.acceptendend
const{By,Builder,until}=require('selenium-webdriver');constassert=require("node:assert");describe('Interactions - Alerts',function(){letdriver;before(asyncfunction(){driver=awaitnewBuilder().forBrowser('chrome').build();});after(async()=>awaitdriver.quit());it('Should be able to getText from alert and accept',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');awaitdriver.findElement(By.id("alert")).click();awaitdriver.wait(until.alertIsPresent());letalert=awaitdriver.switchTo().alert();letalertText=awaitalert.getText();awaitalert.accept();// Verify
assert.equal(alertText,"cheese");});it('Should be able to getText from alert and dismiss',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');awaitdriver.findElement(By.id("confirm")).click();awaitdriver.wait(until.alertIsPresent());letalert=awaitdriver.switchTo().alert();letalertText=awaitalert.getText();awaitalert.dismiss();// Verify
assert.equal(alertText,"Are you sure?");});it('Should be able to enter text in alert prompt',asyncfunction(){lettext='Selenium';awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');awaitdriver.findElement(By.id("prompt")).click();awaitdriver.wait(until.alertIsPresent());letalert=awaitdriver.switchTo().alert();//Type your message
awaitalert.sendKeys(text);awaitalert.accept();letenteredText=awaitdriver.findElement(By.id('text'));assert.equal(awaitenteredText.getText(),text);});});
//Click the link to activate the alert
driver.findElement(By.linkText("See an example alert")).click()//Wait for the alert to be displayed and store it in a variable
valalert=wait.until(ExpectedConditions.alertIsPresent())//Store the alert text in a variable
valtext=alert.getText()//Press the OK button
alert.accept()
alert=driver.switchTo().alert();//Store the alert text in a variable and verify ittext=alert.getText();assertEquals(text,"Are you sure?");//PresstheCancelbutton
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.importdev.selenium.BaseTest;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.support.ui.ExpectedConditions;importorg.openqa.selenium.support.ui.WebDriverWait;importjava.time.Duration;import staticorg.junit.jupiter.api.Assertions.assertEquals;publicclassAlertsTestextendsBaseTest{@TestpublicvoidtestForAlerts()throwsException{ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.addArguments("disable-search-engine-choice-screen");WebDriverdriver=newChromeDriver(chromeOptions);driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));driver.manage().window().maximize();//Navigate to Urldriver.get("https://www.selenium.dev/documentation/webdriver/interactions/alerts/");//Simple Alert//Click the link to activate the alertJavascriptExecutorjs=(JavascriptExecutor)driver;//execute js for alertjs.executeScript("alert('Sample Alert');");WebDriverWaitwait=newWebDriverWait(driver,Duration.ofSeconds(30));//Wait for the alert to be displayed and store it in a variablewait.until(ExpectedConditions.alertIsPresent());Alertalert=driver.switchTo().alert();//Store the alert text in a variable and verify itStringtext=alert.getText();assertEquals(text,"Sample Alert");//Press the OK buttonalert.accept();//Confirm//execute js for confirmjs.executeScript("confirm('Are you sure?');");//Wait for the alert to be displayedwait=newWebDriverWait(driver,Duration.ofSeconds(30));wait.until(ExpectedConditions.alertIsPresent());alert=driver.switchTo().alert();//Store the alert text in a variable and verify ittext=alert.getText();assertEquals(text,"Are you sure?");//Press the Cancel buttonalert.dismiss();//Prompt//execute js for promptjs.executeScript("prompt('What is your name?');");//Wait for the alert to be displayed and store it in a variablewait=newWebDriverWait(driver,Duration.ofSeconds(30));wait.until(ExpectedConditions.alertIsPresent());alert=driver.switchTo().alert();//Store the alert text in a variable and verify ittext=alert.getText();assertEquals(text,"What is your name?");//Type your messagealert.sendKeys("Selenium");//Press the OK buttonalert.accept();//quit the browserdriver.quit();}}
element=driver.find_element(By.LINK_TEXT,"See a sample confirm")driver.execute_script("arguments[0].click();",element)wait=WebDriverWait(driver,timeout=2)alert=wait.until(lambdad:d.switch_to.alert)text=alert.textalert.dismiss()
Show full example
fromseleniumimportwebdriverfromselenium.webdriver.common.byimportByfromselenium.webdriver.support.uiimportWebDriverWaitglobalurlurl="https://www.selenium.dev/documentation/webdriver/interactions/alerts/"deftest_alert_popup():driver=webdriver.Chrome()driver.get(url)element=driver.find_element(By.LINK_TEXT,"See an example alert")element.click()wait=WebDriverWait(driver,timeout=2)alert=wait.until(lambdad:d.switch_to.alert)text=alert.textalert.accept()asserttext=="Sample alert"driver.quit()deftest_confirm_popup():driver=webdriver.Chrome()driver.get(url)element=driver.find_element(By.LINK_TEXT,"See a sample confirm")driver.execute_script("arguments[0].click();",element)wait=WebDriverWait(driver,timeout=2)alert=wait.until(lambdad:d.switch_to.alert)text=alert.textalert.dismiss()asserttext=="Are you sure?"driver.quit()deftest_prompt_popup():driver=webdriver.Chrome()driver.get(url)element=driver.find_element(By.LINK_TEXT,"See a sample prompt")driver.execute_script("arguments[0].click();",element)wait=WebDriverWait(driver,timeout=2)alert=wait.until(lambdad:d.switch_to.alert)alert.send_keys("Selenium")text=alert.textalert.accept()asserttext=="What is your tool of choice?"driver.quit()
//Click the link to activate the alertdriver.FindElement(By.LinkText("See a sample confirm")).Click();//Wait for the alert to be displayedwait.Until(ExpectedConditions.AlertIsPresent());//Store the alert in a variableIAlertalert=driver.SwitchTo().Alert();//Store the alert in a variable for reusestringtext=alert.Text;//Press the Cancel buttonalert.Dismiss();
# Store the alert reference in a variablealert=driver.switch_to.alert# Get the text of the alertalert.text# Press on Cancel buttonalert.dismiss
Show full example
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Alerts'dolet(:driver){start_session}beforedodriver.navigate.to'https://selenium.dev'endit'interacts with an alert'dodriver.execute_script'alert("Hello, World!")'# Store the alert reference in a variablealert=driver.switch_to.alert# Get the text of the alertalert.text# Press on Cancel buttonalert.dismissendit'interacts with a confirm'dodriver.execute_script'confirm("Are you sure?")'# Store the alert reference in a variablealert=driver.switch_to.alert# Get the text of the alertalert.text# Press on Cancel buttonalert.dismissendit'interacts with a prompt'dodriver.execute_script'prompt("What is your name?")'# Store the alert reference in a variablealert=driver.switch_to.alert# Type a messagealert.send_keys('selenium')# Press on Ok buttonalert.acceptendend
const{By,Builder,until}=require('selenium-webdriver');constassert=require("node:assert");describe('Interactions - Alerts',function(){letdriver;before(asyncfunction(){driver=awaitnewBuilder().forBrowser('chrome').build();});after(async()=>awaitdriver.quit());it('Should be able to getText from alert and accept',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');awaitdriver.findElement(By.id("alert")).click();awaitdriver.wait(until.alertIsPresent());letalert=awaitdriver.switchTo().alert();letalertText=awaitalert.getText();awaitalert.accept();// Verify
assert.equal(alertText,"cheese");});it('Should be able to getText from alert and dismiss',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');awaitdriver.findElement(By.id("confirm")).click();awaitdriver.wait(until.alertIsPresent());letalert=awaitdriver.switchTo().alert();letalertText=awaitalert.getText();awaitalert.dismiss();// Verify
assert.equal(alertText,"Are you sure?");});it('Should be able to enter text in alert prompt',asyncfunction(){lettext='Selenium';awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');awaitdriver.findElement(By.id("prompt")).click();awaitdriver.wait(until.alertIsPresent());letalert=awaitdriver.switchTo().alert();//Type your message
awaitalert.sendKeys(text);awaitalert.accept();letenteredText=awaitdriver.findElement(By.id('text'));assert.equal(awaitenteredText.getText(),text);});});
//Click the link to activate the alert
driver.findElement(By.linkText("See a sample confirm")).click()//Wait for the alert to be displayed
wait.until(ExpectedConditions.alertIsPresent())//Store the alert in a variable
valalert=driver.switchTo().alert()//Store the alert in a variable for reuse
valtext=alert.text//Press the Cancel button
alert.dismiss()
wait.until(ExpectedConditions.alertIsPresent());alert=driver.switchTo().alert();//Store the alert text in a variable and verify ittext=alert.getText();assertEquals(text,"What is your name?");//Type your messagealert.sendKeys("Selenium");//PresstheOKbutton
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.importdev.selenium.BaseTest;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.support.ui.ExpectedConditions;importorg.openqa.selenium.support.ui.WebDriverWait;importjava.time.Duration;import staticorg.junit.jupiter.api.Assertions.assertEquals;publicclassAlertsTestextendsBaseTest{@TestpublicvoidtestForAlerts()throwsException{ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.addArguments("disable-search-engine-choice-screen");WebDriverdriver=newChromeDriver(chromeOptions);driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));driver.manage().window().maximize();//Navigate to Urldriver.get("https://www.selenium.dev/documentation/webdriver/interactions/alerts/");//Simple Alert//Click the link to activate the alertJavascriptExecutorjs=(JavascriptExecutor)driver;//execute js for alertjs.executeScript("alert('Sample Alert');");WebDriverWaitwait=newWebDriverWait(driver,Duration.ofSeconds(30));//Wait for the alert to be displayed and store it in a variablewait.until(ExpectedConditions.alertIsPresent());Alertalert=driver.switchTo().alert();//Store the alert text in a variable and verify itStringtext=alert.getText();assertEquals(text,"Sample Alert");//Press the OK buttonalert.accept();//Confirm//execute js for confirmjs.executeScript("confirm('Are you sure?');");//Wait for the alert to be displayedwait=newWebDriverWait(driver,Duration.ofSeconds(30));wait.until(ExpectedConditions.alertIsPresent());alert=driver.switchTo().alert();//Store the alert text in a variable and verify ittext=alert.getText();assertEquals(text,"Are you sure?");//Press the Cancel buttonalert.dismiss();//Prompt//execute js for promptjs.executeScript("prompt('What is your name?');");//Wait for the alert to be displayed and store it in a variablewait=newWebDriverWait(driver,Duration.ofSeconds(30));wait.until(ExpectedConditions.alertIsPresent());alert=driver.switchTo().alert();//Store the alert text in a variable and verify ittext=alert.getText();assertEquals(text,"What is your name?");//Type your messagealert.sendKeys("Selenium");//Press the OK buttonalert.accept();//quit the browserdriver.quit();}}
element=driver.find_element(By.LINK_TEXT,"See a sample prompt")driver.execute_script("arguments[0].click();",element)wait=WebDriverWait(driver,timeout=2)alert=wait.until(lambdad:d.switch_to.alert)alert.send_keys("Selenium")text=alert.textalert.accept()
Show full example
fromseleniumimportwebdriverfromselenium.webdriver.common.byimportByfromselenium.webdriver.support.uiimportWebDriverWaitglobalurlurl="https://www.selenium.dev/documentation/webdriver/interactions/alerts/"deftest_alert_popup():driver=webdriver.Chrome()driver.get(url)element=driver.find_element(By.LINK_TEXT,"See an example alert")element.click()wait=WebDriverWait(driver,timeout=2)alert=wait.until(lambdad:d.switch_to.alert)text=alert.textalert.accept()asserttext=="Sample alert"driver.quit()deftest_confirm_popup():driver=webdriver.Chrome()driver.get(url)element=driver.find_element(By.LINK_TEXT,"See a sample confirm")driver.execute_script("arguments[0].click();",element)wait=WebDriverWait(driver,timeout=2)alert=wait.until(lambdad:d.switch_to.alert)text=alert.textalert.dismiss()asserttext=="Are you sure?"driver.quit()deftest_prompt_popup():driver=webdriver.Chrome()driver.get(url)element=driver.find_element(By.LINK_TEXT,"See a sample prompt")driver.execute_script("arguments[0].click();",element)wait=WebDriverWait(driver,timeout=2)alert=wait.until(lambdad:d.switch_to.alert)alert.send_keys("Selenium")text=alert.textalert.accept()asserttext=="What is your tool of choice?"driver.quit()
//Click the link to activate the alertdriver.FindElement(By.LinkText("See a sample prompt")).Click();//Wait for the alert to be displayed and store it in a variableIAlertalert=wait.Until(ExpectedConditions.AlertIsPresent());//Type your messagealert.SendKeys("Selenium");//Press the OK buttonalert.Accept();
# Store the alert reference in a variablealert=driver.switch_to.alert# Type a messagealert.send_keys('selenium')# Press on Ok buttonalert.accept
Show full example
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Alerts'dolet(:driver){start_session}beforedodriver.navigate.to'https://selenium.dev'endit'interacts with an alert'dodriver.execute_script'alert("Hello, World!")'# Store the alert reference in a variablealert=driver.switch_to.alert# Get the text of the alertalert.text# Press on Cancel buttonalert.dismissendit'interacts with a confirm'dodriver.execute_script'confirm("Are you sure?")'# Store the alert reference in a variablealert=driver.switch_to.alert# Get the text of the alertalert.text# Press on Cancel buttonalert.dismissendit'interacts with a prompt'dodriver.execute_script'prompt("What is your name?")'# Store the alert reference in a variablealert=driver.switch_to.alert# Type a messagealert.send_keys('selenium')# Press on Ok buttonalert.acceptendend
letalert=awaitdriver.switchTo().alert();//Type your message
awaitalert.sendKeys(text);awaitalert.accept();
Show full example
const{By,Builder,until}=require('selenium-webdriver');constassert=require("node:assert");describe('Interactions - Alerts',function(){letdriver;before(asyncfunction(){driver=awaitnewBuilder().forBrowser('chrome').build();});after(async()=>awaitdriver.quit());it('Should be able to getText from alert and accept',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');awaitdriver.findElement(By.id("alert")).click();awaitdriver.wait(until.alertIsPresent());letalert=awaitdriver.switchTo().alert();letalertText=awaitalert.getText();awaitalert.accept();// Verify
assert.equal(alertText,"cheese");});it('Should be able to getText from alert and dismiss',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');awaitdriver.findElement(By.id("confirm")).click();awaitdriver.wait(until.alertIsPresent());letalert=awaitdriver.switchTo().alert();letalertText=awaitalert.getText();awaitalert.dismiss();// Verify
assert.equal(alertText,"Are you sure?");});it('Should be able to enter text in alert prompt',asyncfunction(){lettext='Selenium';awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');awaitdriver.findElement(By.id("prompt")).click();awaitdriver.wait(until.alertIsPresent());letalert=awaitdriver.switchTo().alert();//Type your message
awaitalert.sendKeys(text);awaitalert.accept();letenteredText=awaitdriver.findElement(By.id('text'));assert.equal(awaitenteredText.getText(),text);});});
//Click the link to activate the alert
driver.findElement(By.linkText("See a sample prompt")).click()//Wait for the alert to be displayed and store it in a variable
valalert=wait.until(ExpectedConditions.alertIsPresent())//Type your message
alert.sendKeys("Selenium")//Press the OK button
alert.accept()
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser contextdriver.manage().addCookie(newCookie("key","value"));
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.Cookie;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeDriver;importjava.util.Set;publicclassCookiesTest{WebDriverdriver=newChromeDriver();@TestpublicvoidaddCookie(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser contextdriver.manage().addCookie(newCookie("key","value"));driver.quit();}@TestpublicvoidgetNamedCookie(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser contextdriver.manage().addCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookiecookie=driver.manage().getCookieNamed("foo");Assertions.assertEquals(cookie.getValue(),"bar");driver.quit();}@TestpublicvoidgetAllCookies(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser contextdriver.manage().addCookie(newCookie("test1","cookie1"));driver.manage().addCookie(newCookie("test2","cookie2"));// Get cookiesSet<Cookie>cookies=driver.manage().getCookies();for(Cookiecookie:cookies){if(cookie.getName().equals("test1")){Assertions.assertEquals(cookie.getValue(),"cookie1");}if(cookie.getName().equals("test2")){Assertions.assertEquals(cookie.getValue(),"cookie2");}}driver.quit();}@TestpublicvoiddeleteCookieNamed(){driver.get("https://www.selenium.dev/selenium/web/blank.html");driver.manage().addCookie(newCookie("test1","cookie1"));// delete cookie nameddriver.manage().deleteCookieNamed("test1");driver.quit();}@TestpublicvoiddeleteCookieObject(){driver.get("https://www.selenium.dev/selenium/web/blank.html");Cookiecookie=newCookie("test2","cookie2");driver.manage().addCookie(cookie);/*
Selenium Java bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/driver.manage().deleteCookie(cookie);driver.quit();}@TestpublicvoiddeleteAllCookies(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser contextdriver.manage().addCookie(newCookie("test1","cookie1"));driver.manage().addCookie(newCookie("test2","cookie2"));// Delete All cookiesdriver.manage().deleteAllCookies();driver.quit();}@TestpublicvoidsameSiteCookie(){driver.get("http://www.example.com");Cookiecookie=newCookie.Builder("key","value").sameSite("Strict").build();Cookiecookie1=newCookie.Builder("key","value").sameSite("Lax").build();driver.manage().addCookie(cookie);driver.manage().addCookie(cookie1);System.out.println(cookie.getSameSite());System.out.println(cookie1.getSameSite());driver.quit();}}
driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser contextdriver.add_cookie({"name":"key","value":"value"})
Show full example
fromseleniumimportwebdriverdefadd_cookie():driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser contextdriver.add_cookie({"name":"key","value":"value"})defget_named_cookie():driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser contextdriver.add_cookie({"name":"foo","value":"bar"})# Get cookie details with named cookie 'foo'print(driver.get_cookie("foo"))defget_all_cookies():driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Get all available cookiesprint(driver.get_cookies())defdelete_cookie():driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Delete cookie with name 'test1'driver.delete_cookie("test1")defdelete_all_cookies():driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Delete all cookiesdriver.delete_all_cookies()defsame_side_cookie_attr():driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'driver.add_cookie({"name":"foo","value":"value","sameSite":"Strict"})driver.add_cookie({"name":"foo1","value":"value","sameSite":"Lax"})cookie1=driver.get_cookie("foo")cookie2=driver.get_cookie("foo1")print(cookie1)print(cookie2)
driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("key","value"));
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocs.Interactions{[TestClass]publicclassCookiesTest{WebDriverdriver=newChromeDriver(); [TestMethod]publicvoidaddCookie(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("key","value"));driver.Quit();} [TestMethod]publicvoidgetNamedCookie(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookiecookie=driver.Manage().Cookies.GetCookieNamed("foo");Assert.AreEqual(cookie.Value,"bar");driver.Quit();} [TestMethod]publicvoidgetAllCookies(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Get cookiesvarcookies=driver.Manage().Cookies.AllCookies;foreach(varcookieincookies){if(cookie.Name.Equals("test1")){Assert.AreEqual("cookie1",cookie.Value);}if(cookie.Name.Equals("test2")){Assert.AreEqual("cookie2",cookie.Value);}}driver.Quit();} [TestMethod]publicvoiddeleteCookieNamed(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));// delete cookie nameddriver.Manage().Cookies.DeleteCookieNamed("test1");driver.Quit();} [TestMethod]publicvoiddeleteCookieObject(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";Cookiecookie=newCookie("test2","cookie2");driver.Manage().Cookies.AddCookie(cookie);/*
Selenium CSharp bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/driver.Manage().Cookies.DeleteCookie(cookie);driver.Quit();} [TestMethod]publicvoiddeleteAllCookies(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Delete All cookiesdriver.Manage().Cookies.DeleteAllCookies();driver.Quit();}}}
require'selenium-webdriver'driver=Selenium::WebDriver.for:chromebegindriver.get'https://www.example.com'# Adds the cookie into current browser contextdriver.manage.add_cookie(name:"key",value:"value")ensuredriver.quitend
Show full example
const{Browser,Builder}=require("selenium-webdriver");describe('Cookies',function(){letdriver;before(asyncfunction(){driver=newBuilder().forBrowser(Browser.CHROME).build();});after(async()=>awaitdriver.quit());it('Create a cookie',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain
awaitdriver.manage().addCookie({name:'key',value:'value'});});it('Create cookies with sameSite',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'
awaitdriver.manage().addCookie({name:'key',value:'value',sameSite:'Strict'});awaitdriver.manage().addCookie({name:'key',value:'value',sameSite:'Lax'});});it('Read cookie',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain
awaitdriver.manage().addCookie({name:'foo',value:'bar'});// Get cookie details with named cookie 'foo'
awaitdriver.manage().getCookie('foo').then(function(cookie){console.log('cookie details => ',cookie);});});it('Read all cookies',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookies
awaitdriver.manage().addCookie({name:'test1',value:'cookie1'});awaitdriver.manage().addCookie({name:'test2',value:'cookie2'});// Get all Available cookies
awaitdriver.manage().getCookies().then(function(cookies){console.log('cookie details => ',cookies);});});it('Delete a cookie',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookies
awaitdriver.manage().addCookie({name:'test1',value:'cookie1'});awaitdriver.manage().addCookie({name:'test2',value:'cookie2'});// Delete a cookie with name 'test1'
awaitdriver.manage().deleteCookie('test1');// Get all Available cookies
awaitdriver.manage().getCookies().then(function(cookies){console.log('cookie details => ',cookies);});});it('Delete all cookies',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookies
awaitdriver.manage().addCookie({name:'test1',value:'cookie1'});awaitdriver.manage().addCookie({name:'test2',value:'cookie2'});// Delete all cookies
awaitdriver.manage().deleteAllCookies();});});
importorg.openqa.selenium.Cookieimportorg.openqa.selenium.chrome.ChromeDriverfunmain(){valdriver=ChromeDriver()try{driver.get("https://example.com")// Adds the cookie into current browser context
driver.manage().addCookie(Cookie("key","value"))}finally{driver.quit()}}
获取命名的 Cookie
此方法返回与cookie名称匹配的序列化cookie数据中所有关联的cookie.
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser contextdriver.manage().addCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookiecookie=driver.manage().getCookieNamed("foo");
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.Cookie;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeDriver;importjava.util.Set;publicclassCookiesTest{WebDriverdriver=newChromeDriver();@TestpublicvoidaddCookie(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser contextdriver.manage().addCookie(newCookie("key","value"));driver.quit();}@TestpublicvoidgetNamedCookie(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser contextdriver.manage().addCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookiecookie=driver.manage().getCookieNamed("foo");Assertions.assertEquals(cookie.getValue(),"bar");driver.quit();}@TestpublicvoidgetAllCookies(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser contextdriver.manage().addCookie(newCookie("test1","cookie1"));driver.manage().addCookie(newCookie("test2","cookie2"));// Get cookiesSet<Cookie>cookies=driver.manage().getCookies();for(Cookiecookie:cookies){if(cookie.getName().equals("test1")){Assertions.assertEquals(cookie.getValue(),"cookie1");}if(cookie.getName().equals("test2")){Assertions.assertEquals(cookie.getValue(),"cookie2");}}driver.quit();}@TestpublicvoiddeleteCookieNamed(){driver.get("https://www.selenium.dev/selenium/web/blank.html");driver.manage().addCookie(newCookie("test1","cookie1"));// delete cookie nameddriver.manage().deleteCookieNamed("test1");driver.quit();}@TestpublicvoiddeleteCookieObject(){driver.get("https://www.selenium.dev/selenium/web/blank.html");Cookiecookie=newCookie("test2","cookie2");driver.manage().addCookie(cookie);/*
Selenium Java bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/driver.manage().deleteCookie(cookie);driver.quit();}@TestpublicvoiddeleteAllCookies(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser contextdriver.manage().addCookie(newCookie("test1","cookie1"));driver.manage().addCookie(newCookie("test2","cookie2"));// Delete All cookiesdriver.manage().deleteAllCookies();driver.quit();}@TestpublicvoidsameSiteCookie(){driver.get("http://www.example.com");Cookiecookie=newCookie.Builder("key","value").sameSite("Strict").build();Cookiecookie1=newCookie.Builder("key","value").sameSite("Lax").build();driver.manage().addCookie(cookie);driver.manage().addCookie(cookie1);System.out.println(cookie.getSameSite());System.out.println(cookie1.getSameSite());driver.quit();}}
driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser contextdriver.add_cookie({"name":"foo","value":"bar"})# Get cookie details with named cookie 'foo'print(driver.get_cookie("foo"))
Show full example
fromseleniumimportwebdriverdefadd_cookie():driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser contextdriver.add_cookie({"name":"key","value":"value"})defget_named_cookie():driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser contextdriver.add_cookie({"name":"foo","value":"bar"})# Get cookie details with named cookie 'foo'print(driver.get_cookie("foo"))defget_all_cookies():driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Get all available cookiesprint(driver.get_cookies())defdelete_cookie():driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Delete cookie with name 'test1'driver.delete_cookie("test1")defdelete_all_cookies():driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Delete all cookiesdriver.delete_all_cookies()defsame_side_cookie_attr():driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'driver.add_cookie({"name":"foo","value":"value","sameSite":"Strict"})driver.add_cookie({"name":"foo1","value":"value","sameSite":"Lax"})cookie1=driver.get_cookie("foo")cookie2=driver.get_cookie("foo1")print(cookie1)print(cookie2)
driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookiecookie=driver.Manage().Cookies.GetCookieNamed("foo");
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocs.Interactions{[TestClass]publicclassCookiesTest{WebDriverdriver=newChromeDriver(); [TestMethod]publicvoidaddCookie(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("key","value"));driver.Quit();} [TestMethod]publicvoidgetNamedCookie(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookiecookie=driver.Manage().Cookies.GetCookieNamed("foo");Assert.AreEqual(cookie.Value,"bar");driver.Quit();} [TestMethod]publicvoidgetAllCookies(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Get cookiesvarcookies=driver.Manage().Cookies.AllCookies;foreach(varcookieincookies){if(cookie.Name.Equals("test1")){Assert.AreEqual("cookie1",cookie.Value);}if(cookie.Name.Equals("test2")){Assert.AreEqual("cookie2",cookie.Value);}}driver.Quit();} [TestMethod]publicvoiddeleteCookieNamed(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));// delete cookie nameddriver.Manage().Cookies.DeleteCookieNamed("test1");driver.Quit();} [TestMethod]publicvoiddeleteCookieObject(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";Cookiecookie=newCookie("test2","cookie2");driver.Manage().Cookies.AddCookie(cookie);/*
Selenium CSharp bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/driver.Manage().Cookies.DeleteCookie(cookie);driver.Quit();} [TestMethod]publicvoiddeleteAllCookies(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Delete All cookiesdriver.Manage().Cookies.DeleteAllCookies();driver.Quit();}}}
require'selenium-webdriver'driver=Selenium::WebDriver.for:chromebegindriver.get'https://www.example.com'driver.manage.add_cookie(name:"foo",value:"bar")# Get cookie details with named cookie 'foo'putsdriver.manage.cookie_named('foo')ensuredriver.quitend
awaitdriver.manage().addCookie({name:'foo',value:'bar'});// Get cookie details with named cookie 'foo'
awaitdriver.manage().getCookie('foo').then(function(cookie){
Show full example
const{Browser,Builder}=require("selenium-webdriver");describe('Cookies',function(){letdriver;before(asyncfunction(){driver=newBuilder().forBrowser(Browser.CHROME).build();});after(async()=>awaitdriver.quit());it('Create a cookie',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain
awaitdriver.manage().addCookie({name:'key',value:'value'});});it('Create cookies with sameSite',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'
awaitdriver.manage().addCookie({name:'key',value:'value',sameSite:'Strict'});awaitdriver.manage().addCookie({name:'key',value:'value',sameSite:'Lax'});});it('Read cookie',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain
awaitdriver.manage().addCookie({name:'foo',value:'bar'});// Get cookie details with named cookie 'foo'
awaitdriver.manage().getCookie('foo').then(function(cookie){console.log('cookie details => ',cookie);});});it('Read all cookies',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookies
awaitdriver.manage().addCookie({name:'test1',value:'cookie1'});awaitdriver.manage().addCookie({name:'test2',value:'cookie2'});// Get all Available cookies
awaitdriver.manage().getCookies().then(function(cookies){console.log('cookie details => ',cookies);});});it('Delete a cookie',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookies
awaitdriver.manage().addCookie({name:'test1',value:'cookie1'});awaitdriver.manage().addCookie({name:'test2',value:'cookie2'});// Delete a cookie with name 'test1'
awaitdriver.manage().deleteCookie('test1');// Get all Available cookies
awaitdriver.manage().getCookies().then(function(cookies){console.log('cookie details => ',cookies);});});it('Delete all cookies',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookies
awaitdriver.manage().addCookie({name:'test1',value:'cookie1'});awaitdriver.manage().addCookie({name:'test2',value:'cookie2'});// Delete all cookies
awaitdriver.manage().deleteAllCookies();});});
importorg.openqa.selenium.Cookieimportorg.openqa.selenium.chrome.ChromeDriverfunmain(){valdriver=ChromeDriver()try{driver.get("https://example.com")driver.manage().addCookie(Cookie("foo","bar"))// Get cookie details with named cookie 'foo'
valcookie=driver.manage().getCookieNamed("foo")println(cookie)}finally{driver.quit()}}
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser contextdriver.manage().addCookie(newCookie("test1","cookie1"));driver.manage().addCookie(newCookie("test2","cookie2"));// Get cookiesSet<Cookie>cookies=driver.manage().getCookies();for(Cookiecookie:cookies){if(cookie.getName().equals("test1")){Assertions.assertEquals(cookie.getValue(),"cookie1");}if(cookie.getName().equals("test2")){Assertions.assertEquals(cookie.getValue(),"cookie2");}}
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.Cookie;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeDriver;importjava.util.Set;publicclassCookiesTest{WebDriverdriver=newChromeDriver();@TestpublicvoidaddCookie(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser contextdriver.manage().addCookie(newCookie("key","value"));driver.quit();}@TestpublicvoidgetNamedCookie(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser contextdriver.manage().addCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookiecookie=driver.manage().getCookieNamed("foo");Assertions.assertEquals(cookie.getValue(),"bar");driver.quit();}@TestpublicvoidgetAllCookies(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser contextdriver.manage().addCookie(newCookie("test1","cookie1"));driver.manage().addCookie(newCookie("test2","cookie2"));// Get cookiesSet<Cookie>cookies=driver.manage().getCookies();for(Cookiecookie:cookies){if(cookie.getName().equals("test1")){Assertions.assertEquals(cookie.getValue(),"cookie1");}if(cookie.getName().equals("test2")){Assertions.assertEquals(cookie.getValue(),"cookie2");}}driver.quit();}@TestpublicvoiddeleteCookieNamed(){driver.get("https://www.selenium.dev/selenium/web/blank.html");driver.manage().addCookie(newCookie("test1","cookie1"));// delete cookie nameddriver.manage().deleteCookieNamed("test1");driver.quit();}@TestpublicvoiddeleteCookieObject(){driver.get("https://www.selenium.dev/selenium/web/blank.html");Cookiecookie=newCookie("test2","cookie2");driver.manage().addCookie(cookie);/*
Selenium Java bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/driver.manage().deleteCookie(cookie);driver.quit();}@TestpublicvoiddeleteAllCookies(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser contextdriver.manage().addCookie(newCookie("test1","cookie1"));driver.manage().addCookie(newCookie("test2","cookie2"));// Delete All cookiesdriver.manage().deleteAllCookies();driver.quit();}@TestpublicvoidsameSiteCookie(){driver.get("http://www.example.com");Cookiecookie=newCookie.Builder("key","value").sameSite("Strict").build();Cookiecookie1=newCookie.Builder("key","value").sameSite("Lax").build();driver.manage().addCookie(cookie);driver.manage().addCookie(cookie1);System.out.println(cookie.getSameSite());System.out.println(cookie1.getSameSite());driver.quit();}}
driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Get all available cookiesprint(driver.get_cookies())
Show full example
fromseleniumimportwebdriverdefadd_cookie():driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser contextdriver.add_cookie({"name":"key","value":"value"})defget_named_cookie():driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser contextdriver.add_cookie({"name":"foo","value":"bar"})# Get cookie details with named cookie 'foo'print(driver.get_cookie("foo"))defget_all_cookies():driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Get all available cookiesprint(driver.get_cookies())defdelete_cookie():driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Delete cookie with name 'test1'driver.delete_cookie("test1")defdelete_all_cookies():driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Delete all cookiesdriver.delete_all_cookies()defsame_side_cookie_attr():driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'driver.add_cookie({"name":"foo","value":"value","sameSite":"Strict"})driver.add_cookie({"name":"foo1","value":"value","sameSite":"Lax"})cookie1=driver.get_cookie("foo")cookie2=driver.get_cookie("foo1")print(cookie1)print(cookie2)
driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Get cookiesvarcookies=driver.Manage().Cookies.AllCookies;foreach(varcookieincookies){if(cookie.Name.Equals("test1")){Assert.AreEqual("cookie1",cookie.Value);}if(cookie.Name.Equals("test2")){Assert.AreEqual("cookie2",cookie.Value);}}
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocs.Interactions{[TestClass]publicclassCookiesTest{WebDriverdriver=newChromeDriver(); [TestMethod]publicvoidaddCookie(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("key","value"));driver.Quit();} [TestMethod]publicvoidgetNamedCookie(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookiecookie=driver.Manage().Cookies.GetCookieNamed("foo");Assert.AreEqual(cookie.Value,"bar");driver.Quit();} [TestMethod]publicvoidgetAllCookies(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Get cookiesvarcookies=driver.Manage().Cookies.AllCookies;foreach(varcookieincookies){if(cookie.Name.Equals("test1")){Assert.AreEqual("cookie1",cookie.Value);}if(cookie.Name.Equals("test2")){Assert.AreEqual("cookie2",cookie.Value);}}driver.Quit();} [TestMethod]publicvoiddeleteCookieNamed(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));// delete cookie nameddriver.Manage().Cookies.DeleteCookieNamed("test1");driver.Quit();} [TestMethod]publicvoiddeleteCookieObject(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";Cookiecookie=newCookie("test2","cookie2");driver.Manage().Cookies.AddCookie(cookie);/*
Selenium CSharp bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/driver.Manage().Cookies.DeleteCookie(cookie);driver.Quit();} [TestMethod]publicvoiddeleteAllCookies(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Delete All cookiesdriver.Manage().Cookies.DeleteAllCookies();driver.Quit();}}}
require'selenium-webdriver'driver=Selenium::WebDriver.for:chromebegindriver.get'https://www.example.com'driver.manage.add_cookie(name:"test1",value:"cookie1")driver.manage.add_cookie(name:"test2",value:"cookie2")# Get all available cookiesputsdriver.manage.all_cookiesensuredriver.quitend
// Get all Available cookies
awaitdriver.manage().getCookies().then(function(cookies){
Show full example
const{Browser,Builder}=require("selenium-webdriver");describe('Cookies',function(){letdriver;before(asyncfunction(){driver=newBuilder().forBrowser(Browser.CHROME).build();});after(async()=>awaitdriver.quit());it('Create a cookie',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain
awaitdriver.manage().addCookie({name:'key',value:'value'});});it('Create cookies with sameSite',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'
awaitdriver.manage().addCookie({name:'key',value:'value',sameSite:'Strict'});awaitdriver.manage().addCookie({name:'key',value:'value',sameSite:'Lax'});});it('Read cookie',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain
awaitdriver.manage().addCookie({name:'foo',value:'bar'});// Get cookie details with named cookie 'foo'
awaitdriver.manage().getCookie('foo').then(function(cookie){console.log('cookie details => ',cookie);});});it('Read all cookies',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookies
awaitdriver.manage().addCookie({name:'test1',value:'cookie1'});awaitdriver.manage().addCookie({name:'test2',value:'cookie2'});// Get all Available cookies
awaitdriver.manage().getCookies().then(function(cookies){console.log('cookie details => ',cookies);});});it('Delete a cookie',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookies
awaitdriver.manage().addCookie({name:'test1',value:'cookie1'});awaitdriver.manage().addCookie({name:'test2',value:'cookie2'});// Delete a cookie with name 'test1'
awaitdriver.manage().deleteCookie('test1');// Get all Available cookies
awaitdriver.manage().getCookies().then(function(cookies){console.log('cookie details => ',cookies);});});it('Delete all cookies',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookies
awaitdriver.manage().addCookie({name:'test1',value:'cookie1'});awaitdriver.manage().addCookie({name:'test2',value:'cookie2'});// Delete all cookies
awaitdriver.manage().deleteAllCookies();});});
importorg.openqa.selenium.Cookieimportorg.openqa.selenium.chrome.ChromeDriverfunmain(){valdriver=ChromeDriver()try{driver.get("https://example.com")driver.manage().addCookie(Cookie("test1","cookie1"))driver.manage().addCookie(Cookie("test2","cookie2"))// Get All available cookies
valcookies=driver.manage().cookiesprintln(cookies)}finally{driver.quit()}}
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.Cookie;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeDriver;importjava.util.Set;publicclassCookiesTest{WebDriverdriver=newChromeDriver();@TestpublicvoidaddCookie(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser contextdriver.manage().addCookie(newCookie("key","value"));driver.quit();}@TestpublicvoidgetNamedCookie(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser contextdriver.manage().addCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookiecookie=driver.manage().getCookieNamed("foo");Assertions.assertEquals(cookie.getValue(),"bar");driver.quit();}@TestpublicvoidgetAllCookies(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser contextdriver.manage().addCookie(newCookie("test1","cookie1"));driver.manage().addCookie(newCookie("test2","cookie2"));// Get cookiesSet<Cookie>cookies=driver.manage().getCookies();for(Cookiecookie:cookies){if(cookie.getName().equals("test1")){Assertions.assertEquals(cookie.getValue(),"cookie1");}if(cookie.getName().equals("test2")){Assertions.assertEquals(cookie.getValue(),"cookie2");}}driver.quit();}@TestpublicvoiddeleteCookieNamed(){driver.get("https://www.selenium.dev/selenium/web/blank.html");driver.manage().addCookie(newCookie("test1","cookie1"));// delete cookie nameddriver.manage().deleteCookieNamed("test1");driver.quit();}@TestpublicvoiddeleteCookieObject(){driver.get("https://www.selenium.dev/selenium/web/blank.html");Cookiecookie=newCookie("test2","cookie2");driver.manage().addCookie(cookie);/*
Selenium Java bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/driver.manage().deleteCookie(cookie);driver.quit();}@TestpublicvoiddeleteAllCookies(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser contextdriver.manage().addCookie(newCookie("test1","cookie1"));driver.manage().addCookie(newCookie("test2","cookie2"));// Delete All cookiesdriver.manage().deleteAllCookies();driver.quit();}@TestpublicvoidsameSiteCookie(){driver.get("http://www.example.com");Cookiecookie=newCookie.Builder("key","value").sameSite("Strict").build();Cookiecookie1=newCookie.Builder("key","value").sameSite("Lax").build();driver.manage().addCookie(cookie);driver.manage().addCookie(cookie1);System.out.println(cookie.getSameSite());System.out.println(cookie1.getSameSite());driver.quit();}}
driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Delete cookie with name 'test1'driver.delete_cookie("test1")
Show full example
fromseleniumimportwebdriverdefadd_cookie():driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser contextdriver.add_cookie({"name":"key","value":"value"})defget_named_cookie():driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser contextdriver.add_cookie({"name":"foo","value":"bar"})# Get cookie details with named cookie 'foo'print(driver.get_cookie("foo"))defget_all_cookies():driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Get all available cookiesprint(driver.get_cookies())defdelete_cookie():driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Delete cookie with name 'test1'driver.delete_cookie("test1")defdelete_all_cookies():driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Delete all cookiesdriver.delete_all_cookies()defsame_side_cookie_attr():driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'driver.add_cookie({"name":"foo","value":"value","sameSite":"Strict"})driver.add_cookie({"name":"foo1","value":"value","sameSite":"Lax"})cookie1=driver.get_cookie("foo")cookie2=driver.get_cookie("foo1")print(cookie1)print(cookie2)
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocs.Interactions{[TestClass]publicclassCookiesTest{WebDriverdriver=newChromeDriver(); [TestMethod]publicvoidaddCookie(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("key","value"));driver.Quit();} [TestMethod]publicvoidgetNamedCookie(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookiecookie=driver.Manage().Cookies.GetCookieNamed("foo");Assert.AreEqual(cookie.Value,"bar");driver.Quit();} [TestMethod]publicvoidgetAllCookies(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Get cookiesvarcookies=driver.Manage().Cookies.AllCookies;foreach(varcookieincookies){if(cookie.Name.Equals("test1")){Assert.AreEqual("cookie1",cookie.Value);}if(cookie.Name.Equals("test2")){Assert.AreEqual("cookie2",cookie.Value);}}driver.Quit();} [TestMethod]publicvoiddeleteCookieNamed(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));// delete cookie nameddriver.Manage().Cookies.DeleteCookieNamed("test1");driver.Quit();} [TestMethod]publicvoiddeleteCookieObject(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";Cookiecookie=newCookie("test2","cookie2");driver.Manage().Cookies.AddCookie(cookie);/*
Selenium CSharp bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/driver.Manage().Cookies.DeleteCookie(cookie);driver.Quit();} [TestMethod]publicvoiddeleteAllCookies(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Delete All cookiesdriver.Manage().Cookies.DeleteAllCookies();driver.Quit();}}}
require'selenium-webdriver'driver=Selenium::WebDriver.for:chromebegindriver.get'https://www.example.com'driver.manage.add_cookie(name:"test1",value:"cookie1")driver.manage.add_cookie(name:"test2",value:"cookie2")# delete a cookie with name 'test1'driver.manage.delete_cookie('test1')ensuredriver.quitend
const{Browser,Builder}=require("selenium-webdriver");describe('Cookies',function(){letdriver;before(asyncfunction(){driver=newBuilder().forBrowser(Browser.CHROME).build();});after(async()=>awaitdriver.quit());it('Create a cookie',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain
awaitdriver.manage().addCookie({name:'key',value:'value'});});it('Create cookies with sameSite',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'
awaitdriver.manage().addCookie({name:'key',value:'value',sameSite:'Strict'});awaitdriver.manage().addCookie({name:'key',value:'value',sameSite:'Lax'});});it('Read cookie',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain
awaitdriver.manage().addCookie({name:'foo',value:'bar'});// Get cookie details with named cookie 'foo'
awaitdriver.manage().getCookie('foo').then(function(cookie){console.log('cookie details => ',cookie);});});it('Read all cookies',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookies
awaitdriver.manage().addCookie({name:'test1',value:'cookie1'});awaitdriver.manage().addCookie({name:'test2',value:'cookie2'});// Get all Available cookies
awaitdriver.manage().getCookies().then(function(cookies){console.log('cookie details => ',cookies);});});it('Delete a cookie',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookies
awaitdriver.manage().addCookie({name:'test1',value:'cookie1'});awaitdriver.manage().addCookie({name:'test2',value:'cookie2'});// Delete a cookie with name 'test1'
awaitdriver.manage().deleteCookie('test1');// Get all Available cookies
awaitdriver.manage().getCookies().then(function(cookies){console.log('cookie details => ',cookies);});});it('Delete all cookies',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookies
awaitdriver.manage().addCookie({name:'test1',value:'cookie1'});awaitdriver.manage().addCookie({name:'test2',value:'cookie2'});// Delete all cookies
awaitdriver.manage().deleteAllCookies();});});
importorg.openqa.selenium.Cookieimportorg.openqa.selenium.chrome.ChromeDriverfunmain(){valdriver=ChromeDriver()try{driver.get("https://example.com")driver.manage().addCookie(Cookie("test1","cookie1"))valcookie1=Cookie("test2","cookie2")driver.manage().addCookie(cookie1)// delete a cookie with name 'test1'
driver.manage().deleteCookieNamed("test1")// delete cookie by passing cookie object of current browsing context.
driver.manage().deleteCookie(cookie1)}finally{driver.quit()}}
删除所有 Cookies
此方法删除当前访问上下文的所有cookie.
driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser contextdriver.manage().addCookie(newCookie("test1","cookie1"));driver.manage().addCookie(newCookie("test2","cookie2"));// Delete All cookiesdriver.manage().deleteAllCookies();
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.Cookie;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeDriver;importjava.util.Set;publicclassCookiesTest{WebDriverdriver=newChromeDriver();@TestpublicvoidaddCookie(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser contextdriver.manage().addCookie(newCookie("key","value"));driver.quit();}@TestpublicvoidgetNamedCookie(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser contextdriver.manage().addCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookiecookie=driver.manage().getCookieNamed("foo");Assertions.assertEquals(cookie.getValue(),"bar");driver.quit();}@TestpublicvoidgetAllCookies(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser contextdriver.manage().addCookie(newCookie("test1","cookie1"));driver.manage().addCookie(newCookie("test2","cookie2"));// Get cookiesSet<Cookie>cookies=driver.manage().getCookies();for(Cookiecookie:cookies){if(cookie.getName().equals("test1")){Assertions.assertEquals(cookie.getValue(),"cookie1");}if(cookie.getName().equals("test2")){Assertions.assertEquals(cookie.getValue(),"cookie2");}}driver.quit();}@TestpublicvoiddeleteCookieNamed(){driver.get("https://www.selenium.dev/selenium/web/blank.html");driver.manage().addCookie(newCookie("test1","cookie1"));// delete cookie nameddriver.manage().deleteCookieNamed("test1");driver.quit();}@TestpublicvoiddeleteCookieObject(){driver.get("https://www.selenium.dev/selenium/web/blank.html");Cookiecookie=newCookie("test2","cookie2");driver.manage().addCookie(cookie);/*
Selenium Java bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/driver.manage().deleteCookie(cookie);driver.quit();}@TestpublicvoiddeleteAllCookies(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser contextdriver.manage().addCookie(newCookie("test1","cookie1"));driver.manage().addCookie(newCookie("test2","cookie2"));// Delete All cookiesdriver.manage().deleteAllCookies();driver.quit();}@TestpublicvoidsameSiteCookie(){driver.get("http://www.example.com");Cookiecookie=newCookie.Builder("key","value").sameSite("Strict").build();Cookiecookie1=newCookie.Builder("key","value").sameSite("Lax").build();driver.manage().addCookie(cookie);driver.manage().addCookie(cookie1);System.out.println(cookie.getSameSite());System.out.println(cookie1.getSameSite());driver.quit();}}
driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Delete all cookiesdriver.delete_all_cookies()
Show full example
fromseleniumimportwebdriverdefadd_cookie():driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser contextdriver.add_cookie({"name":"key","value":"value"})defget_named_cookie():driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser contextdriver.add_cookie({"name":"foo","value":"bar"})# Get cookie details with named cookie 'foo'print(driver.get_cookie("foo"))defget_all_cookies():driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Get all available cookiesprint(driver.get_cookies())defdelete_cookie():driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Delete cookie with name 'test1'driver.delete_cookie("test1")defdelete_all_cookies():driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Delete all cookiesdriver.delete_all_cookies()defsame_side_cookie_attr():driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'driver.add_cookie({"name":"foo","value":"value","sameSite":"Strict"})driver.add_cookie({"name":"foo1","value":"value","sameSite":"Lax"})cookie1=driver.get_cookie("foo")cookie2=driver.get_cookie("foo1")print(cookie1)print(cookie2)
driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Delete All cookiesdriver.Manage().Cookies.DeleteAllCookies();
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocs.Interactions{[TestClass]publicclassCookiesTest{WebDriverdriver=newChromeDriver(); [TestMethod]publicvoidaddCookie(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("key","value"));driver.Quit();} [TestMethod]publicvoidgetNamedCookie(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookie into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookiecookie=driver.Manage().Cookies.GetCookieNamed("foo");Assert.AreEqual(cookie.Value,"bar");driver.Quit();} [TestMethod]publicvoidgetAllCookies(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Get cookiesvarcookies=driver.Manage().Cookies.AllCookies;foreach(varcookieincookies){if(cookie.Name.Equals("test1")){Assert.AreEqual("cookie1",cookie.Value);}if(cookie.Name.Equals("test2")){Assert.AreEqual("cookie2",cookie.Value);}}driver.Quit();} [TestMethod]publicvoiddeleteCookieNamed(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";driver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));// delete cookie nameddriver.Manage().Cookies.DeleteCookieNamed("test1");driver.Quit();} [TestMethod]publicvoiddeleteCookieObject(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";Cookiecookie=newCookie("test2","cookie2");driver.Manage().Cookies.AddCookie(cookie);/*
Selenium CSharp bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/driver.Manage().Cookies.DeleteCookie(cookie);driver.Quit();} [TestMethod]publicvoiddeleteAllCookies(){driver.Url="https://www.selenium.dev/selenium/web/blank.html";// Add cookies into current browser contextdriver.Manage().Cookies.AddCookie(newCookie("test1","cookie1"));driver.Manage().Cookies.AddCookie(newCookie("test2","cookie2"));// Delete All cookiesdriver.Manage().Cookies.DeleteAllCookies();driver.Quit();}}}
require'selenium-webdriver'driver=Selenium::WebDriver.for:chromebegindriver.get'https://www.example.com'driver.manage.add_cookie(name:"test1",value:"cookie1")driver.manage.add_cookie(name:"test2",value:"cookie2")# deletes all cookiesdriver.manage.delete_all_cookiesensuredriver.quitend
const{Browser,Builder}=require("selenium-webdriver");describe('Cookies',function(){letdriver;before(asyncfunction(){driver=newBuilder().forBrowser(Browser.CHROME).build();});after(async()=>awaitdriver.quit());it('Create a cookie',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain
awaitdriver.manage().addCookie({name:'key',value:'value'});});it('Create cookies with sameSite',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'
awaitdriver.manage().addCookie({name:'key',value:'value',sameSite:'Strict'});awaitdriver.manage().addCookie({name:'key',value:'value',sameSite:'Lax'});});it('Read cookie',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain
awaitdriver.manage().addCookie({name:'foo',value:'bar'});// Get cookie details with named cookie 'foo'
awaitdriver.manage().getCookie('foo').then(function(cookie){console.log('cookie details => ',cookie);});});it('Read all cookies',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookies
awaitdriver.manage().addCookie({name:'test1',value:'cookie1'});awaitdriver.manage().addCookie({name:'test2',value:'cookie2'});// Get all Available cookies
awaitdriver.manage().getCookies().then(function(cookies){console.log('cookie details => ',cookies);});});it('Delete a cookie',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookies
awaitdriver.manage().addCookie({name:'test1',value:'cookie1'});awaitdriver.manage().addCookie({name:'test2',value:'cookie2'});// Delete a cookie with name 'test1'
awaitdriver.manage().deleteCookie('test1');// Get all Available cookies
awaitdriver.manage().getCookies().then(function(cookies){console.log('cookie details => ',cookies);});});it('Delete all cookies',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookies
awaitdriver.manage().addCookie({name:'test1',value:'cookie1'});awaitdriver.manage().addCookie({name:'test2',value:'cookie2'});// Delete all cookies
awaitdriver.manage().deleteAllCookies();});});
importorg.openqa.selenium.Cookieimportorg.openqa.selenium.chrome.ChromeDriverfunmain(){valdriver=ChromeDriver()try{driver.get("https://example.com")driver.manage().addCookie(Cookie("test1","cookie1"))driver.manage().addCookie(Cookie("test2","cookie2"))// deletes all cookies
driver.manage().deleteAllCookies()}finally{driver.quit()}}
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.Cookie;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeDriver;importjava.util.Set;publicclassCookiesTest{WebDriverdriver=newChromeDriver();@TestpublicvoidaddCookie(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser contextdriver.manage().addCookie(newCookie("key","value"));driver.quit();}@TestpublicvoidgetNamedCookie(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookie into current browser contextdriver.manage().addCookie(newCookie("foo","bar"));// Get cookie details with named cookie 'foo'Cookiecookie=driver.manage().getCookieNamed("foo");Assertions.assertEquals(cookie.getValue(),"bar");driver.quit();}@TestpublicvoidgetAllCookies(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser contextdriver.manage().addCookie(newCookie("test1","cookie1"));driver.manage().addCookie(newCookie("test2","cookie2"));// Get cookiesSet<Cookie>cookies=driver.manage().getCookies();for(Cookiecookie:cookies){if(cookie.getName().equals("test1")){Assertions.assertEquals(cookie.getValue(),"cookie1");}if(cookie.getName().equals("test2")){Assertions.assertEquals(cookie.getValue(),"cookie2");}}driver.quit();}@TestpublicvoiddeleteCookieNamed(){driver.get("https://www.selenium.dev/selenium/web/blank.html");driver.manage().addCookie(newCookie("test1","cookie1"));// delete cookie nameddriver.manage().deleteCookieNamed("test1");driver.quit();}@TestpublicvoiddeleteCookieObject(){driver.get("https://www.selenium.dev/selenium/web/blank.html");Cookiecookie=newCookie("test2","cookie2");driver.manage().addCookie(cookie);/*
Selenium Java bindings also provides a way to delete
cookie by passing cookie object of current browsing context
*/driver.manage().deleteCookie(cookie);driver.quit();}@TestpublicvoiddeleteAllCookies(){driver.get("https://www.selenium.dev/selenium/web/blank.html");// Add cookies into current browser contextdriver.manage().addCookie(newCookie("test1","cookie1"));driver.manage().addCookie(newCookie("test2","cookie2"));// Delete All cookiesdriver.manage().deleteAllCookies();driver.quit();}@TestpublicvoidsameSiteCookie(){driver.get("http://www.example.com");Cookiecookie=newCookie.Builder("key","value").sameSite("Strict").build();Cookiecookie1=newCookie.Builder("key","value").sameSite("Lax").build();driver.manage().addCookie(cookie);driver.manage().addCookie(cookie1);System.out.println(cookie.getSameSite());System.out.println(cookie1.getSameSite());driver.quit();}}
driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'driver.add_cookie({"name":"foo","value":"value","sameSite":"Strict"})driver.add_cookie({"name":"foo1","value":"value","sameSite":"Lax"})cookie1=driver.get_cookie("foo")cookie2=driver.get_cookie("foo1")print(cookie1)print(cookie2)
Show full example
fromseleniumimportwebdriverdefadd_cookie():driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser contextdriver.add_cookie({"name":"key","value":"value"})defget_named_cookie():driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser contextdriver.add_cookie({"name":"foo","value":"bar"})# Get cookie details with named cookie 'foo'print(driver.get_cookie("foo"))defget_all_cookies():driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Get all available cookiesprint(driver.get_cookies())defdelete_cookie():driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Delete cookie with name 'test1'driver.delete_cookie("test1")defdelete_all_cookies():driver=webdriver.Chrome()driver.get("http://www.example.com")driver.add_cookie({"name":"test1","value":"cookie1"})driver.add_cookie({"name":"test2","value":"cookie2"})# Delete all cookiesdriver.delete_all_cookies()defsame_side_cookie_attr():driver=webdriver.Chrome()driver.get("http://www.example.com")# Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'driver.add_cookie({"name":"foo","value":"value","sameSite":"Strict"})driver.add_cookie({"name":"foo1","value":"value","sameSite":"Lax"})cookie1=driver.get_cookie("foo")cookie2=driver.get_cookie("foo1")print(cookie1)print(cookie2)
require'selenium-webdriver'driver=Selenium::WebDriver.for:chromebegindriver.get'https://www.example.com'# Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'driver.manage.add_cookie(name:"foo",value:"bar",same_site:"Strict")driver.manage.add_cookie(name:"foo1",value:"bar",same_site:"Lax")putsdriver.manage.cookie_named('foo')putsdriver.manage.cookie_named('foo1')ensuredriver.quitend
awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'
Show full example
const{Browser,Builder}=require("selenium-webdriver");describe('Cookies',function(){letdriver;before(asyncfunction(){driver=newBuilder().forBrowser(Browser.CHROME).build();});after(async()=>awaitdriver.quit());it('Create a cookie',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain
awaitdriver.manage().addCookie({name:'key',value:'value'});});it('Create cookies with sameSite',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'
awaitdriver.manage().addCookie({name:'key',value:'value',sameSite:'Strict'});awaitdriver.manage().addCookie({name:'key',value:'value',sameSite:'Lax'});});it('Read cookie',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// set a cookie on the current domain
awaitdriver.manage().addCookie({name:'foo',value:'bar'});// Get cookie details with named cookie 'foo'
awaitdriver.manage().getCookie('foo').then(function(cookie){console.log('cookie details => ',cookie);});});it('Read all cookies',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookies
awaitdriver.manage().addCookie({name:'test1',value:'cookie1'});awaitdriver.manage().addCookie({name:'test2',value:'cookie2'});// Get all Available cookies
awaitdriver.manage().getCookies().then(function(cookies){console.log('cookie details => ',cookies);});});it('Delete a cookie',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookies
awaitdriver.manage().addCookie({name:'test1',value:'cookie1'});awaitdriver.manage().addCookie({name:'test2',value:'cookie2'});// Delete a cookie with name 'test1'
awaitdriver.manage().deleteCookie('test1');// Get all Available cookies
awaitdriver.manage().getCookies().then(function(cookies){console.log('cookie details => ',cookies);});});it('Delete all cookies',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// Add few cookies
awaitdriver.manage().addCookie({name:'test1',value:'cookie1'});awaitdriver.manage().addCookie({name:'test2',value:'cookie2'});// Delete all cookies
awaitdriver.manage().deleteAllCookies();});});
但是,如果 iframe 之外没有按钮,那么您可能会得到一个 no such element 无此元素 的错误。
这是因为 Selenium 只知道顶层文档中的元素。为了与按钮进行交互,我们需要首先切换到框架,
这与切换窗口的方式类似。WebDriver 提供了三种切换到帧的方法。
使用 WebElement
使用 WebElement 进行切换是最灵活的选择。您可以使用首选的选择器找到框架并切换到它。
//switch To IFrame using Web ElementWebElementiframe=driver.findElement(By.id("iframe1"));//Switch to the framedriver.switchTo().frame(iframe);assertEquals(true,driver.getPageSource().contains("We Leave From Here"));//Now we can type text into email fieldWebElementemailE=driver.findElement(By.id("email"));emailE.sendKeys("admin@selenium.dev");emailE.clear();
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.packagedev.selenium.interactions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importjava.time.Duration;import staticorg.junit.jupiter.api.Assertions.assertEquals;publicclassFramesTest{@TestpublicvoidinformationWithElements(){WebDriverdriver=newChromeDriver();driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));// Navigate to Urldriver.get("https://www.selenium.dev/selenium/web/iframes.html");//switch To IFrame using Web ElementWebElementiframe=driver.findElement(By.id("iframe1"));//Switch to the framedriver.switchTo().frame(iframe);assertEquals(true,driver.getPageSource().contains("We Leave From Here"));//Now we can type text into email fieldWebElementemailE=driver.findElement(By.id("email"));emailE.sendKeys("admin@selenium.dev");emailE.clear();driver.switchTo().defaultContent();//switch To IFrame using name or iddriver.findElement(By.name("iframe1-name"));//Switch to the framedriver.switchTo().frame(iframe);assertEquals(true,driver.getPageSource().contains("We Leave From Here"));WebElementemail=driver.findElement(By.id("email"));//Now we can type text into email fieldemail.sendKeys("admin@selenium.dev");email.clear();driver.switchTo().defaultContent();//switch To IFrame using indexdriver.switchTo().frame(0);assertEquals(true,driver.getPageSource().contains("We Leave From Here"));//leave framedriver.switchTo().defaultContent();assertEquals(true,driver.getPageSource().contains("This page has iframes"));//quit the browserdriver.quit();}}
# --- Switch to iframe using WebElement ---iframe=driver.find_element(By.ID,"iframe1")driver.switch_to.frame(iframe)assert"We Leave From Here"indriver.page_sourceemail_element=driver.find_element(By.ID,"email")email_element.send_keys("admin@selenium.dev")email_element.clear()driver.switch_to.default_content()
Show full example
# Licensed to the Software Freedom Conservancy (SFC) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information# regarding copyright ownership. The SFC licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0# Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied. See the License for the# specific language governing permissions and limitations# under the License.fromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy#set chrome and launch web pagedriver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/iframes.html")# --- Switch to iframe using WebElement ---iframe=driver.find_element(By.ID,"iframe1")driver.switch_to.frame(iframe)assert"We Leave From Here"indriver.page_sourceemail_element=driver.find_element(By.ID,"email")email_element.send_keys("admin@selenium.dev")email_element.clear()driver.switch_to.default_content()# --- Switch to iframe using name or ID ---iframe1=driver.find_element(By.NAME,"iframe1-name")# (This line doesn't switch, just locates)driver.switch_to.frame(iframe)assert"We Leave From Here"indriver.page_sourceemail=driver.find_element(By.ID,"email")email.send_keys("admin@selenium.dev")email.clear()driver.switch_to.default_content()# --- Switch to iframe using index ---driver.switch_to.frame(0)assert"We Leave From Here"indriver.page_source# --- Final page content check ---driver.switch_to.default_content()assert"This page has iframes"indriver.page_source#quit the driverdriver.quit()#demo code for conference
//switch To IFrame using Web ElementIWebElementiframe=driver.FindElement(By.Id("iframe1"));//Switch to the framedriver.SwitchTo().Frame(iframe);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));//Now we can type text into email fieldIWebElementemailE=driver.FindElement(By.Id("email"));emailE.SendKeys("admin@selenium.dev");emailE.Clear();
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{ [TestClass]publicclassFramesTest{ [TestMethod]publicvoidTestFrames(){WebDriverdriver=newChromeDriver();driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromMilliseconds(500);// Navigate to Urldriver.Url="https://www.selenium.dev/selenium/web/iframes.html";//switch To IFrame using Web ElementIWebElementiframe=driver.FindElement(By.Id("iframe1"));//Switch to the framedriver.SwitchTo().Frame(iframe);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));//Now we can type text into email fieldIWebElementemailE=driver.FindElement(By.Id("email"));emailE.SendKeys("admin@selenium.dev");emailE.Clear();driver.SwitchTo().DefaultContent();//switch To IFrame using name or iddriver.FindElement(By.Name("iframe1-name"));//Switch to the framedriver.SwitchTo().Frame(iframe);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));IWebElementemail=driver.FindElement(By.Id("email"));//Now we can type text into email fieldemail.SendKeys("admin@selenium.dev");email.Clear();driver.SwitchTo().DefaultContent();//switch To IFrame using indexdriver.SwitchTo().Frame(0);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));//leave framedriver.SwitchTo().DefaultContent();Assert.AreEqual(true,driver.PageSource.Contains("This page has iframes"));//quit the browserdriver.Quit();}}}
# Store iframe web elementiframe=driver.find_element(:css,'#modal> iframe')# 切换到 framedriver.switch_to.frameiframe# 单击按钮driver.find_element(:tag_name,'button').click
如果您的 frame 或 iframe 具有 id 或 name 属性,则可以使用该属性。如果名称或 id 在页面上不是唯一的,
那么将切换到找到的第一个。
//switch To IFrame using name or iddriver.findElement(By.name("iframe1-name"));//Switch to the framedriver.switchTo().frame(iframe);assertEquals(true,driver.getPageSource().contains("We Leave From Here"));WebElementemail=driver.findElement(By.id("email"));//Now we can type text into email fieldemail.sendKeys("admin@selenium.dev");email.clear();
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.packagedev.selenium.interactions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importjava.time.Duration;import staticorg.junit.jupiter.api.Assertions.assertEquals;publicclassFramesTest{@TestpublicvoidinformationWithElements(){WebDriverdriver=newChromeDriver();driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));// Navigate to Urldriver.get("https://www.selenium.dev/selenium/web/iframes.html");//switch To IFrame using Web ElementWebElementiframe=driver.findElement(By.id("iframe1"));//Switch to the framedriver.switchTo().frame(iframe);assertEquals(true,driver.getPageSource().contains("We Leave From Here"));//Now we can type text into email fieldWebElementemailE=driver.findElement(By.id("email"));emailE.sendKeys("admin@selenium.dev");emailE.clear();driver.switchTo().defaultContent();//switch To IFrame using name or iddriver.findElement(By.name("iframe1-name"));//Switch to the framedriver.switchTo().frame(iframe);assertEquals(true,driver.getPageSource().contains("We Leave From Here"));WebElementemail=driver.findElement(By.id("email"));//Now we can type text into email fieldemail.sendKeys("admin@selenium.dev");email.clear();driver.switchTo().defaultContent();//switch To IFrame using indexdriver.switchTo().frame(0);assertEquals(true,driver.getPageSource().contains("We Leave From Here"));//leave framedriver.switchTo().defaultContent();assertEquals(true,driver.getPageSource().contains("This page has iframes"));//quit the browserdriver.quit();}}
# --- Switch to iframe using name or ID ---iframe1=driver.find_element(By.NAME,"iframe1-name")# (This line doesn't switch, just locates)driver.switch_to.frame(iframe)assert"We Leave From Here"indriver.page_sourceemail=driver.find_element(By.ID,"email")email.send_keys("admin@selenium.dev")email.clear()driver.switch_to.default_content()
Show full example
# Licensed to the Software Freedom Conservancy (SFC) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information# regarding copyright ownership. The SFC licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0# Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied. See the License for the# specific language governing permissions and limitations# under the License.fromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy#set chrome and launch web pagedriver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/iframes.html")# --- Switch to iframe using WebElement ---iframe=driver.find_element(By.ID,"iframe1")driver.switch_to.frame(iframe)assert"We Leave From Here"indriver.page_sourceemail_element=driver.find_element(By.ID,"email")email_element.send_keys("admin@selenium.dev")email_element.clear()driver.switch_to.default_content()# --- Switch to iframe using name or ID ---iframe1=driver.find_element(By.NAME,"iframe1-name")# (This line doesn't switch, just locates)driver.switch_to.frame(iframe)assert"We Leave From Here"indriver.page_sourceemail=driver.find_element(By.ID,"email")email.send_keys("admin@selenium.dev")email.clear()driver.switch_to.default_content()# --- Switch to iframe using index ---driver.switch_to.frame(0)assert"We Leave From Here"indriver.page_source# --- Final page content check ---driver.switch_to.default_content()assert"This page has iframes"indriver.page_source#quit the driverdriver.quit()#demo code for conference
//switch To IFrame using name or iddriver.FindElement(By.Name("iframe1-name"));//Switch to the framedriver.SwitchTo().Frame(iframe);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));IWebElementemail=driver.FindElement(By.Id("email"));//Now we can type text into email fieldemail.SendKeys("admin@selenium.dev");email.Clear();
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{ [TestClass]publicclassFramesTest{ [TestMethod]publicvoidTestFrames(){WebDriverdriver=newChromeDriver();driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromMilliseconds(500);// Navigate to Urldriver.Url="https://www.selenium.dev/selenium/web/iframes.html";//switch To IFrame using Web ElementIWebElementiframe=driver.FindElement(By.Id("iframe1"));//Switch to the framedriver.SwitchTo().Frame(iframe);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));//Now we can type text into email fieldIWebElementemailE=driver.FindElement(By.Id("email"));emailE.SendKeys("admin@selenium.dev");emailE.Clear();driver.SwitchTo().DefaultContent();//switch To IFrame using name or iddriver.FindElement(By.Name("iframe1-name"));//Switch to the framedriver.SwitchTo().Frame(iframe);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));IWebElementemail=driver.FindElement(By.Id("email"));//Now we can type text into email fieldemail.SendKeys("admin@selenium.dev");email.Clear();driver.SwitchTo().DefaultContent();//switch To IFrame using indexdriver.SwitchTo().Frame(0);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));//leave framedriver.SwitchTo().DefaultContent();Assert.AreEqual(true,driver.PageSource.Contains("This page has iframes"));//quit the browserdriver.Quit();}}}
# Switch by IDdriver.switch_to.frame'buttonframe'# 单击按钮driver.find_element(:tag_name,'button').click
// 使用 ID
awaitdriver.switchTo().frame('buttonframe');// 或者使用 name 代替
awaitdriver.switchTo().frame('myframe');// 现在可以点击按钮
awaitdriver.findElement(By.css('button')).click();
// 使用 ID
driver.switchTo().frame("buttonframe")// 或者使用 name 代替
driver.switchTo().frame("myframe")// 现在可以点击按钮
driver.findElement(By.tagName("button")).click()
//switch To IFrame using indexdriver.switchTo().frame(0);
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.packagedev.selenium.interactions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importjava.time.Duration;import staticorg.junit.jupiter.api.Assertions.assertEquals;publicclassFramesTest{@TestpublicvoidinformationWithElements(){WebDriverdriver=newChromeDriver();driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));// Navigate to Urldriver.get("https://www.selenium.dev/selenium/web/iframes.html");//switch To IFrame using Web ElementWebElementiframe=driver.findElement(By.id("iframe1"));//Switch to the framedriver.switchTo().frame(iframe);assertEquals(true,driver.getPageSource().contains("We Leave From Here"));//Now we can type text into email fieldWebElementemailE=driver.findElement(By.id("email"));emailE.sendKeys("admin@selenium.dev");emailE.clear();driver.switchTo().defaultContent();//switch To IFrame using name or iddriver.findElement(By.name("iframe1-name"));//Switch to the framedriver.switchTo().frame(iframe);assertEquals(true,driver.getPageSource().contains("We Leave From Here"));WebElementemail=driver.findElement(By.id("email"));//Now we can type text into email fieldemail.sendKeys("admin@selenium.dev");email.clear();driver.switchTo().defaultContent();//switch To IFrame using indexdriver.switchTo().frame(0);assertEquals(true,driver.getPageSource().contains("We Leave From Here"));//leave framedriver.switchTo().defaultContent();assertEquals(true,driver.getPageSource().contains("This page has iframes"));//quit the browserdriver.quit();}}
driver.switch_to.frame(0)assert"We Leave From Here"indriver.page_source
Show full example
# Licensed to the Software Freedom Conservancy (SFC) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information# regarding copyright ownership. The SFC licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0# Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied. See the License for the# specific language governing permissions and limitations# under the License.fromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy#set chrome and launch web pagedriver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/iframes.html")# --- Switch to iframe using WebElement ---iframe=driver.find_element(By.ID,"iframe1")driver.switch_to.frame(iframe)assert"We Leave From Here"indriver.page_sourceemail_element=driver.find_element(By.ID,"email")email_element.send_keys("admin@selenium.dev")email_element.clear()driver.switch_to.default_content()# --- Switch to iframe using name or ID ---iframe1=driver.find_element(By.NAME,"iframe1-name")# (This line doesn't switch, just locates)driver.switch_to.frame(iframe)assert"We Leave From Here"indriver.page_sourceemail=driver.find_element(By.ID,"email")email.send_keys("admin@selenium.dev")email.clear()driver.switch_to.default_content()# --- Switch to iframe using index ---driver.switch_to.frame(0)assert"We Leave From Here"indriver.page_source# --- Final page content check ---driver.switch_to.default_content()assert"This page has iframes"indriver.page_source#quit the driverdriver.quit()#demo code for conference
//switch To IFrame using indexdriver.SwitchTo().Frame(0);
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{ [TestClass]publicclassFramesTest{ [TestMethod]publicvoidTestFrames(){WebDriverdriver=newChromeDriver();driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromMilliseconds(500);// Navigate to Urldriver.Url="https://www.selenium.dev/selenium/web/iframes.html";//switch To IFrame using Web ElementIWebElementiframe=driver.FindElement(By.Id("iframe1"));//Switch to the framedriver.SwitchTo().Frame(iframe);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));//Now we can type text into email fieldIWebElementemailE=driver.FindElement(By.Id("email"));emailE.SendKeys("admin@selenium.dev");emailE.Clear();driver.SwitchTo().DefaultContent();//switch To IFrame using name or iddriver.FindElement(By.Name("iframe1-name"));//Switch to the framedriver.SwitchTo().Frame(iframe);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));IWebElementemail=driver.FindElement(By.Id("email"));//Now we can type text into email fieldemail.SendKeys("admin@selenium.dev");email.Clear();driver.SwitchTo().DefaultContent();//switch To IFrame using indexdriver.SwitchTo().Frame(0);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));//leave framedriver.SwitchTo().DefaultContent();Assert.AreEqual(true,driver.PageSource.Contains("This page has iframes"));//quit the browserdriver.Quit();}}}
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.packagedev.selenium.interactions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importjava.time.Duration;import staticorg.junit.jupiter.api.Assertions.assertEquals;publicclassFramesTest{@TestpublicvoidinformationWithElements(){WebDriverdriver=newChromeDriver();driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));// Navigate to Urldriver.get("https://www.selenium.dev/selenium/web/iframes.html");//switch To IFrame using Web ElementWebElementiframe=driver.findElement(By.id("iframe1"));//Switch to the framedriver.switchTo().frame(iframe);assertEquals(true,driver.getPageSource().contains("We Leave From Here"));//Now we can type text into email fieldWebElementemailE=driver.findElement(By.id("email"));emailE.sendKeys("admin@selenium.dev");emailE.clear();driver.switchTo().defaultContent();//switch To IFrame using name or iddriver.findElement(By.name("iframe1-name"));//Switch to the framedriver.switchTo().frame(iframe);assertEquals(true,driver.getPageSource().contains("We Leave From Here"));WebElementemail=driver.findElement(By.id("email"));//Now we can type text into email fieldemail.sendKeys("admin@selenium.dev");email.clear();driver.switchTo().defaultContent();//switch To IFrame using indexdriver.switchTo().frame(0);assertEquals(true,driver.getPageSource().contains("We Leave From Here"));//leave framedriver.switchTo().defaultContent();assertEquals(true,driver.getPageSource().contains("This page has iframes"));//quit the browserdriver.quit();}}
driver.switch_to.default_content()assert"This page has iframes"indriver.page_source
Show full example
# Licensed to the Software Freedom Conservancy (SFC) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information# regarding copyright ownership. The SFC licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0# Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied. See the License for the# specific language governing permissions and limitations# under the License.fromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy#set chrome and launch web pagedriver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/iframes.html")# --- Switch to iframe using WebElement ---iframe=driver.find_element(By.ID,"iframe1")driver.switch_to.frame(iframe)assert"We Leave From Here"indriver.page_sourceemail_element=driver.find_element(By.ID,"email")email_element.send_keys("admin@selenium.dev")email_element.clear()driver.switch_to.default_content()# --- Switch to iframe using name or ID ---iframe1=driver.find_element(By.NAME,"iframe1-name")# (This line doesn't switch, just locates)driver.switch_to.frame(iframe)assert"We Leave From Here"indriver.page_sourceemail=driver.find_element(By.ID,"email")email.send_keys("admin@selenium.dev")email.clear()driver.switch_to.default_content()# --- Switch to iframe using index ---driver.switch_to.frame(0)assert"We Leave From Here"indriver.page_source# --- Final page content check ---driver.switch_to.default_content()assert"This page has iframes"indriver.page_source#quit the driverdriver.quit()#demo code for conference
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{ [TestClass]publicclassFramesTest{ [TestMethod]publicvoidTestFrames(){WebDriverdriver=newChromeDriver();driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromMilliseconds(500);// Navigate to Urldriver.Url="https://www.selenium.dev/selenium/web/iframes.html";//switch To IFrame using Web ElementIWebElementiframe=driver.FindElement(By.Id("iframe1"));//Switch to the framedriver.SwitchTo().Frame(iframe);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));//Now we can type text into email fieldIWebElementemailE=driver.FindElement(By.Id("email"));emailE.SendKeys("admin@selenium.dev");emailE.Clear();driver.SwitchTo().DefaultContent();//switch To IFrame using name or iddriver.FindElement(By.Name("iframe1-name"));//Switch to the framedriver.SwitchTo().Frame(iframe);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));IWebElementemail=driver.FindElement(By.Id("email"));//Now we can type text into email fieldemail.SendKeys("admin@selenium.dev");email.Clear();driver.SwitchTo().DefaultContent();//switch To IFrame using indexdriver.SwitchTo().Frame(0);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));//leave framedriver.SwitchTo().DefaultContent();Assert.AreEqual(true,driver.PageSource.Contains("This page has iframes"));//quit the browserdriver.Quit();}}}
packagedev.selenium.interactions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.print.PageMargin;importorg.openqa.selenium.print.PrintOptions;importorg.openqa.selenium.print.PageSize;importdev.selenium.BaseChromeTest;publicclassPrintOptionsTestextendsBaseChromeTest{@TestpublicvoidTestOrientation(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setOrientation(PrintOptions.Orientation.LANDSCAPE);PrintOptions.Orientationcurrent_orientation=printOptions.getOrientation();}@TestpublicvoidTestRange(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setPageRanges("1-2");String[]current_range=printOptions.getPageRanges();}@TestpublicvoidTestSize(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setPageSize(newPageSize(27.94,21.59));// A4 size in cmdoublecurrentHeight=printOptions.getPageSize().getHeight();// use getWidth() to retrieve width}@TestpublicvoidTestMargins(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();PageMarginmargins=newPageMargin(1.0,1.0,1.0,1.0);printOptions.setPageMargin(margins);doubletopMargin=margins.getTop();doublebottomMargin=margins.getBottom();doubleleftMargin=margins.getLeft();doublerightMargin=margins.getRight();}@TestpublicvoidTestScale(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setScale(.50);doublecurrent_scale=printOptions.getScale();}@TestpublicvoidTestBackground(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setBackground(true);booleancurrent_background=printOptions.getBackground();}@TestpublicvoidTestShrinkToFit(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setShrinkToFit(true);booleancurrent_shrink_to_fit=printOptions.getShrinkToFit();}}
driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.orientation="landscape"## landscape or portrait
Show full example
importpytestfromseleniumimportwebdriverfromselenium.webdriver.common.print_page_optionsimportPrintOptions@pytest.fixture()defdriver():driver=webdriver.Chrome()yielddriverdriver.quit()deftest_orientation(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.orientation="landscape"## landscape or portraitassertprint_options.orientation=="landscape"deftest_range(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.page_ranges=["1, 2, 3"]## ["1", "2", "3"] or ["1-3"]assertprint_options.page_ranges==["1, 2, 3"]deftest_size(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.page_height=27.94# Use page_width to assign widthassertprint_options.page_height==27.94deftest_margin(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.margin_top=10print_options.margin_bottom=10print_options.margin_left=10print_options.margin_right=10assertprint_options.margin_top==10assertprint_options.margin_bottom==10assertprint_options.margin_left==10assertprint_options.margin_right==10deftest_scale(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.scale=0.5## 0.1 to 2.0current_scale=print_options.scaleassertcurrent_scale==0.5deftest_background(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.background=True## True or Falseassertprint_options.backgroundisTruedeftest_shrink_to_fit(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.shrink_to_fit=True## True or Falseassertprint_options.shrink_to_fitisTrue
packagedev.selenium.interactions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.print.PageMargin;importorg.openqa.selenium.print.PrintOptions;importorg.openqa.selenium.print.PageSize;importdev.selenium.BaseChromeTest;publicclassPrintOptionsTestextendsBaseChromeTest{@TestpublicvoidTestOrientation(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setOrientation(PrintOptions.Orientation.LANDSCAPE);PrintOptions.Orientationcurrent_orientation=printOptions.getOrientation();}@TestpublicvoidTestRange(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setPageRanges("1-2");String[]current_range=printOptions.getPageRanges();}@TestpublicvoidTestSize(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setPageSize(newPageSize(27.94,21.59));// A4 size in cmdoublecurrentHeight=printOptions.getPageSize().getHeight();// use getWidth() to retrieve width}@TestpublicvoidTestMargins(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();PageMarginmargins=newPageMargin(1.0,1.0,1.0,1.0);printOptions.setPageMargin(margins);doubletopMargin=margins.getTop();doublebottomMargin=margins.getBottom();doubleleftMargin=margins.getLeft();doublerightMargin=margins.getRight();}@TestpublicvoidTestScale(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setScale(.50);doublecurrent_scale=printOptions.getScale();}@TestpublicvoidTestBackground(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setBackground(true);booleancurrent_background=printOptions.getBackground();}@TestpublicvoidTestShrinkToFit(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setShrinkToFit(true);booleancurrent_shrink_to_fit=printOptions.getShrinkToFit();}}
publicvoidTestRange(){IWebDriverdriver=newChromeDriver();driver.Navigate().GoToUrl("https://selenium.dev");PrintOptionsprintOptions=newPrintOptions();printOptions.AddPageRangeToPrint("1-3");// add range of pagesprintOptions.AddPageToPrint(5);// add individual page}
Show full example
usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocumentation.SeleniumInteractions{ [TestClass]publicclassPrintOptionsTest{ [TestMethod]publicvoidTestOrientation(){IWebDriverdriver=newChromeDriver();driver.Navigate().GoToUrl("https://selenium.dev");PrintOptionsprintOptions=newPrintOptions();printOptions.Orientation=PrintOrientation.Landscape;PrintOrientationcurrentOrientation=printOptions.Orientation;} [TestMethod]publicvoidTestRange(){IWebDriverdriver=newChromeDriver();driver.Navigate().GoToUrl("https://selenium.dev");PrintOptionsprintOptions=newPrintOptions();printOptions.AddPageRangeToPrint("1-3");// add range of pagesprintOptions.AddPageToPrint(5);// add individual page} [TestMethod]publicvoidTestSize(){IWebDriverdriver=newChromeDriver();driver.Navigate().GoToUrl("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();PrintOptions.PageSizecurrentDimensions=printOptions.PageDimensions;} [TestMethod]publicvoidTestBackgrounds(){IWebDriverdriver=newChromeDriver();driver.Navigate().GoToUrl("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.OutputBackgroundImages=true;boolcurrentBackgrounds=printOptions.OutputBackgroundImages;} [TestMethod]publicvoidTestMargins(){IWebDriverdriver=newChromeDriver();driver.Navigate().GoToUrl("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();PrintOptions.MarginscurrentMargins=printOptions.PageMargins;} [TestMethod]publicvoidTestScale(){IWebDriverdriver=newChromeDriver();driver.Navigate().GoToUrl("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.ScaleFactor=0.5;doublecurrentScale=printOptions.ScaleFactor;} [TestMethod]publicvoidTestShrinkToFit(){IWebDriverdriver=newChromeDriver();driver.Navigate().GoToUrl("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.ShrinkToFit=true;boolcurrentShrinkToFit=printOptions.ShrinkToFit;} [TestMethod]publicvoidPrintWithPrintsPageTest(){WebDriverdriver=newChromeDriver();driver.Navigate().GoToUrl("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();PrintDocumentprintedPage=driver.Print(printOptions);Assert.IsTrue(printedPage.AsBase64EncodedString.StartsWith("JVBER"));}}}
driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.page_ranges=["1, 2, 3"]## ["1", "2", "3"] or ["1-3"]
Show full example
importpytestfromseleniumimportwebdriverfromselenium.webdriver.common.print_page_optionsimportPrintOptions@pytest.fixture()defdriver():driver=webdriver.Chrome()yielddriverdriver.quit()deftest_orientation(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.orientation="landscape"## landscape or portraitassertprint_options.orientation=="landscape"deftest_range(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.page_ranges=["1, 2, 3"]## ["1", "2", "3"] or ["1-3"]assertprint_options.page_ranges==["1, 2, 3"]deftest_size(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.page_height=27.94# Use page_width to assign widthassertprint_options.page_height==27.94deftest_margin(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.margin_top=10print_options.margin_bottom=10print_options.margin_left=10print_options.margin_right=10assertprint_options.margin_top==10assertprint_options.margin_bottom==10assertprint_options.margin_left==10assertprint_options.margin_right==10deftest_scale(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.scale=0.5## 0.1 to 2.0current_scale=print_options.scaleassertcurrent_scale==0.5deftest_background(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.background=True## True or Falseassertprint_options.backgroundisTruedeftest_shrink_to_fit(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.shrink_to_fit=True## True or Falseassertprint_options.shrink_to_fitisTrue
driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setPageSize(newPageSize(27.94,21.59));// A4 size in cmdoublecurrentHeight=printOptions.getPageSize().getHeight();//usegetWidth()toretrievewidth
Show full example
packagedev.selenium.interactions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.print.PageMargin;importorg.openqa.selenium.print.PrintOptions;importorg.openqa.selenium.print.PageSize;importdev.selenium.BaseChromeTest;publicclassPrintOptionsTestextendsBaseChromeTest{@TestpublicvoidTestOrientation(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setOrientation(PrintOptions.Orientation.LANDSCAPE);PrintOptions.Orientationcurrent_orientation=printOptions.getOrientation();}@TestpublicvoidTestRange(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setPageRanges("1-2");String[]current_range=printOptions.getPageRanges();}@TestpublicvoidTestSize(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setPageSize(newPageSize(27.94,21.59));// A4 size in cmdoublecurrentHeight=printOptions.getPageSize().getHeight();// use getWidth() to retrieve width}@TestpublicvoidTestMargins(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();PageMarginmargins=newPageMargin(1.0,1.0,1.0,1.0);printOptions.setPageMargin(margins);doubletopMargin=margins.getTop();doublebottomMargin=margins.getBottom();doubleleftMargin=margins.getLeft();doublerightMargin=margins.getRight();}@TestpublicvoidTestScale(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setScale(.50);doublecurrent_scale=printOptions.getScale();}@TestpublicvoidTestBackground(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setBackground(true);booleancurrent_background=printOptions.getBackground();}@TestpublicvoidTestShrinkToFit(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setShrinkToFit(true);booleancurrent_shrink_to_fit=printOptions.getShrinkToFit();}}
driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.page_height=27.94# Use page_width to assign width
Show full example
importpytestfromseleniumimportwebdriverfromselenium.webdriver.common.print_page_optionsimportPrintOptions@pytest.fixture()defdriver():driver=webdriver.Chrome()yielddriverdriver.quit()deftest_orientation(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.orientation="landscape"## landscape or portraitassertprint_options.orientation=="landscape"deftest_range(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.page_ranges=["1, 2, 3"]## ["1", "2", "3"] or ["1-3"]assertprint_options.page_ranges==["1, 2, 3"]deftest_size(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.page_height=27.94# Use page_width to assign widthassertprint_options.page_height==27.94deftest_margin(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.margin_top=10print_options.margin_bottom=10print_options.margin_left=10print_options.margin_right=10assertprint_options.margin_top==10assertprint_options.margin_bottom==10assertprint_options.margin_left==10assertprint_options.margin_right==10deftest_scale(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.scale=0.5## 0.1 to 2.0current_scale=print_options.scaleassertcurrent_scale==0.5deftest_background(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.background=True## True or Falseassertprint_options.backgroundisTruedeftest_shrink_to_fit(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.shrink_to_fit=True## True or Falseassertprint_options.shrink_to_fitisTrue
packagedev.selenium.interactions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.print.PageMargin;importorg.openqa.selenium.print.PrintOptions;importorg.openqa.selenium.print.PageSize;importdev.selenium.BaseChromeTest;publicclassPrintOptionsTestextendsBaseChromeTest{@TestpublicvoidTestOrientation(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setOrientation(PrintOptions.Orientation.LANDSCAPE);PrintOptions.Orientationcurrent_orientation=printOptions.getOrientation();}@TestpublicvoidTestRange(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setPageRanges("1-2");String[]current_range=printOptions.getPageRanges();}@TestpublicvoidTestSize(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setPageSize(newPageSize(27.94,21.59));// A4 size in cmdoublecurrentHeight=printOptions.getPageSize().getHeight();// use getWidth() to retrieve width}@TestpublicvoidTestMargins(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();PageMarginmargins=newPageMargin(1.0,1.0,1.0,1.0);printOptions.setPageMargin(margins);doubletopMargin=margins.getTop();doublebottomMargin=margins.getBottom();doubleleftMargin=margins.getLeft();doublerightMargin=margins.getRight();}@TestpublicvoidTestScale(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setScale(.50);doublecurrent_scale=printOptions.getScale();}@TestpublicvoidTestBackground(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setBackground(true);booleancurrent_background=printOptions.getBackground();}@TestpublicvoidTestShrinkToFit(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setShrinkToFit(true);booleancurrent_shrink_to_fit=printOptions.getShrinkToFit();}}
importpytestfromseleniumimportwebdriverfromselenium.webdriver.common.print_page_optionsimportPrintOptions@pytest.fixture()defdriver():driver=webdriver.Chrome()yielddriverdriver.quit()deftest_orientation(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.orientation="landscape"## landscape or portraitassertprint_options.orientation=="landscape"deftest_range(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.page_ranges=["1, 2, 3"]## ["1", "2", "3"] or ["1-3"]assertprint_options.page_ranges==["1, 2, 3"]deftest_size(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.page_height=27.94# Use page_width to assign widthassertprint_options.page_height==27.94deftest_margin(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.margin_top=10print_options.margin_bottom=10print_options.margin_left=10print_options.margin_right=10assertprint_options.margin_top==10assertprint_options.margin_bottom==10assertprint_options.margin_left==10assertprint_options.margin_right==10deftest_scale(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.scale=0.5## 0.1 to 2.0current_scale=print_options.scaleassertcurrent_scale==0.5deftest_background(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.background=True## True or Falseassertprint_options.backgroundisTruedeftest_shrink_to_fit(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.shrink_to_fit=True## True or Falseassertprint_options.shrink_to_fitisTrue
packagedev.selenium.interactions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.print.PageMargin;importorg.openqa.selenium.print.PrintOptions;importorg.openqa.selenium.print.PageSize;importdev.selenium.BaseChromeTest;publicclassPrintOptionsTestextendsBaseChromeTest{@TestpublicvoidTestOrientation(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setOrientation(PrintOptions.Orientation.LANDSCAPE);PrintOptions.Orientationcurrent_orientation=printOptions.getOrientation();}@TestpublicvoidTestRange(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setPageRanges("1-2");String[]current_range=printOptions.getPageRanges();}@TestpublicvoidTestSize(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setPageSize(newPageSize(27.94,21.59));// A4 size in cmdoublecurrentHeight=printOptions.getPageSize().getHeight();// use getWidth() to retrieve width}@TestpublicvoidTestMargins(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();PageMarginmargins=newPageMargin(1.0,1.0,1.0,1.0);printOptions.setPageMargin(margins);doubletopMargin=margins.getTop();doublebottomMargin=margins.getBottom();doubleleftMargin=margins.getLeft();doublerightMargin=margins.getRight();}@TestpublicvoidTestScale(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setScale(.50);doublecurrent_scale=printOptions.getScale();}@TestpublicvoidTestBackground(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setBackground(true);booleancurrent_background=printOptions.getBackground();}@TestpublicvoidTestShrinkToFit(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setShrinkToFit(true);booleancurrent_shrink_to_fit=printOptions.getShrinkToFit();}}
driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.scale=0.5## 0.1 to 2.0current_scale=print_options.scale
Show full example
importpytestfromseleniumimportwebdriverfromselenium.webdriver.common.print_page_optionsimportPrintOptions@pytest.fixture()defdriver():driver=webdriver.Chrome()yielddriverdriver.quit()deftest_orientation(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.orientation="landscape"## landscape or portraitassertprint_options.orientation=="landscape"deftest_range(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.page_ranges=["1, 2, 3"]## ["1", "2", "3"] or ["1-3"]assertprint_options.page_ranges==["1, 2, 3"]deftest_size(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.page_height=27.94# Use page_width to assign widthassertprint_options.page_height==27.94deftest_margin(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.margin_top=10print_options.margin_bottom=10print_options.margin_left=10print_options.margin_right=10assertprint_options.margin_top==10assertprint_options.margin_bottom==10assertprint_options.margin_left==10assertprint_options.margin_right==10deftest_scale(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.scale=0.5## 0.1 to 2.0current_scale=print_options.scaleassertcurrent_scale==0.5deftest_background(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.background=True## True or Falseassertprint_options.backgroundisTruedeftest_shrink_to_fit(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.shrink_to_fit=True## True or Falseassertprint_options.shrink_to_fitisTrue
packagedev.selenium.interactions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.print.PageMargin;importorg.openqa.selenium.print.PrintOptions;importorg.openqa.selenium.print.PageSize;importdev.selenium.BaseChromeTest;publicclassPrintOptionsTestextendsBaseChromeTest{@TestpublicvoidTestOrientation(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setOrientation(PrintOptions.Orientation.LANDSCAPE);PrintOptions.Orientationcurrent_orientation=printOptions.getOrientation();}@TestpublicvoidTestRange(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setPageRanges("1-2");String[]current_range=printOptions.getPageRanges();}@TestpublicvoidTestSize(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setPageSize(newPageSize(27.94,21.59));// A4 size in cmdoublecurrentHeight=printOptions.getPageSize().getHeight();// use getWidth() to retrieve width}@TestpublicvoidTestMargins(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();PageMarginmargins=newPageMargin(1.0,1.0,1.0,1.0);printOptions.setPageMargin(margins);doubletopMargin=margins.getTop();doublebottomMargin=margins.getBottom();doubleleftMargin=margins.getLeft();doublerightMargin=margins.getRight();}@TestpublicvoidTestScale(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setScale(.50);doublecurrent_scale=printOptions.getScale();}@TestpublicvoidTestBackground(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setBackground(true);booleancurrent_background=printOptions.getBackground();}@TestpublicvoidTestShrinkToFit(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setShrinkToFit(true);booleancurrent_shrink_to_fit=printOptions.getShrinkToFit();}}
driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.background=True## True or False
Show full example
importpytestfromseleniumimportwebdriverfromselenium.webdriver.common.print_page_optionsimportPrintOptions@pytest.fixture()defdriver():driver=webdriver.Chrome()yielddriverdriver.quit()deftest_orientation(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.orientation="landscape"## landscape or portraitassertprint_options.orientation=="landscape"deftest_range(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.page_ranges=["1, 2, 3"]## ["1", "2", "3"] or ["1-3"]assertprint_options.page_ranges==["1, 2, 3"]deftest_size(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.page_height=27.94# Use page_width to assign widthassertprint_options.page_height==27.94deftest_margin(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.margin_top=10print_options.margin_bottom=10print_options.margin_left=10print_options.margin_right=10assertprint_options.margin_top==10assertprint_options.margin_bottom==10assertprint_options.margin_left==10assertprint_options.margin_right==10deftest_scale(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.scale=0.5## 0.1 to 2.0current_scale=print_options.scaleassertcurrent_scale==0.5deftest_background(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.background=True## True or Falseassertprint_options.backgroundisTruedeftest_shrink_to_fit(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.shrink_to_fit=True## True or Falseassertprint_options.shrink_to_fitisTrue
packagedev.selenium.interactions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.print.PageMargin;importorg.openqa.selenium.print.PrintOptions;importorg.openqa.selenium.print.PageSize;importdev.selenium.BaseChromeTest;publicclassPrintOptionsTestextendsBaseChromeTest{@TestpublicvoidTestOrientation(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setOrientation(PrintOptions.Orientation.LANDSCAPE);PrintOptions.Orientationcurrent_orientation=printOptions.getOrientation();}@TestpublicvoidTestRange(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setPageRanges("1-2");String[]current_range=printOptions.getPageRanges();}@TestpublicvoidTestSize(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setPageSize(newPageSize(27.94,21.59));// A4 size in cmdoublecurrentHeight=printOptions.getPageSize().getHeight();// use getWidth() to retrieve width}@TestpublicvoidTestMargins(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();PageMarginmargins=newPageMargin(1.0,1.0,1.0,1.0);printOptions.setPageMargin(margins);doubletopMargin=margins.getTop();doublebottomMargin=margins.getBottom();doubleleftMargin=margins.getLeft();doublerightMargin=margins.getRight();}@TestpublicvoidTestScale(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setScale(.50);doublecurrent_scale=printOptions.getScale();}@TestpublicvoidTestBackground(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setBackground(true);booleancurrent_background=printOptions.getBackground();}@TestpublicvoidTestShrinkToFit(){driver.get("https://www.selenium.dev/");PrintOptionsprintOptions=newPrintOptions();printOptions.setShrinkToFit(true);booleancurrent_shrink_to_fit=printOptions.getShrinkToFit();}}
driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.shrink_to_fit=True## True or False
Show full example
importpytestfromseleniumimportwebdriverfromselenium.webdriver.common.print_page_optionsimportPrintOptions@pytest.fixture()defdriver():driver=webdriver.Chrome()yielddriverdriver.quit()deftest_orientation(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.orientation="landscape"## landscape or portraitassertprint_options.orientation=="landscape"deftest_range(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.page_ranges=["1, 2, 3"]## ["1", "2", "3"] or ["1-3"]assertprint_options.page_ranges==["1, 2, 3"]deftest_size(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.page_height=27.94# Use page_width to assign widthassertprint_options.page_height==27.94deftest_margin(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.margin_top=10print_options.margin_bottom=10print_options.margin_left=10print_options.margin_right=10assertprint_options.margin_top==10assertprint_options.margin_bottom==10assertprint_options.margin_left==10assertprint_options.margin_right==10deftest_scale(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.scale=0.5## 0.1 to 2.0current_scale=print_options.scaleassertcurrent_scale==0.5deftest_background(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.background=True## True or Falseassertprint_options.backgroundisTruedeftest_shrink_to_fit(driver):driver.get("https://www.selenium.dev/")print_options=PrintOptions()print_options.shrink_to_fit=True## True or Falseassertprint_options.shrink_to_fitisTrue
配置好打印选项后,就可以打印页面了。为此,您可以调用打印功能,生成网页的 PDF 表示形式。
生成的 PDF 文件可以保存到本地存储器中,以便进一步使用或分发。
使用 PrintsPage() 时,打印命令将以 base64 编码格式返回 PDF
数据,该格式可以解码并写入所需位置的文件,而使用 BrowsingContext() 时将返回字符串。
// Navigate to Urldriver.get("https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html");//fetch handle of thisStringcurrHandle=driver.getWindowHandle();assertNotNull(currHandle);
Show full example
packagedev.selenium.interactions;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importjava.time.Duration;importorg.junit.jupiter.api.Test;import staticorg.junit.jupiter.api.Assertions.*;publicclassWindowsTest{@TestpublicvoidwindowsExampleCode(){WebDriverdriver=newChromeDriver();driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));// Navigate to Urldriver.get("https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html");//fetch handle of thisStringcurrHandle=driver.getWindowHandle();assertNotNull(currHandle);//click on link to open a new windowdriver.findElement(By.linkText("Open new window")).click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowObject[]windowHandles=driver.getWindowHandles().toArray();driver.switchTo().window((String)windowHandles[1]);//assert on title of new windowStringtitle=driver.getTitle();assertEquals("Simple Page",title);//closing current windowdriver.close();//Switch back to the old tab or windowdriver.switchTo().window((String)windowHandles[0]);//Opens a new tab and switches to new tabdriver.switchTo().newWindow(WindowType.TAB);assertEquals("",driver.getTitle());//Opens a new window and switches to new windowdriver.switchTo().newWindow(WindowType.WINDOW);assertEquals("",driver.getTitle());//quitting driverdriver.quit();//close all windows}}
// Navigate to Urldriver.Url="https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html";//fetch handle of thisStringcurrHandle=driver.CurrentWindowHandle;Assert.IsNotNull(currHandle);
Show full example
usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{ [TestClass]publicclassWindowsTest{ [TestMethod]publicvoidTestWindowCommands(){WebDriverdriver=newChromeDriver();driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromMilliseconds(500);// Navigate to Urldriver.Url="https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html";//fetch handle of thisStringcurrHandle=driver.CurrentWindowHandle;Assert.IsNotNull(currHandle);//click on link to open a new windowdriver.FindElement(By.LinkText("Open new window")).Click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowIList<string>windowHandles=newList<string>(driver.WindowHandles);driver.SwitchTo().Window(windowHandles[1]);//assert on title of new windowStringtitle=driver.Title;Assert.AreEqual("Simple Page",title);//closing current windowdriver.Close();//Switch back to the old tab or windowdriver.SwitchTo().Window(windowHandles[0]);//Opens a new tab and switches to new tabdriver.SwitchTo().NewWindow(WindowType.Tab);Assert.AreEqual("",driver.Title);//Opens a new window and switches to new windowdriver.SwitchTo().NewWindow(WindowType.Window);Assert.AreEqual("",driver.Title);//quitting driverdriver.Quit();//close all windows}}}
不过,Selenium 4 提供了一个新的 api NewWindow
它创建一个新选项卡 (或) 新窗口并自动切换到它。
//click on link to open a new windowdriver.findElement(By.linkText("Open new window")).click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowObject[]windowHandles=driver.getWindowHandles().toArray();driver.switchTo().window((String)windowHandles[1]);//assert on title of new windowStringtitle=driver.getTitle();assertEquals("Simple Page",title);
Show full example
packagedev.selenium.interactions;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importjava.time.Duration;importorg.junit.jupiter.api.Test;import staticorg.junit.jupiter.api.Assertions.*;publicclassWindowsTest{@TestpublicvoidwindowsExampleCode(){WebDriverdriver=newChromeDriver();driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));// Navigate to Urldriver.get("https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html");//fetch handle of thisStringcurrHandle=driver.getWindowHandle();assertNotNull(currHandle);//click on link to open a new windowdriver.findElement(By.linkText("Open new window")).click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowObject[]windowHandles=driver.getWindowHandles().toArray();driver.switchTo().window((String)windowHandles[1]);//assert on title of new windowStringtitle=driver.getTitle();assertEquals("Simple Page",title);//closing current windowdriver.close();//Switch back to the old tab or windowdriver.switchTo().window((String)windowHandles[0]);//Opens a new tab and switches to new tabdriver.switchTo().newWindow(WindowType.TAB);assertEquals("",driver.getTitle());//Opens a new window and switches to new windowdriver.switchTo().newWindow(WindowType.WINDOW);assertEquals("",driver.getTitle());//quitting driverdriver.quit();//close all windows}}
//click on link to open a new windowdriver.FindElement(By.LinkText("Open new window")).Click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowIList<string>windowHandles=newList<string>(driver.WindowHandles);driver.SwitchTo().Window(windowHandles[1]);//assert on title of new windowStringtitle=driver.Title;Assert.AreEqual("Simple Page",title);
Show full example
usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{ [TestClass]publicclassWindowsTest{ [TestMethod]publicvoidTestWindowCommands(){WebDriverdriver=newChromeDriver();driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromMilliseconds(500);// Navigate to Urldriver.Url="https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html";//fetch handle of thisStringcurrHandle=driver.CurrentWindowHandle;Assert.IsNotNull(currHandle);//click on link to open a new windowdriver.FindElement(By.LinkText("Open new window")).Click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowIList<string>windowHandles=newList<string>(driver.WindowHandles);driver.SwitchTo().Window(windowHandles[1]);//assert on title of new windowStringtitle=driver.Title;Assert.AreEqual("Simple Page",title);//closing current windowdriver.Close();//Switch back to the old tab or windowdriver.SwitchTo().Window(windowHandles[0]);//Opens a new tab and switches to new tabdriver.SwitchTo().NewWindow(WindowType.Tab);Assert.AreEqual("",driver.Title);//Opens a new window and switches to new windowdriver.SwitchTo().NewWindow(WindowType.Window);Assert.AreEqual("",driver.Title);//quitting driverdriver.Quit();//close all windows}}}
//closing current windowdriver.close();//Switch back to the old tab or windowdriver.switchTo().window((String)windowHandles[0]);
Show full example
packagedev.selenium.interactions;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importjava.time.Duration;importorg.junit.jupiter.api.Test;import staticorg.junit.jupiter.api.Assertions.*;publicclassWindowsTest{@TestpublicvoidwindowsExampleCode(){WebDriverdriver=newChromeDriver();driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));// Navigate to Urldriver.get("https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html");//fetch handle of thisStringcurrHandle=driver.getWindowHandle();assertNotNull(currHandle);//click on link to open a new windowdriver.findElement(By.linkText("Open new window")).click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowObject[]windowHandles=driver.getWindowHandles().toArray();driver.switchTo().window((String)windowHandles[1]);//assert on title of new windowStringtitle=driver.getTitle();assertEquals("Simple Page",title);//closing current windowdriver.close();//Switch back to the old tab or windowdriver.switchTo().window((String)windowHandles[0]);//Opens a new tab and switches to new tabdriver.switchTo().newWindow(WindowType.TAB);assertEquals("",driver.getTitle());//Opens a new window and switches to new windowdriver.switchTo().newWindow(WindowType.WINDOW);assertEquals("",driver.getTitle());//quitting driverdriver.quit();//close all windows}}
//closing current windowdriver.Close();//Switch back to the old tab or windowdriver.SwitchTo().Window(windowHandles[0]);
Show full example
usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{ [TestClass]publicclassWindowsTest{ [TestMethod]publicvoidTestWindowCommands(){WebDriverdriver=newChromeDriver();driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromMilliseconds(500);// Navigate to Urldriver.Url="https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html";//fetch handle of thisStringcurrHandle=driver.CurrentWindowHandle;Assert.IsNotNull(currHandle);//click on link to open a new windowdriver.FindElement(By.LinkText("Open new window")).Click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowIList<string>windowHandles=newList<string>(driver.WindowHandles);driver.SwitchTo().Window(windowHandles[1]);//assert on title of new windowStringtitle=driver.Title;Assert.AreEqual("Simple Page",title);//closing current windowdriver.Close();//Switch back to the old tab or windowdriver.SwitchTo().Window(windowHandles[0]);//Opens a new tab and switches to new tabdriver.SwitchTo().NewWindow(WindowType.Tab);Assert.AreEqual("",driver.Title);//Opens a new window and switches to new windowdriver.SwitchTo().NewWindow(WindowType.Window);Assert.AreEqual("",driver.Title);//quitting driverdriver.Quit();//close all windows}}}
//Opens a new tab and switches to new tabdriver.switchTo().newWindow(WindowType.TAB);assertEquals("",driver.getTitle());//Opens a new window and switches to new windowdriver.switchTo().newWindow(WindowType.WINDOW);assertEquals("",driver.getTitle());
Show full example
packagedev.selenium.interactions;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importjava.time.Duration;importorg.junit.jupiter.api.Test;import staticorg.junit.jupiter.api.Assertions.*;publicclassWindowsTest{@TestpublicvoidwindowsExampleCode(){WebDriverdriver=newChromeDriver();driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));// Navigate to Urldriver.get("https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html");//fetch handle of thisStringcurrHandle=driver.getWindowHandle();assertNotNull(currHandle);//click on link to open a new windowdriver.findElement(By.linkText("Open new window")).click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowObject[]windowHandles=driver.getWindowHandles().toArray();driver.switchTo().window((String)windowHandles[1]);//assert on title of new windowStringtitle=driver.getTitle();assertEquals("Simple Page",title);//closing current windowdriver.close();//Switch back to the old tab or windowdriver.switchTo().window((String)windowHandles[0]);//Opens a new tab and switches to new tabdriver.switchTo().newWindow(WindowType.TAB);assertEquals("",driver.getTitle());//Opens a new window and switches to new windowdriver.switchTo().newWindow(WindowType.WINDOW);assertEquals("",driver.getTitle());//quitting driverdriver.quit();//close all windows}}
//Opens a new tab and switches to new tabdriver.SwitchTo().NewWindow(WindowType.Tab);Assert.AreEqual("",driver.Title);//Opens a new window and switches to new windowdriver.SwitchTo().NewWindow(WindowType.Window);Assert.AreEqual("",driver.Title);
Show full example
usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{ [TestClass]publicclassWindowsTest{ [TestMethod]publicvoidTestWindowCommands(){WebDriverdriver=newChromeDriver();driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromMilliseconds(500);// Navigate to Urldriver.Url="https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html";//fetch handle of thisStringcurrHandle=driver.CurrentWindowHandle;Assert.IsNotNull(currHandle);//click on link to open a new windowdriver.FindElement(By.LinkText("Open new window")).Click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowIList<string>windowHandles=newList<string>(driver.WindowHandles);driver.SwitchTo().Window(windowHandles[1]);//assert on title of new windowStringtitle=driver.Title;Assert.AreEqual("Simple Page",title);//closing current windowdriver.Close();//Switch back to the old tab or windowdriver.SwitchTo().Window(windowHandles[0]);//Opens a new tab and switches to new tabdriver.SwitchTo().NewWindow(WindowType.Tab);Assert.AreEqual("",driver.Title);//Opens a new window and switches to new windowdriver.SwitchTo().NewWindow(WindowType.Window);Assert.AreEqual("",driver.Title);//quitting driverdriver.Quit();//close all windows}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Windows'dolet(:driver){start_session}it'opens new tab'dodriver.switch_to.new_window(:tab)expect(driver.window_handles.size).toeq2endit'opens new window'dodriver.switch_to.new_window(:window)expect(driver.window_handles.size).toeq2endend
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Windows'dolet(:driver){start_session}it'opens new tab'dodriver.switch_to.new_window(:tab)expect(driver.window_handles.size).toeq2endit'opens new window'dodriver.switch_to.new_window(:window)expect(driver.window_handles.size).toeq2endend
const{Builder,By}=require('selenium-webdriver');constchrome=require('selenium-webdriver/chrome');constassert=require("node:assert");letopts=newchrome.Options();opts.addArguments('--headless');letstartIndex=0letendIndex=5letpdfMagicNumber='JVBER'letimgMagicNumber='iVBOR'letbase64Codedescribe('Interactions - Windows',function(){letdriver;before(asyncfunction(){driver=awaitnewBuilder().forBrowser('chrome').setChromeOptions(opts).build();});after(async()=>awaitdriver.quit());it('Should be able to print page to pdf',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');letbase64=awaitdriver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below
// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code=base64.slice(startIndex,endIndex)assert.strictEqual(base64Code,pdfMagicNumber)});it('Should be able to get text using executeScript',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Stores the header element
letheader=awaitdriver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header element
lettext=awaitdriver.executeScript('return arguments[0].innerText',header);assert.strictEqual(text,`Type Stuff`)});it('Should be able to take Element Screenshot',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');letheader=awaitdriver.findElement(By.css('h1'));// Captures the element screenshot
letencodedString=awaitheader.takeScreenshot(true);// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code=encodedString.slice(startIndex,endIndex)assert.strictEqual(base64Code,imgMagicNumber)});it('Should be able to takeScreenshot',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Captures the screenshot
letencodedString=awaitdriver.takeScreenshot();// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code=encodedString.slice(startIndex,endIndex)assert.strictEqual(base64Code,imgMagicNumber)});it('Should be able to switch to newWindow and newTab and close',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');constinitialWindow=awaitdriver.getAllWindowHandles();assert.strictEqual(initialWindow.length,1)// Opens a new tab and switches to new tab
awaitdriver.switchTo().newWindow('tab');constbrowserTabs=awaitdriver.getAllWindowHandles();assert.strictEqual(browserTabs.length,2)// Opens a new window and switches to new window
awaitdriver.switchTo().newWindow('window');constwindows=awaitdriver.getAllWindowHandles();assert.strictEqual(windows.length,3)//Close the tab or window
awaitdriver.close();//Switch back to the old tab or window
awaitdriver.switchTo().window(windows[1]);constwindowsAfterClose=awaitdriver.getAllWindowHandles();assert.strictEqual(windowsAfterClose.length,2);});it('Should be able to getWindow Size',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individually
const{width,height}=awaitdriver.manage().window().getRect();// Or store the dimensions and query them later
constrect=awaitdriver.manage().window().getRect();constwindowWidth=rect.width;constwindowHeight=rect.height;assert.ok(windowWidth>0);assert.ok(windowHeight>0);});it('Should be able to getWindow position',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individually
const{x,y}=awaitdriver.manage().window().getRect();// Or store the dimensions and query them later
constrect=awaitdriver.manage().window().getRect();constx1=rect.x;consty1=rect.y;assert.ok(x1>=0);assert.ok(y1>=0);});});
const{Builder,By}=require('selenium-webdriver');constchrome=require('selenium-webdriver/chrome');constassert=require("node:assert");letopts=newchrome.Options();opts.addArguments('--headless');letstartIndex=0letendIndex=5letpdfMagicNumber='JVBER'letimgMagicNumber='iVBOR'letbase64Codedescribe('Interactions - Windows',function(){letdriver;before(asyncfunction(){driver=awaitnewBuilder().forBrowser('chrome').setChromeOptions(opts).build();});after(async()=>awaitdriver.quit());it('Should be able to print page to pdf',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');letbase64=awaitdriver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below
// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code=base64.slice(startIndex,endIndex)assert.strictEqual(base64Code,pdfMagicNumber)});it('Should be able to get text using executeScript',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Stores the header element
letheader=awaitdriver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header element
lettext=awaitdriver.executeScript('return arguments[0].innerText',header);assert.strictEqual(text,`Type Stuff`)});it('Should be able to take Element Screenshot',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');letheader=awaitdriver.findElement(By.css('h1'));// Captures the element screenshot
letencodedString=awaitheader.takeScreenshot(true);// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code=encodedString.slice(startIndex,endIndex)assert.strictEqual(base64Code,imgMagicNumber)});it('Should be able to takeScreenshot',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Captures the screenshot
letencodedString=awaitdriver.takeScreenshot();// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code=encodedString.slice(startIndex,endIndex)assert.strictEqual(base64Code,imgMagicNumber)});it('Should be able to switch to newWindow and newTab and close',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');constinitialWindow=awaitdriver.getAllWindowHandles();assert.strictEqual(initialWindow.length,1)// Opens a new tab and switches to new tab
awaitdriver.switchTo().newWindow('tab');constbrowserTabs=awaitdriver.getAllWindowHandles();assert.strictEqual(browserTabs.length,2)// Opens a new window and switches to new window
awaitdriver.switchTo().newWindow('window');constwindows=awaitdriver.getAllWindowHandles();assert.strictEqual(windows.length,3)//Close the tab or window
awaitdriver.close();//Switch back to the old tab or window
awaitdriver.switchTo().window(windows[1]);constwindowsAfterClose=awaitdriver.getAllWindowHandles();assert.strictEqual(windowsAfterClose.length,2);});it('Should be able to getWindow Size',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individually
const{width,height}=awaitdriver.manage().window().getRect();// Or store the dimensions and query them later
constrect=awaitdriver.manage().window().getRect();constwindowWidth=rect.width;constwindowHeight=rect.height;assert.ok(windowWidth>0);assert.ok(windowHeight>0);});it('Should be able to getWindow position',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individually
const{x,y}=awaitdriver.manage().window().getRect();// Or store the dimensions and query them later
constrect=awaitdriver.manage().window().getRect();constx1=rect.x;consty1=rect.y;assert.ok(x1>=0);assert.ok(y1>=0);});});
packagedev.selenium.interactions;importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;importjava.time.Duration;importorg.junit.jupiter.api.Test;import staticorg.junit.jupiter.api.Assertions.*;publicclassWindowsTest{@TestpublicvoidwindowsExampleCode(){WebDriverdriver=newChromeDriver();driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));// Navigate to Urldriver.get("https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html");//fetch handle of thisStringcurrHandle=driver.getWindowHandle();assertNotNull(currHandle);//click on link to open a new windowdriver.findElement(By.linkText("Open new window")).click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowObject[]windowHandles=driver.getWindowHandles().toArray();driver.switchTo().window((String)windowHandles[1]);//assert on title of new windowStringtitle=driver.getTitle();assertEquals("Simple Page",title);//closing current windowdriver.close();//Switch back to the old tab or windowdriver.switchTo().window((String)windowHandles[0]);//Opens a new tab and switches to new tabdriver.switchTo().newWindow(WindowType.TAB);assertEquals("",driver.getTitle());//Opens a new window and switches to new windowdriver.switchTo().newWindow(WindowType.WINDOW);assertEquals("",driver.getTitle());//quitting driverdriver.quit();//close all windows}}
//quitting driverdriver.Quit();//close all windows
Show full example
usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{ [TestClass]publicclassWindowsTest{ [TestMethod]publicvoidTestWindowCommands(){WebDriverdriver=newChromeDriver();driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromMilliseconds(500);// Navigate to Urldriver.Url="https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html";//fetch handle of thisStringcurrHandle=driver.CurrentWindowHandle;Assert.IsNotNull(currHandle);//click on link to open a new windowdriver.FindElement(By.LinkText("Open new window")).Click();//fetch handles of all windows, there will be two, [0]- default, [1] - new windowIList<string>windowHandles=newList<string>(driver.WindowHandles);driver.SwitchTo().Window(windowHandles[1]);//assert on title of new windowStringtitle=driver.Title;Assert.AreEqual("Simple Page",title);//closing current windowdriver.Close();//Switch back to the old tab or windowdriver.SwitchTo().Window(windowHandles[0]);//Opens a new tab and switches to new tabdriver.SwitchTo().NewWindow(WindowType.Tab);Assert.AreEqual("",driver.Title);//Opens a new window and switches to new windowdriver.SwitchTo().NewWindow(WindowType.Window);Assert.AreEqual("",driver.Title);//quitting driverdriver.Quit();//close all windows}}}
const{Builder,By}=require('selenium-webdriver');constchrome=require('selenium-webdriver/chrome');constassert=require("node:assert");letopts=newchrome.Options();opts.addArguments('--headless');letstartIndex=0letendIndex=5letpdfMagicNumber='JVBER'letimgMagicNumber='iVBOR'letbase64Codedescribe('Interactions - Windows',function(){letdriver;before(asyncfunction(){driver=awaitnewBuilder().forBrowser('chrome').setChromeOptions(opts).build();});after(async()=>awaitdriver.quit());it('Should be able to print page to pdf',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');letbase64=awaitdriver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below
// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code=base64.slice(startIndex,endIndex)assert.strictEqual(base64Code,pdfMagicNumber)});it('Should be able to get text using executeScript',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Stores the header element
letheader=awaitdriver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header element
lettext=awaitdriver.executeScript('return arguments[0].innerText',header);assert.strictEqual(text,`Type Stuff`)});it('Should be able to take Element Screenshot',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');letheader=awaitdriver.findElement(By.css('h1'));// Captures the element screenshot
letencodedString=awaitheader.takeScreenshot(true);// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code=encodedString.slice(startIndex,endIndex)assert.strictEqual(base64Code,imgMagicNumber)});it('Should be able to takeScreenshot',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Captures the screenshot
letencodedString=awaitdriver.takeScreenshot();// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code=encodedString.slice(startIndex,endIndex)assert.strictEqual(base64Code,imgMagicNumber)});it('Should be able to switch to newWindow and newTab and close',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');constinitialWindow=awaitdriver.getAllWindowHandles();assert.strictEqual(initialWindow.length,1)// Opens a new tab and switches to new tab
awaitdriver.switchTo().newWindow('tab');constbrowserTabs=awaitdriver.getAllWindowHandles();assert.strictEqual(browserTabs.length,2)// Opens a new window and switches to new window
awaitdriver.switchTo().newWindow('window');constwindows=awaitdriver.getAllWindowHandles();assert.strictEqual(windows.length,3)//Close the tab or window
awaitdriver.close();//Switch back to the old tab or window
awaitdriver.switchTo().window(windows[1]);constwindowsAfterClose=awaitdriver.getAllWindowHandles();assert.strictEqual(windowsAfterClose.length,2);});it('Should be able to getWindow Size',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individually
const{width,height}=awaitdriver.manage().window().getRect();// Or store the dimensions and query them later
constrect=awaitdriver.manage().window().getRect();constwindowWidth=rect.width;constwindowHeight=rect.height;assert.ok(windowWidth>0);assert.ok(windowHeight>0);});it('Should be able to getWindow position',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individually
const{x,y}=awaitdriver.manage().window().getRect();// Or store the dimensions and query them later
constrect=awaitdriver.manage().window().getRect();constx1=rect.x;consty1=rect.y;assert.ok(x1>=0);assert.ok(y1>=0);});});
const{Builder,By}=require('selenium-webdriver');constchrome=require('selenium-webdriver/chrome');constassert=require("node:assert");letopts=newchrome.Options();opts.addArguments('--headless');letstartIndex=0letendIndex=5letpdfMagicNumber='JVBER'letimgMagicNumber='iVBOR'letbase64Codedescribe('Interactions - Windows',function(){letdriver;before(asyncfunction(){driver=awaitnewBuilder().forBrowser('chrome').setChromeOptions(opts).build();});after(async()=>awaitdriver.quit());it('Should be able to print page to pdf',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');letbase64=awaitdriver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below
// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code=base64.slice(startIndex,endIndex)assert.strictEqual(base64Code,pdfMagicNumber)});it('Should be able to get text using executeScript',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Stores the header element
letheader=awaitdriver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header element
lettext=awaitdriver.executeScript('return arguments[0].innerText',header);assert.strictEqual(text,`Type Stuff`)});it('Should be able to take Element Screenshot',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');letheader=awaitdriver.findElement(By.css('h1'));// Captures the element screenshot
letencodedString=awaitheader.takeScreenshot(true);// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code=encodedString.slice(startIndex,endIndex)assert.strictEqual(base64Code,imgMagicNumber)});it('Should be able to takeScreenshot',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Captures the screenshot
letencodedString=awaitdriver.takeScreenshot();// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code=encodedString.slice(startIndex,endIndex)assert.strictEqual(base64Code,imgMagicNumber)});it('Should be able to switch to newWindow and newTab and close',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');constinitialWindow=awaitdriver.getAllWindowHandles();assert.strictEqual(initialWindow.length,1)// Opens a new tab and switches to new tab
awaitdriver.switchTo().newWindow('tab');constbrowserTabs=awaitdriver.getAllWindowHandles();assert.strictEqual(browserTabs.length,2)// Opens a new window and switches to new window
awaitdriver.switchTo().newWindow('window');constwindows=awaitdriver.getAllWindowHandles();assert.strictEqual(windows.length,3)//Close the tab or window
awaitdriver.close();//Switch back to the old tab or window
awaitdriver.switchTo().window(windows[1]);constwindowsAfterClose=awaitdriver.getAllWindowHandles();assert.strictEqual(windowsAfterClose.length,2);});it('Should be able to getWindow Size',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individually
const{width,height}=awaitdriver.manage().window().getRect();// Or store the dimensions and query them later
constrect=awaitdriver.manage().window().getRect();constwindowWidth=rect.width;constwindowHeight=rect.height;assert.ok(windowWidth>0);assert.ok(windowHeight>0);});it('Should be able to getWindow position',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individually
const{x,y}=awaitdriver.manage().window().getRect();// Or store the dimensions and query them later
constrect=awaitdriver.manage().window().getRect();constx1=rect.x;consty1=rect.y;assert.ok(x1>=0);assert.ok(y1>=0);});});
#Access each dimension individuallyx=driver.manage.window.position.xy=driver.manage.window.position.y# Or store the dimensions and query them laterrect=driver.manage.window.rectx1=rect.xy1=rect.y
const{Builder,By}=require('selenium-webdriver');constchrome=require('selenium-webdriver/chrome');constassert=require("node:assert");letopts=newchrome.Options();opts.addArguments('--headless');letstartIndex=0letendIndex=5letpdfMagicNumber='JVBER'letimgMagicNumber='iVBOR'letbase64Codedescribe('Interactions - Windows',function(){letdriver;before(asyncfunction(){driver=awaitnewBuilder().forBrowser('chrome').setChromeOptions(opts).build();});after(async()=>awaitdriver.quit());it('Should be able to print page to pdf',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');letbase64=awaitdriver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below
// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code=base64.slice(startIndex,endIndex)assert.strictEqual(base64Code,pdfMagicNumber)});it('Should be able to get text using executeScript',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Stores the header element
letheader=awaitdriver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header element
lettext=awaitdriver.executeScript('return arguments[0].innerText',header);assert.strictEqual(text,`Type Stuff`)});it('Should be able to take Element Screenshot',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');letheader=awaitdriver.findElement(By.css('h1'));// Captures the element screenshot
letencodedString=awaitheader.takeScreenshot(true);// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code=encodedString.slice(startIndex,endIndex)assert.strictEqual(base64Code,imgMagicNumber)});it('Should be able to takeScreenshot',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Captures the screenshot
letencodedString=awaitdriver.takeScreenshot();// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code=encodedString.slice(startIndex,endIndex)assert.strictEqual(base64Code,imgMagicNumber)});it('Should be able to switch to newWindow and newTab and close',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');constinitialWindow=awaitdriver.getAllWindowHandles();assert.strictEqual(initialWindow.length,1)// Opens a new tab and switches to new tab
awaitdriver.switchTo().newWindow('tab');constbrowserTabs=awaitdriver.getAllWindowHandles();assert.strictEqual(browserTabs.length,2)// Opens a new window and switches to new window
awaitdriver.switchTo().newWindow('window');constwindows=awaitdriver.getAllWindowHandles();assert.strictEqual(windows.length,3)//Close the tab or window
awaitdriver.close();//Switch back to the old tab or window
awaitdriver.switchTo().window(windows[1]);constwindowsAfterClose=awaitdriver.getAllWindowHandles();assert.strictEqual(windowsAfterClose.length,2);});it('Should be able to getWindow Size',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individually
const{width,height}=awaitdriver.manage().window().getRect();// Or store the dimensions and query them later
constrect=awaitdriver.manage().window().getRect();constwindowWidth=rect.width;constwindowHeight=rect.height;assert.ok(windowWidth>0);assert.ok(windowHeight>0);});it('Should be able to getWindow position',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individually
const{x,y}=awaitdriver.manage().window().getRect();// Or store the dimensions and query them later
constrect=awaitdriver.manage().window().getRect();constx1=rect.x;consty1=rect.y;assert.ok(x1>=0);assert.ok(y1>=0);});});
const{Builder,By}=require('selenium-webdriver');constchrome=require('selenium-webdriver/chrome');constassert=require("node:assert");letopts=newchrome.Options();opts.addArguments('--headless');letstartIndex=0letendIndex=5letpdfMagicNumber='JVBER'letimgMagicNumber='iVBOR'letbase64Codedescribe('Interactions - Windows',function(){letdriver;before(asyncfunction(){driver=awaitnewBuilder().forBrowser('chrome').setChromeOptions(opts).build();});after(async()=>awaitdriver.quit());it('Should be able to print page to pdf',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');letbase64=awaitdriver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below
// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code=base64.slice(startIndex,endIndex)assert.strictEqual(base64Code,pdfMagicNumber)});it('Should be able to get text using executeScript',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Stores the header element
letheader=awaitdriver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header element
lettext=awaitdriver.executeScript('return arguments[0].innerText',header);assert.strictEqual(text,`Type Stuff`)});it('Should be able to take Element Screenshot',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');letheader=awaitdriver.findElement(By.css('h1'));// Captures the element screenshot
letencodedString=awaitheader.takeScreenshot(true);// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code=encodedString.slice(startIndex,endIndex)assert.strictEqual(base64Code,imgMagicNumber)});it('Should be able to takeScreenshot',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Captures the screenshot
letencodedString=awaitdriver.takeScreenshot();// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code=encodedString.slice(startIndex,endIndex)assert.strictEqual(base64Code,imgMagicNumber)});it('Should be able to switch to newWindow and newTab and close',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');constinitialWindow=awaitdriver.getAllWindowHandles();assert.strictEqual(initialWindow.length,1)// Opens a new tab and switches to new tab
awaitdriver.switchTo().newWindow('tab');constbrowserTabs=awaitdriver.getAllWindowHandles();assert.strictEqual(browserTabs.length,2)// Opens a new window and switches to new window
awaitdriver.switchTo().newWindow('window');constwindows=awaitdriver.getAllWindowHandles();assert.strictEqual(windows.length,3)//Close the tab or window
awaitdriver.close();//Switch back to the old tab or window
awaitdriver.switchTo().window(windows[1]);constwindowsAfterClose=awaitdriver.getAllWindowHandles();assert.strictEqual(windowsAfterClose.length,2);});it('Should be able to getWindow Size',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individually
const{width,height}=awaitdriver.manage().window().getRect();// Or store the dimensions and query them later
constrect=awaitdriver.manage().window().getRect();constwindowWidth=rect.width;constwindowHeight=rect.height;assert.ok(windowWidth>0);assert.ok(windowHeight>0);});it('Should be able to getWindow position',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individually
const{x,y}=awaitdriver.manage().window().getRect();// Or store the dimensions and query them later
constrect=awaitdriver.manage().window().getRect();constx1=rect.x;consty1=rect.y;assert.ok(x1>=0);assert.ok(y1>=0);});});
fromseleniumimportwebdriverdriver=webdriver.Chrome()# Navigate to urldriver.get("http://www.example.com")# Returns and base64 encoded string into imagedriver.save_screenshot('./image.png')driver.quit()
usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingOpenQA.Selenium.Support.UI;vardriver=newChromeDriver();driver.Navigate().GoToUrl("http://www.example.com");Screenshotscreenshot=(driverasITakesScreenshot).GetScreenshot();screenshot.SaveAsFile("screenshot.png",ScreenshotImageFormat.Png);// Format values are Bmp, Gif, Jpeg, Png, Tiff
require'selenium-webdriver'driver=Selenium::WebDriver.for:chromebegindriver.get'https://example.com/'# Takes and Stores the screenshot in specified pathdriver.save_screenshot('./image.png')end
// Captures the screenshot
letencodedString=awaitdriver.takeScreenshot();// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
Show full example
const{Builder,By}=require('selenium-webdriver');constchrome=require('selenium-webdriver/chrome');constassert=require("node:assert");letopts=newchrome.Options();opts.addArguments('--headless');letstartIndex=0letendIndex=5letpdfMagicNumber='JVBER'letimgMagicNumber='iVBOR'letbase64Codedescribe('Interactions - Windows',function(){letdriver;before(asyncfunction(){driver=awaitnewBuilder().forBrowser('chrome').setChromeOptions(opts).build();});after(async()=>awaitdriver.quit());it('Should be able to print page to pdf',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');letbase64=awaitdriver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below
// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code=base64.slice(startIndex,endIndex)assert.strictEqual(base64Code,pdfMagicNumber)});it('Should be able to get text using executeScript',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Stores the header element
letheader=awaitdriver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header element
lettext=awaitdriver.executeScript('return arguments[0].innerText',header);assert.strictEqual(text,`Type Stuff`)});it('Should be able to take Element Screenshot',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');letheader=awaitdriver.findElement(By.css('h1'));// Captures the element screenshot
letencodedString=awaitheader.takeScreenshot(true);// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code=encodedString.slice(startIndex,endIndex)assert.strictEqual(base64Code,imgMagicNumber)});it('Should be able to takeScreenshot',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Captures the screenshot
letencodedString=awaitdriver.takeScreenshot();// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code=encodedString.slice(startIndex,endIndex)assert.strictEqual(base64Code,imgMagicNumber)});it('Should be able to switch to newWindow and newTab and close',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');constinitialWindow=awaitdriver.getAllWindowHandles();assert.strictEqual(initialWindow.length,1)// Opens a new tab and switches to new tab
awaitdriver.switchTo().newWindow('tab');constbrowserTabs=awaitdriver.getAllWindowHandles();assert.strictEqual(browserTabs.length,2)// Opens a new window and switches to new window
awaitdriver.switchTo().newWindow('window');constwindows=awaitdriver.getAllWindowHandles();assert.strictEqual(windows.length,3)//Close the tab or window
awaitdriver.close();//Switch back to the old tab or window
awaitdriver.switchTo().window(windows[1]);constwindowsAfterClose=awaitdriver.getAllWindowHandles();assert.strictEqual(windowsAfterClose.length,2);});it('Should be able to getWindow Size',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individually
const{width,height}=awaitdriver.manage().window().getRect();// Or store the dimensions and query them later
constrect=awaitdriver.manage().window().getRect();constwindowWidth=rect.width;constwindowHeight=rect.height;assert.ok(windowWidth>0);assert.ok(windowHeight>0);});it('Should be able to getWindow position',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individually
const{x,y}=awaitdriver.manage().window().getRect();// Or store the dimensions and query them later
constrect=awaitdriver.manage().window().getRect();constx1=rect.x;consty1=rect.y;assert.ok(x1>=0);assert.ok(y1>=0);});});
fromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydriver=webdriver.Chrome()# Navigate to urldriver.get("http://www.example.com")ele=driver.find_element(By.CSS_SELECTOR,'h1')# Returns and base64 encoded string into imageele.screenshot('./image.png')driver.quit()
usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingOpenQA.Selenium.Support.UI;// Webdrivervardriver=newChromeDriver();driver.Navigate().GoToUrl("http://www.example.com");// Fetch element using FindElementvarwebElement=driver.FindElement(By.CssSelector("h1"));// Screenshot for the elementvarelementScreenshot=(webElementasITakesScreenshot).GetScreenshot();elementScreenshot.SaveAsFile("screenshot_of_element.png");
# Works with Selenium4-alpha7 Ruby bindings and aboverequire'selenium-webdriver'driver=Selenium::WebDriver.for:chromebegindriver.get'https://example.com/'ele=driver.find_element(:css,'h1')# Takes and Stores the element screenshot in specified pathele.save_screenshot('./image.jpg')end
letheader=awaitdriver.findElement(By.css('h1'));// Captures the element screenshot
letencodedString=awaitheader.takeScreenshot(true);// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
Show full example
const{Builder,By}=require('selenium-webdriver');constchrome=require('selenium-webdriver/chrome');constassert=require("node:assert");letopts=newchrome.Options();opts.addArguments('--headless');letstartIndex=0letendIndex=5letpdfMagicNumber='JVBER'letimgMagicNumber='iVBOR'letbase64Codedescribe('Interactions - Windows',function(){letdriver;before(asyncfunction(){driver=awaitnewBuilder().forBrowser('chrome').setChromeOptions(opts).build();});after(async()=>awaitdriver.quit());it('Should be able to print page to pdf',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');letbase64=awaitdriver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below
// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code=base64.slice(startIndex,endIndex)assert.strictEqual(base64Code,pdfMagicNumber)});it('Should be able to get text using executeScript',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Stores the header element
letheader=awaitdriver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header element
lettext=awaitdriver.executeScript('return arguments[0].innerText',header);assert.strictEqual(text,`Type Stuff`)});it('Should be able to take Element Screenshot',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');letheader=awaitdriver.findElement(By.css('h1'));// Captures the element screenshot
letencodedString=awaitheader.takeScreenshot(true);// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code=encodedString.slice(startIndex,endIndex)assert.strictEqual(base64Code,imgMagicNumber)});it('Should be able to takeScreenshot',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Captures the screenshot
letencodedString=awaitdriver.takeScreenshot();// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code=encodedString.slice(startIndex,endIndex)assert.strictEqual(base64Code,imgMagicNumber)});it('Should be able to switch to newWindow and newTab and close',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');constinitialWindow=awaitdriver.getAllWindowHandles();assert.strictEqual(initialWindow.length,1)// Opens a new tab and switches to new tab
awaitdriver.switchTo().newWindow('tab');constbrowserTabs=awaitdriver.getAllWindowHandles();assert.strictEqual(browserTabs.length,2)// Opens a new window and switches to new window
awaitdriver.switchTo().newWindow('window');constwindows=awaitdriver.getAllWindowHandles();assert.strictEqual(windows.length,3)//Close the tab or window
awaitdriver.close();//Switch back to the old tab or window
awaitdriver.switchTo().window(windows[1]);constwindowsAfterClose=awaitdriver.getAllWindowHandles();assert.strictEqual(windowsAfterClose.length,2);});it('Should be able to getWindow Size',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individually
const{width,height}=awaitdriver.manage().window().getRect();// Or store the dimensions and query them later
constrect=awaitdriver.manage().window().getRect();constwindowWidth=rect.width;constwindowHeight=rect.height;assert.ok(windowWidth>0);assert.ok(windowHeight>0);});it('Should be able to getWindow position',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individually
const{x,y}=awaitdriver.manage().window().getRect();// Or store the dimensions and query them later
constrect=awaitdriver.manage().window().getRect();constx1=rect.x;consty1=rect.y;assert.ok(x1>=0);assert.ok(y1>=0);});});
//Creating the JavascriptExecutor interface object by Type castingJavascriptExecutorjs=(JavascriptExecutor)driver;//Button ElementWebElementbutton=driver.findElement(By.name("btnLogin"));//Executing JavaScript to click on elementjs.executeScript("arguments[0].click();",button);//Get return value from scriptStringtext=(String)js.executeScript("return arguments[0].innerText",button);//Executing JavaScript directlyjs.executeScript("console.log('hello world')");
# Stores the header elementheader=driver.find_element(By.CSS_SELECTOR,"h1")# Executing JavaScript to capture innerText of header elementdriver.execute_script('return arguments[0].innerText',header)
//creating Chromedriver instanceIWebDriverdriver=newChromeDriver();//Creating the JavascriptExecutor interface object by Type castingIJavaScriptExecutorjs=(IJavaScriptExecutor)driver;//Button ElementIWebElementbutton=driver.FindElement(By.Name("btnLogin"));//Executing JavaScript to click on elementjs.ExecuteScript("arguments[0].click();",button);//Get return value from scriptStringtext=(String)js.ExecuteScript("return arguments[0].innerText",button);//Executing JavaScript directlyjs.ExecuteScript("console.log('hello world')");
# Stores the header elementheader=driver.find_element(css:'h1')# Get return value from scriptresult=driver.execute_script("return arguments[0].innerText",header)# Executing JavaScript directlydriver.execute_script("alert('hello world')")
// Stores the header element
letheader=awaitdriver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header element
lettext=awaitdriver.executeScript('return arguments[0].innerText',header);
Show full example
const{Builder,By}=require('selenium-webdriver');constchrome=require('selenium-webdriver/chrome');constassert=require("node:assert");letopts=newchrome.Options();opts.addArguments('--headless');letstartIndex=0letendIndex=5letpdfMagicNumber='JVBER'letimgMagicNumber='iVBOR'letbase64Codedescribe('Interactions - Windows',function(){letdriver;before(asyncfunction(){driver=awaitnewBuilder().forBrowser('chrome').setChromeOptions(opts).build();});after(async()=>awaitdriver.quit());it('Should be able to print page to pdf',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');letbase64=awaitdriver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below
// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code=base64.slice(startIndex,endIndex)assert.strictEqual(base64Code,pdfMagicNumber)});it('Should be able to get text using executeScript',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Stores the header element
letheader=awaitdriver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header element
lettext=awaitdriver.executeScript('return arguments[0].innerText',header);assert.strictEqual(text,`Type Stuff`)});it('Should be able to take Element Screenshot',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');letheader=awaitdriver.findElement(By.css('h1'));// Captures the element screenshot
letencodedString=awaitheader.takeScreenshot(true);// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code=encodedString.slice(startIndex,endIndex)assert.strictEqual(base64Code,imgMagicNumber)});it('Should be able to takeScreenshot',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Captures the screenshot
letencodedString=awaitdriver.takeScreenshot();// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code=encodedString.slice(startIndex,endIndex)assert.strictEqual(base64Code,imgMagicNumber)});it('Should be able to switch to newWindow and newTab and close',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');constinitialWindow=awaitdriver.getAllWindowHandles();assert.strictEqual(initialWindow.length,1)// Opens a new tab and switches to new tab
awaitdriver.switchTo().newWindow('tab');constbrowserTabs=awaitdriver.getAllWindowHandles();assert.strictEqual(browserTabs.length,2)// Opens a new window and switches to new window
awaitdriver.switchTo().newWindow('window');constwindows=awaitdriver.getAllWindowHandles();assert.strictEqual(windows.length,3)//Close the tab or window
awaitdriver.close();//Switch back to the old tab or window
awaitdriver.switchTo().window(windows[1]);constwindowsAfterClose=awaitdriver.getAllWindowHandles();assert.strictEqual(windowsAfterClose.length,2);});it('Should be able to getWindow Size',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individually
const{width,height}=awaitdriver.manage().window().getRect();// Or store the dimensions and query them later
constrect=awaitdriver.manage().window().getRect();constwindowWidth=rect.width;constwindowHeight=rect.height;assert.ok(windowWidth>0);assert.ok(windowHeight>0);});it('Should be able to getWindow position',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individually
const{x,y}=awaitdriver.manage().window().getRect();// Or store the dimensions and query them later
constrect=awaitdriver.manage().window().getRect();constx1=rect.x;consty1=rect.y;assert.ok(x1>=0);assert.ok(y1>=0);});});
// Stores the header element
valheader=driver.findElement(By.cssSelector("h1"))// Get return value from script
valresult=driver.executeScript("return arguments[0].innerText",header)// Executing JavaScript directly
driver.executeScript("alert('hello world')")
awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');letbase64=awaitdriver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below
// await fs.writeFileSync('./test.pdf', base64, 'base64');
Show full example
const{Builder,By}=require('selenium-webdriver');constchrome=require('selenium-webdriver/chrome');constassert=require("node:assert");letopts=newchrome.Options();opts.addArguments('--headless');letstartIndex=0letendIndex=5letpdfMagicNumber='JVBER'letimgMagicNumber='iVBOR'letbase64Codedescribe('Interactions - Windows',function(){letdriver;before(asyncfunction(){driver=awaitnewBuilder().forBrowser('chrome').setChromeOptions(opts).build();});after(async()=>awaitdriver.quit());it('Should be able to print page to pdf',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/alerts.html');letbase64=awaitdriver.printPage({pageRanges:["1-2"]});// page can be saved as a PDF as below
// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code=base64.slice(startIndex,endIndex)assert.strictEqual(base64Code,pdfMagicNumber)});it('Should be able to get text using executeScript',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Stores the header element
letheader=awaitdriver.findElement(By.css('h1'));// Executing JavaScript to capture innerText of header element
lettext=awaitdriver.executeScript('return arguments[0].innerText',header);assert.strictEqual(text,`Type Stuff`)});it('Should be able to take Element Screenshot',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');letheader=awaitdriver.findElement(By.css('h1'));// Captures the element screenshot
letencodedString=awaitheader.takeScreenshot(true);// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code=encodedString.slice(startIndex,endIndex)assert.strictEqual(base64Code,imgMagicNumber)});it('Should be able to takeScreenshot',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');// Captures the screenshot
letencodedString=awaitdriver.takeScreenshot();// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code=encodedString.slice(startIndex,endIndex)assert.strictEqual(base64Code,imgMagicNumber)});it('Should be able to switch to newWindow and newTab and close',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');constinitialWindow=awaitdriver.getAllWindowHandles();assert.strictEqual(initialWindow.length,1)// Opens a new tab and switches to new tab
awaitdriver.switchTo().newWindow('tab');constbrowserTabs=awaitdriver.getAllWindowHandles();assert.strictEqual(browserTabs.length,2)// Opens a new window and switches to new window
awaitdriver.switchTo().newWindow('window');constwindows=awaitdriver.getAllWindowHandles();assert.strictEqual(windows.length,3)//Close the tab or window
awaitdriver.close();//Switch back to the old tab or window
awaitdriver.switchTo().window(windows[1]);constwindowsAfterClose=awaitdriver.getAllWindowHandles();assert.strictEqual(windowsAfterClose.length,2);});it('Should be able to getWindow Size',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individually
const{width,height}=awaitdriver.manage().window().getRect();// Or store the dimensions and query them later
constrect=awaitdriver.manage().window().getRect();constwindowWidth=rect.width;constwindowHeight=rect.height;assert.ok(windowWidth>0);assert.ok(windowHeight>0);});it('Should be able to getWindow position',asyncfunction(){awaitdriver.get('https://www.selenium.dev/selenium/web/');// Access each dimension individually
const{x,y}=awaitdriver.manage().window().getRect();// Or store the dimensions and query them later
constrect=awaitdriver.manage().window().getRect();constx1=rect.x;consty1=rect.y;assert.ok(x1>=0);assert.ok(y1>=0);});});
packagedev.selenium.interactions;importdev.selenium.BaseChromeTest;importjava.security.spec.PKCS8EncodedKeySpec;importjava.util.Base64;importjava.util.List;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.InvalidArgumentException;importorg.openqa.selenium.virtualauthenticator.Credential;importorg.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;importorg.openqa.selenium.virtualauthenticator.VirtualAuthenticator;importorg.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;publicclassVirtualAuthenticatorTestextendsBaseChromeTest{/**
* A pkcs#8 encoded encrypted RSA private key as a base64url string.
*/privatefinalstaticStringbase64EncodedRsaPK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"+"GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOT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ESi0oiDdkz3KOHPwIjn6B"+"hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"+"WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"+"NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"+"nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";privatefinalstaticPKCS8EncodedKeySpecrsaPrivateKey=newPKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(base64EncodedRsaPK));// A pkcs#8 encoded unencrypted EC256 private key as a base64url string.Stringbase64EncodedEC256PK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";PKCS8EncodedKeySpecec256PrivateKey=newPKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));@TestpublicvoidtestVirtualOptions(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setIsUserVerified(true).setHasUserVerification(true).setIsUserConsenting(true).setTransport(VirtualAuthenticatorOptions.Transport.USB).setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);Assertions.assertEquals(6,options.toMap().size());}@TestpublicvoidtestCreateAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(0,credentialList.size());}@TestpublicvoidtestRemoveAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions();VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);((HasVirtualAuthenticator)driver).removeVirtualAuthenticator(authenticator);Assertions.assertThrows(InvalidArgumentException.class,authenticator::getCredentials);}@TestpublicvoidtestCreateAndAddResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2).setHasResidentKey(true).setHasUserVerification(true).setIsUserVerified(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.createResidentCredential(credentialId,"localhost",rsaPrivateKey,userHandle,/*signCount=*/0);authenticator.addCredential(residentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());}@TestpublicvoidtestAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);PKCS8EncodedKeySpecprivateKey=newPKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));byte[]credentialId={1,2,3,4};byte[]userHandle={1};Credentialcredential=Credential.createResidentCredential(credentialId,"localhost",privateKey,userHandle,/*signCount=*/0);Assertions.assertThrows(InvalidArgumentException.class,()->authenticator.addCredential(credential));}@TestpublicvoidtestCreateAndAddNonResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.createNonResidentCredential(credentialId,"localhost",ec256PrivateKey,/*signCount=*/0);authenticator.addCredential(nonResidentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());}@TestpublicvoidtestGetCredential(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2).setHasResidentKey(true).setHasUserVerification(true).setIsUserVerified(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.createResidentCredential(credentialId,"localhost",rsaPrivateKey,userHandle,/*signCount=*/0);authenticator.addCredential(residentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());Assertions.assertArrayEquals(rsaPrivateKey.getEncoded(),credential.getPrivateKey().getEncoded());}@TestpublicvoidtestRemoveCredential(){VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};Credentialcredential=Credential.createNonResidentCredential(credentialId,"localhost",rsaPrivateKey,0);authenticator.addCredential(credential);authenticator.removeCredential(credentialId);Assertions.assertEquals(0,authenticator.getCredentials().size());}@TestpublicvoidtestRemoveAllCredentials(){VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialresidentCredential=Credential.createNonResidentCredential(credentialId,"localhost",rsaPrivateKey,/*signCount=*/0);authenticator.addCredential(residentCredential);authenticator.removeAllCredentials();Assertions.assertEquals(0,authenticator.getCredentials().size());}@TestpublicvoidtestSetUserVerified(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setIsUserVerified(true);Assertions.assertTrue((boolean)options.toMap().get("isUserVerified"));}}
usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingMicrosoft.IdentityModel.Tokens;usingOpenQA.Selenium;usingOpenQA.Selenium.VirtualAuth;usingstaticOpenQA.Selenium.VirtualAuth.VirtualAuthenticatorOptions;usingSystem.Collections.Generic;usingSystem;namespaceSeleniumDocs.VirtualAuthentication{ [TestClass]publicclassVirtualAuthenticatorTest:BaseChromeTest{//A pkcs#8 encoded encrypted RSA private key as a base64 string.privatestaticstringbase64EncodedRSAPK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"+"GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"+"9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"+"vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"+"zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"+"XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"+"RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"+"QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"+"S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"+"ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"+"ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"+"OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"+"ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"+"hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"+"WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"+"NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"+"nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";privatestaticbyte[]bytes=System.Convert.FromBase64String(base64EncodedRSAPK);privatestringbase64EncodedPK=Base64UrlEncoder.Encode(bytes);// A pkcs#8 encoded unencrypted EC256 private key as a base64url string.privatestringbase64EncodedEC256PK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB"; [TestMethod]publicvoidVirtualOptionsShouldAllowSettingOptions(){// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetIsUserVerified(true).SetHasUserVerification(true).SetIsUserConsenting(true).SetTransport(VirtualAuthenticatorOptions.Transport.USB).SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);Assert.AreEqual(6,options.ToDictionary().Count);} [TestMethod]publicvoidShouldBeAbleToCreateAuthenticator(){// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);// Register a virtual authenticator((WebDriver)driver).AddVirtualAuthenticator(options);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(0,credentialList.Count);} [TestMethod]publicvoidShouldBeAbleToRemoveAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);StringvirtualAuthenticatorId=((WebDriver)driver).AddVirtualAuthenticator(options);((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);// Since the authenticator was removed, any operation using it will throw an errorAssert.ThrowsException<InvalidOperationException>(()=>((WebDriver)driver).GetCredentials());} [TestMethod]publicvoidShouldBeAbleToCreateAndAddResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(Protocol.CTAP2).SetHasResidentKey(true).SetHasUserVerification(true).SetIsUserVerified(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedPK,userHandle,0);((WebDriver)driver).AddCredential(residentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,credential.Id);} [TestMethod]publicvoidShouldNotAddResidentCredentialWhenAuthenticatorUsesU2FProtocol(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};Credentialcredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedEC256PK,userHandle,0);Assert.ThrowsException<WebDriverArgumentException>(()=>((WebDriver)driver).AddCredential(credential));} [TestMethod]publicvoidShouldBeAbleToCreateAndAddNonResidentKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,nonResidentCredential.Id);} [TestMethod]publicvoidShouldBeAbleToGetCredential(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(Protocol.CTAP2).SetHasResidentKey(true).SetHasUserVerification(true).SetIsUserVerified(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedPK,userHandle,0);((WebDriver)driver).AddCredential(residentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,residentCredential.Id);Assert.AreEqual(base64EncodedPK,credential.PrivateKey);} [TestMethod]publicvoidShouldBeAbleToRemoveCredential(){((WebDriver)driver).AddVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);((WebDriver)driver).RemoveCredential(credentialId);Assert.AreEqual(0,((WebDriver)driver).GetCredentials().Count);} [TestMethod]publicvoidShouldBeAbleToRemoveAllCredentias(){((WebDriver)driver).AddVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);((WebDriver)driver).RemoveAllCredentials();Assert.AreEqual(0,((WebDriver)driver).GetCredentials().Count);} [TestMethod]publicvoidShouldBeSetVerifiedOption(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetIsUserVerified(true);Assert.IsTrue((bool)options.ToDictionary()["isUserVerified"]);}}}
importpytestfrombase64importurlsafe_b64decode,urlsafe_b64encodefromselenium.common.exceptionsimportInvalidArgumentExceptionfromselenium.webdriver.chrome.webdriverimportWebDriverfromselenium.webdriver.common.virtual_authenticatorimport(Credential,VirtualAuthenticatorOptions,)BASE64__ENCODED_PK='''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzth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
K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct
lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
'''@pytest.fixture(scope="module",autouse=True)defdriver():yieldWebDriver()deftest_virtual_authenticator_options():options=VirtualAuthenticatorOptions()options.is_user_verified=Trueoptions.has_user_verification=Trueoptions.is_user_consenting=Trueoptions.transport=VirtualAuthenticatorOptions.Transport.USBoptions.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=Falseassertlen(options.to_dict())==6deftest_add_authenticator(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Get list of credentialscredential_list=driver.get_credentials()assertlen(credential_list)==0deftest_remove_authenticator(driver):# Create default virtual authenticator optionoptions=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Remove virtual authenticatordriver.remove_virtual_authenticator()assertdriver.virtual_authenticator_idisNonedeftest_create_and_add_resident_key(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.CTAP2options.has_resident_key=Trueoptions.has_user_verification=Trueoptions.is_user_verified=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(resident_credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1deftest_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parameterscredential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# Expect InvalidArgumentException withpytest.raises(InvalidArgumentException):driver.add_credential(credential)deftest_create_and_add_non_resident_key(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1deftest_get_credential(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.CTAP2options.has_resident_key=Trueoptions.has_user_verfied=Trueoptions.is_user_verified=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parameterscredential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1assertcredential_list[0].id==urlsafe_b64encode(credential_id).decode()deftest_remove_credential(driver):# Create default virtual authenticator optionsoptions=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# remove the credential created from virtual authenticatordriver.remove_credential(credential.id)# credential can also be removed using Byte Array# driver.remove_credential(credential_id) assertlen(driver.get_credentials())==0deftest_remove_all_credentials(driver):# Create default virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.has_resident_key=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(resident_credential)# remove all credentials in virtual authenticatordriver.remove_all_credentials()assertlen(driver.get_credentials())==0deftest_set_user_verified():# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.is_user_verified=Trueassertoptions.to_dict().get("isUserVerified")isTrue
packagedev.selenium.interactions;importdev.selenium.BaseChromeTest;importjava.security.spec.PKCS8EncodedKeySpec;importjava.util.Base64;importjava.util.List;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.InvalidArgumentException;importorg.openqa.selenium.virtualauthenticator.Credential;importorg.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;importorg.openqa.selenium.virtualauthenticator.VirtualAuthenticator;importorg.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;publicclassVirtualAuthenticatorTestextendsBaseChromeTest{/**
* A pkcs#8 encoded encrypted RSA private key as a base64url string.
*/privatefinalstaticStringbase64EncodedRsaPK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"+"GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"+"9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"+"vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"+"zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"+"XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"+"RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"+"QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"+"S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"+"ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"+"ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"+"OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"+"ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"+"hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"+"WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"+"NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"+"nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";privatefinalstaticPKCS8EncodedKeySpecrsaPrivateKey=newPKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(base64EncodedRsaPK));// A pkcs#8 encoded unencrypted EC256 private key as a base64url string.Stringbase64EncodedEC256PK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";PKCS8EncodedKeySpecec256PrivateKey=newPKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));@TestpublicvoidtestVirtualOptions(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setIsUserVerified(true).setHasUserVerification(true).setIsUserConsenting(true).setTransport(VirtualAuthenticatorOptions.Transport.USB).setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);Assertions.assertEquals(6,options.toMap().size());}@TestpublicvoidtestCreateAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(0,credentialList.size());}@TestpublicvoidtestRemoveAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions();VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);((HasVirtualAuthenticator)driver).removeVirtualAuthenticator(authenticator);Assertions.assertThrows(InvalidArgumentException.class,authenticator::getCredentials);}@TestpublicvoidtestCreateAndAddResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2).setHasResidentKey(true).setHasUserVerification(true).setIsUserVerified(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.createResidentCredential(credentialId,"localhost",rsaPrivateKey,userHandle,/*signCount=*/0);authenticator.addCredential(residentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());}@TestpublicvoidtestAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);PKCS8EncodedKeySpecprivateKey=newPKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));byte[]credentialId={1,2,3,4};byte[]userHandle={1};Credentialcredential=Credential.createResidentCredential(credentialId,"localhost",privateKey,userHandle,/*signCount=*/0);Assertions.assertThrows(InvalidArgumentException.class,()->authenticator.addCredential(credential));}@TestpublicvoidtestCreateAndAddNonResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.createNonResidentCredential(credentialId,"localhost",ec256PrivateKey,/*signCount=*/0);authenticator.addCredential(nonResidentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());}@TestpublicvoidtestGetCredential(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2).setHasResidentKey(true).setHasUserVerification(true).setIsUserVerified(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.createResidentCredential(credentialId,"localhost",rsaPrivateKey,userHandle,/*signCount=*/0);authenticator.addCredential(residentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());Assertions.assertArrayEquals(rsaPrivateKey.getEncoded(),credential.getPrivateKey().getEncoded());}@TestpublicvoidtestRemoveCredential(){VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};Credentialcredential=Credential.createNonResidentCredential(credentialId,"localhost",rsaPrivateKey,0);authenticator.addCredential(credential);authenticator.removeCredential(credentialId);Assertions.assertEquals(0,authenticator.getCredentials().size());}@TestpublicvoidtestRemoveAllCredentials(){VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialresidentCredential=Credential.createNonResidentCredential(credentialId,"localhost",rsaPrivateKey,/*signCount=*/0);authenticator.addCredential(residentCredential);authenticator.removeAllCredentials();Assertions.assertEquals(0,authenticator.getCredentials().size());}@TestpublicvoidtestSetUserVerified(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setIsUserVerified(true);Assertions.assertTrue((boolean)options.toMap().get("isUserVerified"));}}
// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);// Register a virtual authenticator((WebDriver)driver).AddVirtualAuthenticator(options);List<Credential>credentialList=((WebDriver)driver).GetCredentials();
Show full example
usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingMicrosoft.IdentityModel.Tokens;usingOpenQA.Selenium;usingOpenQA.Selenium.VirtualAuth;usingstaticOpenQA.Selenium.VirtualAuth.VirtualAuthenticatorOptions;usingSystem.Collections.Generic;usingSystem;namespaceSeleniumDocs.VirtualAuthentication{ [TestClass]publicclassVirtualAuthenticatorTest:BaseChromeTest{//A pkcs#8 encoded encrypted RSA private key as a base64 string.privatestaticstringbase64EncodedRSAPK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2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OfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"+"ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"+"hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"+"WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"+"NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"+"nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";privatestaticbyte[]bytes=System.Convert.FromBase64String(base64EncodedRSAPK);privatestringbase64EncodedPK=Base64UrlEncoder.Encode(bytes);// A pkcs#8 encoded unencrypted EC256 private key as a base64url string.privatestringbase64EncodedEC256PK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB"; [TestMethod]publicvoidVirtualOptionsShouldAllowSettingOptions(){// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetIsUserVerified(true).SetHasUserVerification(true).SetIsUserConsenting(true).SetTransport(VirtualAuthenticatorOptions.Transport.USB).SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);Assert.AreEqual(6,options.ToDictionary().Count);} [TestMethod]publicvoidShouldBeAbleToCreateAuthenticator(){// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);// Register a virtual authenticator((WebDriver)driver).AddVirtualAuthenticator(options);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(0,credentialList.Count);} [TestMethod]publicvoidShouldBeAbleToRemoveAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);StringvirtualAuthenticatorId=((WebDriver)driver).AddVirtualAuthenticator(options);((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);// Since the authenticator was removed, any operation using it will throw an errorAssert.ThrowsException<InvalidOperationException>(()=>((WebDriver)driver).GetCredentials());} [TestMethod]publicvoidShouldBeAbleToCreateAndAddResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(Protocol.CTAP2).SetHasResidentKey(true).SetHasUserVerification(true).SetIsUserVerified(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedPK,userHandle,0);((WebDriver)driver).AddCredential(residentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,credential.Id);} [TestMethod]publicvoidShouldNotAddResidentCredentialWhenAuthenticatorUsesU2FProtocol(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};Credentialcredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedEC256PK,userHandle,0);Assert.ThrowsException<WebDriverArgumentException>(()=>((WebDriver)driver).AddCredential(credential));} [TestMethod]publicvoidShouldBeAbleToCreateAndAddNonResidentKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,nonResidentCredential.Id);} [TestMethod]publicvoidShouldBeAbleToGetCredential(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(Protocol.CTAP2).SetHasResidentKey(true).SetHasUserVerification(true).SetIsUserVerified(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedPK,userHandle,0);((WebDriver)driver).AddCredential(residentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,residentCredential.Id);Assert.AreEqual(base64EncodedPK,credential.PrivateKey);} [TestMethod]publicvoidShouldBeAbleToRemoveCredential(){((WebDriver)driver).AddVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);((WebDriver)driver).RemoveCredential(credentialId);Assert.AreEqual(0,((WebDriver)driver).GetCredentials().Count);} [TestMethod]publicvoidShouldBeAbleToRemoveAllCredentias(){((WebDriver)driver).AddVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);((WebDriver)driver).RemoveAllCredentials();Assert.AreEqual(0,((WebDriver)driver).GetCredentials().Count);} [TestMethod]publicvoidShouldBeSetVerifiedOption(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetIsUserVerified(true);Assert.IsTrue((bool)options.ToDictionary()["isUserVerified"]);}}}
options=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)
Show full example
importpytestfrombase64importurlsafe_b64decode,urlsafe_b64encodefromselenium.common.exceptionsimportInvalidArgumentExceptionfromselenium.webdriver.chrome.webdriverimportWebDriverfromselenium.webdriver.common.virtual_authenticatorimport(Credential,VirtualAuthenticatorOptions,)BASE64__ENCODED_PK='''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV
oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ
FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq
GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0
+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9lj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ytest.fixture(scope="module",autouse=True)defdriver():yieldWebDriver()deftest_virtual_authenticator_options():options=VirtualAuthenticatorOptions()options.is_user_verified=Trueoptions.has_user_verification=Trueoptions.is_user_consenting=Trueoptions.transport=VirtualAuthenticatorOptions.Transport.USBoptions.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=Falseassertlen(options.to_dict())==6deftest_add_authenticator(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Get list of credentialscredential_list=driver.get_credentials()assertlen(credential_list)==0deftest_remove_authenticator(driver):# Create default virtual authenticator optionoptions=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Remove virtual authenticatordriver.remove_virtual_authenticator()assertdriver.virtual_authenticator_idisNonedeftest_create_and_add_resident_key(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.CTAP2options.has_resident_key=Trueoptions.has_user_verification=Trueoptions.is_user_verified=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(resident_credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1deftest_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parameterscredential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# Expect InvalidArgumentException withpytest.raises(InvalidArgumentException):driver.add_credential(credential)deftest_create_and_add_non_resident_key(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1deftest_get_credential(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.CTAP2options.has_resident_key=Trueoptions.has_user_verfied=Trueoptions.is_user_verified=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parameterscredential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1assertcredential_list[0].id==urlsafe_b64encode(credential_id).decode()deftest_remove_credential(driver):# Create default virtual authenticator optionsoptions=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# remove the credential created from virtual authenticatordriver.remove_credential(credential.id)# credential can also be removed using Byte Array# driver.remove_credential(credential_id) assertlen(driver.get_credentials())==0deftest_remove_all_credentials(driver):# Create default virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.has_resident_key=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(resident_credential)# remove all credentials in virtual authenticatordriver.remove_all_credentials()assertlen(driver.get_credentials())==0deftest_set_user_verified():# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.is_user_verified=Trueassertoptions.to_dict().get("isUserVerified")isTrue
options.setProtocol(Protocol['U2F']);options.setHasResidentKey(false);// Register a virtual authenticator
awaitdriver.addVirtualAuthenticator(options);
Show full example
const{Builder}=require("selenium-webdriver");const{Credential,VirtualAuthenticatorOptions,Transport,Protocol}=require("selenium-webdriver/lib/virtual_authenticator");constassert=require('assert')const{InvalidArgumentError}=require("selenium-webdriver/lib/error");describe('Virtual authenticator',function(){constBASE64_ENCODED_PK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV"+"oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ"+"FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJ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wYADmkfTRmHDvqzQSSvoC2S7aa"+"9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH"+"zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H"+"BYGpI8g==";constbase64EncodedPK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";letoptions;letdriver;before(asyncfunction(){options=newVirtualAuthenticatorOptions();driver=awaitnewBuilder().forBrowser('chrome').build();});after(async()=>awaitdriver.quit());functionarraysEqual(array1,array2){return(array1.length===array2.length&&array1.every((item)=>array2.includes(item))&&array2.every((item)=>array1.includes(item)));}it('Register a virtual authenticator',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(false);// Register a virtual authenticator
awaitdriver.addVirtualAuthenticator(options);letcredentialList=awaitdriver.getCredentials();assert.equal(0,credentialList.length);});it('Remove authenticator',asyncfunction(){awaitdriver.addVirtualAuthenticator(options);awaitdriver.removeVirtualAuthenticator();// Since the authenticator was removed, any operation using it will throw an error
try{awaitdriver.getCredentials()}catch(e){if(einstanceofInvalidArgumentError){assert(true)}else{assert(false)}}});it('Createa and add residential key',asyncfunction(){options.setProtocol(Protocol['CTAP2']);options.setHasResidentKey(true);options.setHasUserVerification(true);options.setIsUserVerified(true);awaitdriver.addVirtualAuthenticator(options);letresidentCredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(residentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));});it('Add resident credential not supported when authenticator uses U2F protocol',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(true);awaitdriver.addVirtualAuthenticator(options);letcredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(base64EncodedPK,'base64').toString('binary'),0);try{awaitdriver.addCredential(credential)}catch(e){if(einstanceofInvalidArgumentError){assert(true)}else{assert(false)}}});it('Create and add non residential key',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(false);awaitdriver.addVirtualAuthenticator(options);letnonResidentCredential=newCredential().createNonResidentCredential(newUint8Array([1,2,3,4]),'localhost',Buffer.from(base64EncodedPK,'base64').toString('binary'),0);awaitdriver.addCredential(nonResidentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));});it('Get credential',asyncfunction(){options.setProtocol(Protocol['CTAP2']);options.setHasResidentKey(true);options.setHasUserVerification(true);options.setIsUserVerified(true);awaitdriver.addVirtualAuthenticator(options);letresidentCredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(residentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));assert.equal(BASE64_ENCODED_PK,Buffer.from(credentialList[0].privateKey(),'binary').toString('base64'));});it('Remove all credentials',asyncfunction(){awaitdriver.addVirtualAuthenticator(options);letnonResidentCredential=newCredential().createNonResidentCredential(newUint8Array([1,2,3,4]),'localhost',Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(nonResidentCredential);awaitdriver.removeAllCredentials();letcredentialList=awaitdriver.getCredentials();assert.equal(0,credentialList.length);});it('Set is user verified',asyncfunction(){options.setIsUserVerified(true);assert.equal(options.getIsUserVerified(),true);});});
packagedev.selenium.interactions;importdev.selenium.BaseChromeTest;importjava.security.spec.PKCS8EncodedKeySpec;importjava.util.Base64;importjava.util.List;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.InvalidArgumentException;importorg.openqa.selenium.virtualauthenticator.Credential;importorg.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;importorg.openqa.selenium.virtualauthenticator.VirtualAuthenticator;importorg.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;publicclassVirtualAuthenticatorTestextendsBaseChromeTest{/**
* A pkcs#8 encoded encrypted RSA private key as a base64url string.
*/privatefinalstaticStringbase64EncodedRsaPK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"+"GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"+"9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"+"vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"+"zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/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0n/lyqxE4HBYGpI8g==";privatefinalstaticPKCS8EncodedKeySpecrsaPrivateKey=newPKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(base64EncodedRsaPK));// A pkcs#8 encoded unencrypted EC256 private key as a base64url string.Stringbase64EncodedEC256PK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";PKCS8EncodedKeySpecec256PrivateKey=newPKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));@TestpublicvoidtestVirtualOptions(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setIsUserVerified(true).setHasUserVerification(true).setIsUserConsenting(true).setTransport(VirtualAuthenticatorOptions.Transport.USB).setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);Assertions.assertEquals(6,options.toMap().size());}@TestpublicvoidtestCreateAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(0,credentialList.size());}@TestpublicvoidtestRemoveAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions();VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);((HasVirtualAuthenticator)driver).removeVirtualAuthenticator(authenticator);Assertions.assertThrows(InvalidArgumentException.class,authenticator::getCredentials);}@TestpublicvoidtestCreateAndAddResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2).setHasResidentKey(true).setHasUserVerification(true).setIsUserVerified(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.createResidentCredential(credentialId,"localhost",rsaPrivateKey,userHandle,/*signCount=*/0);authenticator.addCredential(residentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());}@TestpublicvoidtestAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);PKCS8EncodedKeySpecprivateKey=newPKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));byte[]credentialId={1,2,3,4};byte[]userHandle={1};Credentialcredential=Credential.createResidentCredential(credentialId,"localhost",privateKey,userHandle,/*signCount=*/0);Assertions.assertThrows(InvalidArgumentException.class,()->authenticator.addCredential(credential));}@TestpublicvoidtestCreateAndAddNonResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.createNonResidentCredential(credentialId,"localhost",ec256PrivateKey,/*signCount=*/0);authenticator.addCredential(nonResidentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());}@TestpublicvoidtestGetCredential(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2).setHasResidentKey(true).setHasUserVerification(true).setIsUserVerified(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.createResidentCredential(credentialId,"localhost",rsaPrivateKey,userHandle,/*signCount=*/0);authenticator.addCredential(residentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());Assertions.assertArrayEquals(rsaPrivateKey.getEncoded(),credential.getPrivateKey().getEncoded());}@TestpublicvoidtestRemoveCredential(){VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};Credentialcredential=Credential.createNonResidentCredential(credentialId,"localhost",rsaPrivateKey,0);authenticator.addCredential(credential);authenticator.removeCredential(credentialId);Assertions.assertEquals(0,authenticator.getCredentials().size());}@TestpublicvoidtestRemoveAllCredentials(){VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialresidentCredential=Credential.createNonResidentCredential(credentialId,"localhost",rsaPrivateKey,/*signCount=*/0);authenticator.addCredential(residentCredential);authenticator.removeAllCredentials();Assertions.assertEquals(0,authenticator.getCredentials().size());}@TestpublicvoidtestSetUserVerified(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setIsUserVerified(true);Assertions.assertTrue((boolean)options.toMap().get("isUserVerified"));}}
usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingMicrosoft.IdentityModel.Tokens;usingOpenQA.Selenium;usingOpenQA.Selenium.VirtualAuth;usingstaticOpenQA.Selenium.VirtualAuth.VirtualAuthenticatorOptions;usingSystem.Collections.Generic;usingSystem;namespaceSeleniumDocs.VirtualAuthentication{ [TestClass]publicclassVirtualAuthenticatorTest:BaseChromeTest{//A pkcs#8 encoded encrypted RSA private key as a base64 string.privatestaticstringbase64EncodedRSAPK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"+"GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"+"9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"+"vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"+"zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"+"XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"+"RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"+"QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"+"S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"+"ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"+"ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"+"OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"+"ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"+"hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"+"WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"+"NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"+"nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";privatestaticbyte[]bytes=System.Convert.FromBase64String(base64EncodedRSAPK);privatestringbase64EncodedPK=Base64UrlEncoder.Encode(bytes);// A pkcs#8 encoded unencrypted EC256 private key as a base64url string.privatestringbase64EncodedEC256PK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB"; [TestMethod]publicvoidVirtualOptionsShouldAllowSettingOptions(){// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetIsUserVerified(true).SetHasUserVerification(true).SetIsUserConsenting(true).SetTransport(VirtualAuthenticatorOptions.Transport.USB).SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);Assert.AreEqual(6,options.ToDictionary().Count);} [TestMethod]publicvoidShouldBeAbleToCreateAuthenticator(){// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);// Register a virtual authenticator((WebDriver)driver).AddVirtualAuthenticator(options);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(0,credentialList.Count);} [TestMethod]publicvoidShouldBeAbleToRemoveAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);StringvirtualAuthenticatorId=((WebDriver)driver).AddVirtualAuthenticator(options);((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);// Since the authenticator was removed, any operation using it will throw an errorAssert.ThrowsException<InvalidOperationException>(()=>((WebDriver)driver).GetCredentials());} [TestMethod]publicvoidShouldBeAbleToCreateAndAddResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(Protocol.CTAP2).SetHasResidentKey(true).SetHasUserVerification(true).SetIsUserVerified(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedPK,userHandle,0);((WebDriver)driver).AddCredential(residentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,credential.Id);} [TestMethod]publicvoidShouldNotAddResidentCredentialWhenAuthenticatorUsesU2FProtocol(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};Credentialcredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedEC256PK,userHandle,0);Assert.ThrowsException<WebDriverArgumentException>(()=>((WebDriver)driver).AddCredential(credential));} [TestMethod]publicvoidShouldBeAbleToCreateAndAddNonResidentKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,nonResidentCredential.Id);} [TestMethod]publicvoidShouldBeAbleToGetCredential(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(Protocol.CTAP2).SetHasResidentKey(true).SetHasUserVerification(true).SetIsUserVerified(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedPK,userHandle,0);((WebDriver)driver).AddCredential(residentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,residentCredential.Id);Assert.AreEqual(base64EncodedPK,credential.PrivateKey);} [TestMethod]publicvoidShouldBeAbleToRemoveCredential(){((WebDriver)driver).AddVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);((WebDriver)driver).RemoveCredential(credentialId);Assert.AreEqual(0,((WebDriver)driver).GetCredentials().Count);} [TestMethod]publicvoidShouldBeAbleToRemoveAllCredentias(){((WebDriver)driver).AddVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);((WebDriver)driver).RemoveAllCredentials();Assert.AreEqual(0,((WebDriver)driver).GetCredentials().Count);} [TestMethod]publicvoidShouldBeSetVerifiedOption(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetIsUserVerified(true);Assert.IsTrue((bool)options.ToDictionary()["isUserVerified"]);}}}
options=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Remove virtual authenticatordriver.remove_virtual_authenticator()
Show full example
importpytestfrombase64importurlsafe_b64decode,urlsafe_b64encodefromselenium.common.exceptionsimportInvalidArgumentExceptionfromselenium.webdriver.chrome.webdriverimportWebDriverfromselenium.webdriver.common.virtual_authenticatorimport(Credential,VirtualAuthenticatorOptions,)BASE64__ENCODED_PK='''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV
oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ
FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq
GjHtCK+R2QkXAgMBAAECggEAVc6bu7V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33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
'''@pytest.fixture(scope="module",autouse=True)defdriver():yieldWebDriver()deftest_virtual_authenticator_options():options=VirtualAuthenticatorOptions()options.is_user_verified=Trueoptions.has_user_verification=Trueoptions.is_user_consenting=Trueoptions.transport=VirtualAuthenticatorOptions.Transport.USBoptions.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=Falseassertlen(options.to_dict())==6deftest_add_authenticator(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Get list of credentialscredential_list=driver.get_credentials()assertlen(credential_list)==0deftest_remove_authenticator(driver):# Create default virtual authenticator optionoptions=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Remove virtual authenticatordriver.remove_virtual_authenticator()assertdriver.virtual_authenticator_idisNonedeftest_create_and_add_resident_key(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.CTAP2options.has_resident_key=Trueoptions.has_user_verification=Trueoptions.is_user_verified=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(resident_credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1deftest_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parameterscredential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# Expect InvalidArgumentException withpytest.raises(InvalidArgumentException):driver.add_credential(credential)deftest_create_and_add_non_resident_key(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1deftest_get_credential(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.CTAP2options.has_resident_key=Trueoptions.has_user_verfied=Trueoptions.is_user_verified=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parameterscredential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1assertcredential_list[0].id==urlsafe_b64encode(credential_id).decode()deftest_remove_credential(driver):# Create default virtual authenticator optionsoptions=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# remove the credential created from virtual authenticatordriver.remove_credential(credential.id)# credential can also be removed using Byte Array# driver.remove_credential(credential_id) assertlen(driver.get_credentials())==0deftest_remove_all_credentials(driver):# Create default virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.has_resident_key=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(resident_credential)# remove all credentials in virtual authenticatordriver.remove_all_credentials()assertlen(driver.get_credentials())==0deftest_set_user_verified():# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.is_user_verified=Trueassertoptions.to_dict().get("isUserVerified")isTrue
const{Builder}=require("selenium-webdriver");const{Credential,VirtualAuthenticatorOptions,Transport,Protocol}=require("selenium-webdriver/lib/virtual_authenticator");constassert=require('assert')const{InvalidArgumentError}=require("selenium-webdriver/lib/error");describe('Virtual authenticator',function(){constBASE64_ENCODED_PK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV"+"oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi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lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa"+"9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH"+"zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H"+"BYGpI8g==";constbase64EncodedPK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";letoptions;letdriver;before(asyncfunction(){options=newVirtualAuthenticatorOptions();driver=awaitnewBuilder().forBrowser('chrome').build();});after(async()=>awaitdriver.quit());functionarraysEqual(array1,array2){return(array1.length===array2.length&&array1.every((item)=>array2.includes(item))&&array2.every((item)=>array1.includes(item)));}it('Register a virtual authenticator',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(false);// Register a virtual authenticator
awaitdriver.addVirtualAuthenticator(options);letcredentialList=awaitdriver.getCredentials();assert.equal(0,credentialList.length);});it('Remove authenticator',asyncfunction(){awaitdriver.addVirtualAuthenticator(options);awaitdriver.removeVirtualAuthenticator();// Since the authenticator was removed, any operation using it will throw an error
try{awaitdriver.getCredentials()}catch(e){if(einstanceofInvalidArgumentError){assert(true)}else{assert(false)}}});it('Createa and add residential key',asyncfunction(){options.setProtocol(Protocol['CTAP2']);options.setHasResidentKey(true);options.setHasUserVerification(true);options.setIsUserVerified(true);awaitdriver.addVirtualAuthenticator(options);letresidentCredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(residentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));});it('Add resident credential not supported when authenticator uses U2F protocol',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(true);awaitdriver.addVirtualAuthenticator(options);letcredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(base64EncodedPK,'base64').toString('binary'),0);try{awaitdriver.addCredential(credential)}catch(e){if(einstanceofInvalidArgumentError){assert(true)}else{assert(false)}}});it('Create and add non residential key',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(false);awaitdriver.addVirtualAuthenticator(options);letnonResidentCredential=newCredential().createNonResidentCredential(newUint8Array([1,2,3,4]),'localhost',Buffer.from(base64EncodedPK,'base64').toString('binary'),0);awaitdriver.addCredential(nonResidentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));});it('Get credential',asyncfunction(){options.setProtocol(Protocol['CTAP2']);options.setHasResidentKey(true);options.setHasUserVerification(true);options.setIsUserVerified(true);awaitdriver.addVirtualAuthenticator(options);letresidentCredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(residentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));assert.equal(BASE64_ENCODED_PK,Buffer.from(credentialList[0].privateKey(),'binary').toString('base64'));});it('Remove all credentials',asyncfunction(){awaitdriver.addVirtualAuthenticator(options);letnonResidentCredential=newCredential().createNonResidentCredential(newUint8Array([1,2,3,4]),'localhost',Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(nonResidentCredential);awaitdriver.removeAllCredentials();letcredentialList=awaitdriver.getCredentials();assert.equal(0,credentialList.length);});it('Set is user verified',asyncfunction(){options.setIsUserVerified(true);assert.equal(options.getIsUserVerified(),true);});});
packagedev.selenium.interactions;importdev.selenium.BaseChromeTest;importjava.security.spec.PKCS8EncodedKeySpec;importjava.util.Base64;importjava.util.List;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.InvalidArgumentException;importorg.openqa.selenium.virtualauthenticator.Credential;importorg.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;importorg.openqa.selenium.virtualauthenticator.VirtualAuthenticator;importorg.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;publicclassVirtualAuthenticatorTestextendsBaseChromeTest{/**
* A pkcs#8 encoded encrypted RSA private key as a base64url string.
*/privatefinalstaticStringbase64EncodedRsaPK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"+"GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"+"9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"+"vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"+"zAgyPuQ0+j4Vjssr9V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8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"+"nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";privatefinalstaticPKCS8EncodedKeySpecrsaPrivateKey=newPKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(base64EncodedRsaPK));// A pkcs#8 encoded unencrypted EC256 private key as a base64url string.Stringbase64EncodedEC256PK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";PKCS8EncodedKeySpecec256PrivateKey=newPKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));@TestpublicvoidtestVirtualOptions(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setIsUserVerified(true).setHasUserVerification(true).setIsUserConsenting(true).setTransport(VirtualAuthenticatorOptions.Transport.USB).setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);Assertions.assertEquals(6,options.toMap().size());}@TestpublicvoidtestCreateAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(0,credentialList.size());}@TestpublicvoidtestRemoveAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions();VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);((HasVirtualAuthenticator)driver).removeVirtualAuthenticator(authenticator);Assertions.assertThrows(InvalidArgumentException.class,authenticator::getCredentials);}@TestpublicvoidtestCreateAndAddResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2).setHasResidentKey(true).setHasUserVerification(true).setIsUserVerified(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.createResidentCredential(credentialId,"localhost",rsaPrivateKey,userHandle,/*signCount=*/0);authenticator.addCredential(residentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());}@TestpublicvoidtestAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);PKCS8EncodedKeySpecprivateKey=newPKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));byte[]credentialId={1,2,3,4};byte[]userHandle={1};Credentialcredential=Credential.createResidentCredential(credentialId,"localhost",privateKey,userHandle,/*signCount=*/0);Assertions.assertThrows(InvalidArgumentException.class,()->authenticator.addCredential(credential));}@TestpublicvoidtestCreateAndAddNonResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.createNonResidentCredential(credentialId,"localhost",ec256PrivateKey,/*signCount=*/0);authenticator.addCredential(nonResidentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());}@TestpublicvoidtestGetCredential(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2).setHasResidentKey(true).setHasUserVerification(true).setIsUserVerified(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.createResidentCredential(credentialId,"localhost",rsaPrivateKey,userHandle,/*signCount=*/0);authenticator.addCredential(residentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());Assertions.assertArrayEquals(rsaPrivateKey.getEncoded(),credential.getPrivateKey().getEncoded());}@TestpublicvoidtestRemoveCredential(){VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};Credentialcredential=Credential.createNonResidentCredential(credentialId,"localhost",rsaPrivateKey,0);authenticator.addCredential(credential);authenticator.removeCredential(credentialId);Assertions.assertEquals(0,authenticator.getCredentials().size());}@TestpublicvoidtestRemoveAllCredentials(){VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialresidentCredential=Credential.createNonResidentCredential(credentialId,"localhost",rsaPrivateKey,/*signCount=*/0);authenticator.addCredential(residentCredential);authenticator.removeAllCredentials();Assertions.assertEquals(0,authenticator.getCredentials().size());}@TestpublicvoidtestSetUserVerified(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setIsUserVerified(true);Assertions.assertTrue((boolean)options.toMap().get("isUserVerified"));}}
usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingMicrosoft.IdentityModel.Tokens;usingOpenQA.Selenium;usingOpenQA.Selenium.VirtualAuth;usingstaticOpenQA.Selenium.VirtualAuth.VirtualAuthenticatorOptions;usingSystem.Collections.Generic;usingSystem;namespaceSeleniumDocs.VirtualAuthentication{ [TestClass]publicclassVirtualAuthenticatorTest:BaseChromeTest{//A pkcs#8 encoded encrypted RSA private key as a base64 string.privatestaticstringbase64EncodedRSAPK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"+"GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"+"9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"+"vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"+"zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"+"XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"+"RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"+"QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"+"S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"+"ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"+"ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"+"OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"+"ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"+"hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"+"WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"+"NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"+"nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";privatestaticbyte[]bytes=System.Convert.FromBase64String(base64EncodedRSAPK);privatestringbase64EncodedPK=Base64UrlEncoder.Encode(bytes);// A pkcs#8 encoded unencrypted EC256 private key as a base64url string.privatestringbase64EncodedEC256PK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB"; [TestMethod]publicvoidVirtualOptionsShouldAllowSettingOptions(){// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetIsUserVerified(true).SetHasUserVerification(true).SetIsUserConsenting(true).SetTransport(VirtualAuthenticatorOptions.Transport.USB).SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);Assert.AreEqual(6,options.ToDictionary().Count);} [TestMethod]publicvoidShouldBeAbleToCreateAuthenticator(){// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);// Register a virtual authenticator((WebDriver)driver).AddVirtualAuthenticator(options);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(0,credentialList.Count);} [TestMethod]publicvoidShouldBeAbleToRemoveAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);StringvirtualAuthenticatorId=((WebDriver)driver).AddVirtualAuthenticator(options);((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);// Since the authenticator was removed, any operation using it will throw an errorAssert.ThrowsException<InvalidOperationException>(()=>((WebDriver)driver).GetCredentials());} [TestMethod]publicvoidShouldBeAbleToCreateAndAddResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(Protocol.CTAP2).SetHasResidentKey(true).SetHasUserVerification(true).SetIsUserVerified(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedPK,userHandle,0);((WebDriver)driver).AddCredential(residentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,credential.Id);} [TestMethod]publicvoidShouldNotAddResidentCredentialWhenAuthenticatorUsesU2FProtocol(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};Credentialcredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedEC256PK,userHandle,0);Assert.ThrowsException<WebDriverArgumentException>(()=>((WebDriver)driver).AddCredential(credential));} [TestMethod]publicvoidShouldBeAbleToCreateAndAddNonResidentKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,nonResidentCredential.Id);} [TestMethod]publicvoidShouldBeAbleToGetCredential(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(Protocol.CTAP2).SetHasResidentKey(true).SetHasUserVerification(true).SetIsUserVerified(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedPK,userHandle,0);((WebDriver)driver).AddCredential(residentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,residentCredential.Id);Assert.AreEqual(base64EncodedPK,credential.PrivateKey);} [TestMethod]publicvoidShouldBeAbleToRemoveCredential(){((WebDriver)driver).AddVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);((WebDriver)driver).RemoveCredential(credentialId);Assert.AreEqual(0,((WebDriver)driver).GetCredentials().Count);} [TestMethod]publicvoidShouldBeAbleToRemoveAllCredentias(){((WebDriver)driver).AddVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);((WebDriver)driver).RemoveAllCredentials();Assert.AreEqual(0,((WebDriver)driver).GetCredentials().Count);} [TestMethod]publicvoidShouldBeSetVerifiedOption(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetIsUserVerified(true);Assert.IsTrue((bool)options.ToDictionary()["isUserVerified"]);}}}
# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)
Show full example
importpytestfrombase64importurlsafe_b64decode,urlsafe_b64encodefromselenium.common.exceptionsimportInvalidArgumentExceptionfromselenium.webdriver.chrome.webdriverimportWebDriverfromselenium.webdriver.common.virtual_authenticatorimport(Credential,VirtualAuthenticatorOptions,)BASE64__ENCODED_PK='''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV
oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRk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K1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
'''@pytest.fixture(scope="module",autouse=True)defdriver():yieldWebDriver()deftest_virtual_authenticator_options():options=VirtualAuthenticatorOptions()options.is_user_verified=Trueoptions.has_user_verification=Trueoptions.is_user_consenting=Trueoptions.transport=VirtualAuthenticatorOptions.Transport.USBoptions.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=Falseassertlen(options.to_dict())==6deftest_add_authenticator(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Get list of credentialscredential_list=driver.get_credentials()assertlen(credential_list)==0deftest_remove_authenticator(driver):# Create default virtual authenticator optionoptions=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Remove virtual authenticatordriver.remove_virtual_authenticator()assertdriver.virtual_authenticator_idisNonedeftest_create_and_add_resident_key(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.CTAP2options.has_resident_key=Trueoptions.has_user_verification=Trueoptions.is_user_verified=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(resident_credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1deftest_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parameterscredential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# Expect InvalidArgumentException withpytest.raises(InvalidArgumentException):driver.add_credential(credential)deftest_create_and_add_non_resident_key(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1deftest_get_credential(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.CTAP2options.has_resident_key=Trueoptions.has_user_verfied=Trueoptions.is_user_verified=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parameterscredential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1assertcredential_list[0].id==urlsafe_b64encode(credential_id).decode()deftest_remove_credential(driver):# Create default virtual authenticator optionsoptions=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# remove the credential created from virtual authenticatordriver.remove_credential(credential.id)# credential can also be removed using Byte Array# driver.remove_credential(credential_id) assertlen(driver.get_credentials())==0deftest_remove_all_credentials(driver):# Create default virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.has_resident_key=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(resident_credential)# remove all credentials in virtual authenticatordriver.remove_all_credentials()assertlen(driver.get_credentials())==0deftest_set_user_verified():# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.is_user_verified=Trueassertoptions.to_dict().get("isUserVerified")isTrue
const{Builder}=require("selenium-webdriver");const{Credential,VirtualAuthenticatorOptions,Transport,Protocol}=require("selenium-webdriver/lib/virtual_authenticator");constassert=require('assert')const{InvalidArgumentError}=require("selenium-webdriver/lib/error");describe('Virtual authenticator',function(){constBASE64_ENCODED_PK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8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Uwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8"+"K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct"+"lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa"+"9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH"+"zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H"+"BYGpI8g==";constbase64EncodedPK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";letoptions;letdriver;before(asyncfunction(){options=newVirtualAuthenticatorOptions();driver=awaitnewBuilder().forBrowser('chrome').build();});after(async()=>awaitdriver.quit());functionarraysEqual(array1,array2){return(array1.length===array2.length&&array1.every((item)=>array2.includes(item))&&array2.every((item)=>array1.includes(item)));}it('Register a virtual authenticator',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(false);// Register a virtual authenticator
awaitdriver.addVirtualAuthenticator(options);letcredentialList=awaitdriver.getCredentials();assert.equal(0,credentialList.length);});it('Remove authenticator',asyncfunction(){awaitdriver.addVirtualAuthenticator(options);awaitdriver.removeVirtualAuthenticator();// Since the authenticator was removed, any operation using it will throw an error
try{awaitdriver.getCredentials()}catch(e){if(einstanceofInvalidArgumentError){assert(true)}else{assert(false)}}});it('Createa and add residential key',asyncfunction(){options.setProtocol(Protocol['CTAP2']);options.setHasResidentKey(true);options.setHasUserVerification(true);options.setIsUserVerified(true);awaitdriver.addVirtualAuthenticator(options);letresidentCredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(residentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));});it('Add resident credential not supported when authenticator uses U2F protocol',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(true);awaitdriver.addVirtualAuthenticator(options);letcredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(base64EncodedPK,'base64').toString('binary'),0);try{awaitdriver.addCredential(credential)}catch(e){if(einstanceofInvalidArgumentError){assert(true)}else{assert(false)}}});it('Create and add non residential key',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(false);awaitdriver.addVirtualAuthenticator(options);letnonResidentCredential=newCredential().createNonResidentCredential(newUint8Array([1,2,3,4]),'localhost',Buffer.from(base64EncodedPK,'base64').toString('binary'),0);awaitdriver.addCredential(nonResidentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));});it('Get credential',asyncfunction(){options.setProtocol(Protocol['CTAP2']);options.setHasResidentKey(true);options.setHasUserVerification(true);options.setIsUserVerified(true);awaitdriver.addVirtualAuthenticator(options);letresidentCredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(residentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));assert.equal(BASE64_ENCODED_PK,Buffer.from(credentialList[0].privateKey(),'binary').toString('base64'));});it('Remove all credentials',asyncfunction(){awaitdriver.addVirtualAuthenticator(options);letnonResidentCredential=newCredential().createNonResidentCredential(newUint8Array([1,2,3,4]),'localhost',Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(nonResidentCredential);awaitdriver.removeAllCredentials();letcredentialList=awaitdriver.getCredentials();assert.equal(0,credentialList.length);});it('Set is user verified',asyncfunction(){options.setIsUserVerified(true);assert.equal(options.getIsUserVerified(),true);});});
packagedev.selenium.interactions;importdev.selenium.BaseChromeTest;importjava.security.spec.PKCS8EncodedKeySpec;importjava.util.Base64;importjava.util.List;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.InvalidArgumentException;importorg.openqa.selenium.virtualauthenticator.Credential;importorg.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;importorg.openqa.selenium.virtualauthenticator.VirtualAuthenticator;importorg.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;publicclassVirtualAuthenticatorTestextendsBaseChromeTest{/**
* A pkcs#8 encoded encrypted RSA private key as a base64url string.
*/privatefinalstaticStringbase64EncodedRsaPK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"+"GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"+"9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXr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BwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"+"NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"+"nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";privatefinalstaticPKCS8EncodedKeySpecrsaPrivateKey=newPKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(base64EncodedRsaPK));// A pkcs#8 encoded unencrypted EC256 private key as a base64url string.Stringbase64EncodedEC256PK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";PKCS8EncodedKeySpecec256PrivateKey=newPKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));@TestpublicvoidtestVirtualOptions(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setIsUserVerified(true).setHasUserVerification(true).setIsUserConsenting(true).setTransport(VirtualAuthenticatorOptions.Transport.USB).setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);Assertions.assertEquals(6,options.toMap().size());}@TestpublicvoidtestCreateAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(0,credentialList.size());}@TestpublicvoidtestRemoveAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions();VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);((HasVirtualAuthenticator)driver).removeVirtualAuthenticator(authenticator);Assertions.assertThrows(InvalidArgumentException.class,authenticator::getCredentials);}@TestpublicvoidtestCreateAndAddResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2).setHasResidentKey(true).setHasUserVerification(true).setIsUserVerified(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.createResidentCredential(credentialId,"localhost",rsaPrivateKey,userHandle,/*signCount=*/0);authenticator.addCredential(residentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());}@TestpublicvoidtestAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);PKCS8EncodedKeySpecprivateKey=newPKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));byte[]credentialId={1,2,3,4};byte[]userHandle={1};Credentialcredential=Credential.createResidentCredential(credentialId,"localhost",privateKey,userHandle,/*signCount=*/0);Assertions.assertThrows(InvalidArgumentException.class,()->authenticator.addCredential(credential));}@TestpublicvoidtestCreateAndAddNonResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.createNonResidentCredential(credentialId,"localhost",ec256PrivateKey,/*signCount=*/0);authenticator.addCredential(nonResidentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());}@TestpublicvoidtestGetCredential(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2).setHasResidentKey(true).setHasUserVerification(true).setIsUserVerified(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.createResidentCredential(credentialId,"localhost",rsaPrivateKey,userHandle,/*signCount=*/0);authenticator.addCredential(residentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());Assertions.assertArrayEquals(rsaPrivateKey.getEncoded(),credential.getPrivateKey().getEncoded());}@TestpublicvoidtestRemoveCredential(){VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};Credentialcredential=Credential.createNonResidentCredential(credentialId,"localhost",rsaPrivateKey,0);authenticator.addCredential(credential);authenticator.removeCredential(credentialId);Assertions.assertEquals(0,authenticator.getCredentials().size());}@TestpublicvoidtestRemoveAllCredentials(){VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialresidentCredential=Credential.createNonResidentCredential(credentialId,"localhost",rsaPrivateKey,/*signCount=*/0);authenticator.addCredential(residentCredential);authenticator.removeAllCredentials();Assertions.assertEquals(0,authenticator.getCredentials().size());}@TestpublicvoidtestSetUserVerified(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setIsUserVerified(true);Assertions.assertTrue((boolean)options.toMap().get("isUserVerified"));}}
usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingMicrosoft.IdentityModel.Tokens;usingOpenQA.Selenium;usingOpenQA.Selenium.VirtualAuth;usingstaticOpenQA.Selenium.VirtualAuth.VirtualAuthenticatorOptions;usingSystem.Collections.Generic;usingSystem;namespaceSeleniumDocs.VirtualAuthentication{ [TestClass]publicclassVirtualAuthenticatorTest:BaseChromeTest{//A pkcs#8 encoded encrypted RSA private key as a base64 string.privatestaticstringbase64EncodedRSAPK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"+"GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"+"9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"+"vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"+"zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"+"XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"+"RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"+"QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"+"S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"+"ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"+"ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"+"OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"+"ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"+"hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"+"WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"+"NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"+"nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";privatestaticbyte[]bytes=System.Convert.FromBase64String(base64EncodedRSAPK);privatestringbase64EncodedPK=Base64UrlEncoder.Encode(bytes);// A pkcs#8 encoded unencrypted EC256 private key as a base64url string.privatestringbase64EncodedEC256PK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB"; [TestMethod]publicvoidVirtualOptionsShouldAllowSettingOptions(){// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetIsUserVerified(true).SetHasUserVerification(true).SetIsUserConsenting(true).SetTransport(VirtualAuthenticatorOptions.Transport.USB).SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);Assert.AreEqual(6,options.ToDictionary().Count);} [TestMethod]publicvoidShouldBeAbleToCreateAuthenticator(){// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);// Register a virtual authenticator((WebDriver)driver).AddVirtualAuthenticator(options);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(0,credentialList.Count);} [TestMethod]publicvoidShouldBeAbleToRemoveAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);StringvirtualAuthenticatorId=((WebDriver)driver).AddVirtualAuthenticator(options);((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);// Since the authenticator was removed, any operation using it will throw an errorAssert.ThrowsException<InvalidOperationException>(()=>((WebDriver)driver).GetCredentials());} [TestMethod]publicvoidShouldBeAbleToCreateAndAddResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(Protocol.CTAP2).SetHasResidentKey(true).SetHasUserVerification(true).SetIsUserVerified(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedPK,userHandle,0);((WebDriver)driver).AddCredential(residentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,credential.Id);} [TestMethod]publicvoidShouldNotAddResidentCredentialWhenAuthenticatorUsesU2FProtocol(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};Credentialcredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedEC256PK,userHandle,0);Assert.ThrowsException<WebDriverArgumentException>(()=>((WebDriver)driver).AddCredential(credential));} [TestMethod]publicvoidShouldBeAbleToCreateAndAddNonResidentKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,nonResidentCredential.Id);} [TestMethod]publicvoidShouldBeAbleToGetCredential(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(Protocol.CTAP2).SetHasResidentKey(true).SetHasUserVerification(true).SetIsUserVerified(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedPK,userHandle,0);((WebDriver)driver).AddCredential(residentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,residentCredential.Id);Assert.AreEqual(base64EncodedPK,credential.PrivateKey);} [TestMethod]publicvoidShouldBeAbleToRemoveCredential(){((WebDriver)driver).AddVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);((WebDriver)driver).RemoveCredential(credentialId);Assert.AreEqual(0,((WebDriver)driver).GetCredentials().Count);} [TestMethod]publicvoidShouldBeAbleToRemoveAllCredentias(){((WebDriver)driver).AddVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);((WebDriver)driver).RemoveAllCredentials();Assert.AreEqual(0,((WebDriver)driver).GetCredentials().Count);} [TestMethod]publicvoidShouldBeSetVerifiedOption(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetIsUserVerified(true);Assert.IsTrue((bool)options.ToDictionary()["isUserVerified"]);}}}
# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)
Show full example
importpytestfrombase64importurlsafe_b64decode,urlsafe_b64encodefromselenium.common.exceptionsimportInvalidArgumentExceptionfromselenium.webdriver.chrome.webdriverimportWebDriverfromselenium.webdriver.common.virtual_authenticatorimport(Credential,VirtualAuthenticatorOptions,)BASE64__ENCODED_PK='''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO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ASOmqM1ml667axeZDIR867ZG8
K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct
lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
'''@pytest.fixture(scope="module",autouse=True)defdriver():yieldWebDriver()deftest_virtual_authenticator_options():options=VirtualAuthenticatorOptions()options.is_user_verified=Trueoptions.has_user_verification=Trueoptions.is_user_consenting=Trueoptions.transport=VirtualAuthenticatorOptions.Transport.USBoptions.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=Falseassertlen(options.to_dict())==6deftest_add_authenticator(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Get list of credentialscredential_list=driver.get_credentials()assertlen(credential_list)==0deftest_remove_authenticator(driver):# Create default virtual authenticator optionoptions=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Remove virtual authenticatordriver.remove_virtual_authenticator()assertdriver.virtual_authenticator_idisNonedeftest_create_and_add_resident_key(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.CTAP2options.has_resident_key=Trueoptions.has_user_verification=Trueoptions.is_user_verified=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(resident_credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1deftest_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parameterscredential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# Expect InvalidArgumentException withpytest.raises(InvalidArgumentException):driver.add_credential(credential)deftest_create_and_add_non_resident_key(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1deftest_get_credential(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.CTAP2options.has_resident_key=Trueoptions.has_user_verfied=Trueoptions.is_user_verified=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parameterscredential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1assertcredential_list[0].id==urlsafe_b64encode(credential_id).decode()deftest_remove_credential(driver):# Create default virtual authenticator optionsoptions=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# remove the credential created from virtual authenticatordriver.remove_credential(credential.id)# credential can also be removed using Byte Array# driver.remove_credential(credential_id) assertlen(driver.get_credentials())==0deftest_remove_all_credentials(driver):# Create default virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.has_resident_key=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(resident_credential)# remove all credentials in virtual authenticatordriver.remove_all_credentials()assertlen(driver.get_credentials())==0deftest_set_user_verified():# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.is_user_verified=Trueassertoptions.to_dict().get("isUserVerified")isTrue
const{Builder}=require("selenium-webdriver");const{Credential,VirtualAuthenticatorOptions,Transport,Protocol}=require("selenium-webdriver/lib/virtual_authenticator");constassert=require('assert')const{InvalidArgumentError}=require("selenium-webdriver/lib/error");describe('Virtual authenticator',function(){constBASE64_ENCODED_PK="MIIEvAIBADANBgkqhki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89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi"+"uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8"+"K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct"+"lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa"+"9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH"+"zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H"+"BYGpI8g==";constbase64EncodedPK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";letoptions;letdriver;before(asyncfunction(){options=newVirtualAuthenticatorOptions();driver=awaitnewBuilder().forBrowser('chrome').build();});after(async()=>awaitdriver.quit());functionarraysEqual(array1,array2){return(array1.length===array2.length&&array1.every((item)=>array2.includes(item))&&array2.every((item)=>array1.includes(item)));}it('Register a virtual authenticator',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(false);// Register a virtual authenticator
awaitdriver.addVirtualAuthenticator(options);letcredentialList=awaitdriver.getCredentials();assert.equal(0,credentialList.length);});it('Remove authenticator',asyncfunction(){awaitdriver.addVirtualAuthenticator(options);awaitdriver.removeVirtualAuthenticator();// Since the authenticator was removed, any operation using it will throw an error
try{awaitdriver.getCredentials()}catch(e){if(einstanceofInvalidArgumentError){assert(true)}else{assert(false)}}});it('Createa and add residential key',asyncfunction(){options.setProtocol(Protocol['CTAP2']);options.setHasResidentKey(true);options.setHasUserVerification(true);options.setIsUserVerified(true);awaitdriver.addVirtualAuthenticator(options);letresidentCredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(residentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));});it('Add resident credential not supported when authenticator uses U2F protocol',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(true);awaitdriver.addVirtualAuthenticator(options);letcredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(base64EncodedPK,'base64').toString('binary'),0);try{awaitdriver.addCredential(credential)}catch(e){if(einstanceofInvalidArgumentError){assert(true)}else{assert(false)}}});it('Create and add non residential key',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(false);awaitdriver.addVirtualAuthenticator(options);letnonResidentCredential=newCredential().createNonResidentCredential(newUint8Array([1,2,3,4]),'localhost',Buffer.from(base64EncodedPK,'base64').toString('binary'),0);awaitdriver.addCredential(nonResidentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));});it('Get credential',asyncfunction(){options.setProtocol(Protocol['CTAP2']);options.setHasResidentKey(true);options.setHasUserVerification(true);options.setIsUserVerified(true);awaitdriver.addVirtualAuthenticator(options);letresidentCredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(residentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));assert.equal(BASE64_ENCODED_PK,Buffer.from(credentialList[0].privateKey(),'binary').toString('base64'));});it('Remove all credentials',asyncfunction(){awaitdriver.addVirtualAuthenticator(options);letnonResidentCredential=newCredential().createNonResidentCredential(newUint8Array([1,2,3,4]),'localhost',Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(nonResidentCredential);awaitdriver.removeAllCredentials();letcredentialList=awaitdriver.getCredentials();assert.equal(0,credentialList.length);});it('Set is user verified',asyncfunction(){options.setIsUserVerified(true);assert.equal(options.getIsUserVerified(),true);});});
packagedev.selenium.interactions;importdev.selenium.BaseChromeTest;importjava.security.spec.PKCS8EncodedKeySpec;importjava.util.Base64;importjava.util.List;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.InvalidArgumentException;importorg.openqa.selenium.virtualauthenticator.Credential;importorg.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;importorg.openqa.selenium.virtualauthenticator.VirtualAuthenticator;importorg.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;publicclassVirtualAuthenticatorTestextendsBaseChromeTest{/**
* A pkcs#8 encoded encrypted RSA private key as a base64url string.
*/privatefinalstaticStringbase64EncodedRsaPK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"+"GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN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oGACdh4wXESi0oiDdkz3KOHPwIjn6B"+"hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"+"WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"+"NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"+"nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";privatefinalstaticPKCS8EncodedKeySpecrsaPrivateKey=newPKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(base64EncodedRsaPK));// A pkcs#8 encoded unencrypted EC256 private key as a base64url string.Stringbase64EncodedEC256PK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";PKCS8EncodedKeySpecec256PrivateKey=newPKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));@TestpublicvoidtestVirtualOptions(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setIsUserVerified(true).setHasUserVerification(true).setIsUserConsenting(true).setTransport(VirtualAuthenticatorOptions.Transport.USB).setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);Assertions.assertEquals(6,options.toMap().size());}@TestpublicvoidtestCreateAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(0,credentialList.size());}@TestpublicvoidtestRemoveAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions();VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);((HasVirtualAuthenticator)driver).removeVirtualAuthenticator(authenticator);Assertions.assertThrows(InvalidArgumentException.class,authenticator::getCredentials);}@TestpublicvoidtestCreateAndAddResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2).setHasResidentKey(true).setHasUserVerification(true).setIsUserVerified(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.createResidentCredential(credentialId,"localhost",rsaPrivateKey,userHandle,/*signCount=*/0);authenticator.addCredential(residentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());}@TestpublicvoidtestAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);PKCS8EncodedKeySpecprivateKey=newPKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));byte[]credentialId={1,2,3,4};byte[]userHandle={1};Credentialcredential=Credential.createResidentCredential(credentialId,"localhost",privateKey,userHandle,/*signCount=*/0);Assertions.assertThrows(InvalidArgumentException.class,()->authenticator.addCredential(credential));}@TestpublicvoidtestCreateAndAddNonResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.createNonResidentCredential(credentialId,"localhost",ec256PrivateKey,/*signCount=*/0);authenticator.addCredential(nonResidentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());}@TestpublicvoidtestGetCredential(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2).setHasResidentKey(true).setHasUserVerification(true).setIsUserVerified(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.createResidentCredential(credentialId,"localhost",rsaPrivateKey,userHandle,/*signCount=*/0);authenticator.addCredential(residentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());Assertions.assertArrayEquals(rsaPrivateKey.getEncoded(),credential.getPrivateKey().getEncoded());}@TestpublicvoidtestRemoveCredential(){VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};Credentialcredential=Credential.createNonResidentCredential(credentialId,"localhost",rsaPrivateKey,0);authenticator.addCredential(credential);authenticator.removeCredential(credentialId);Assertions.assertEquals(0,authenticator.getCredentials().size());}@TestpublicvoidtestRemoveAllCredentials(){VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialresidentCredential=Credential.createNonResidentCredential(credentialId,"localhost",rsaPrivateKey,/*signCount=*/0);authenticator.addCredential(residentCredential);authenticator.removeAllCredentials();Assertions.assertEquals(0,authenticator.getCredentials().size());}@TestpublicvoidtestSetUserVerified(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setIsUserVerified(true);Assertions.assertTrue((boolean)options.toMap().get("isUserVerified"));}}
usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingMicrosoft.IdentityModel.Tokens;usingOpenQA.Selenium;usingOpenQA.Selenium.VirtualAuth;usingstaticOpenQA.Selenium.VirtualAuth.VirtualAuthenticatorOptions;usingSystem.Collections.Generic;usingSystem;namespaceSeleniumDocs.VirtualAuthentication{ [TestClass]publicclassVirtualAuthenticatorTest:BaseChromeTest{//A pkcs#8 encoded encrypted RSA private key as a base64 string.privatestaticstringbase64EncodedRSAPK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"+"GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"+"9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"+"vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"+"zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"+"XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"+"RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"+"QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"+"S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"+"ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"+"ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"+"OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"+"ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"+"hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"+"WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"+"NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"+"nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";privatestaticbyte[]bytes=System.Convert.FromBase64String(base64EncodedRSAPK);privatestringbase64EncodedPK=Base64UrlEncoder.Encode(bytes);// A pkcs#8 encoded unencrypted EC256 private key as a base64url string.privatestringbase64EncodedEC256PK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB"; [TestMethod]publicvoidVirtualOptionsShouldAllowSettingOptions(){// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetIsUserVerified(true).SetHasUserVerification(true).SetIsUserConsenting(true).SetTransport(VirtualAuthenticatorOptions.Transport.USB).SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);Assert.AreEqual(6,options.ToDictionary().Count);} [TestMethod]publicvoidShouldBeAbleToCreateAuthenticator(){// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);// Register a virtual authenticator((WebDriver)driver).AddVirtualAuthenticator(options);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(0,credentialList.Count);} [TestMethod]publicvoidShouldBeAbleToRemoveAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);StringvirtualAuthenticatorId=((WebDriver)driver).AddVirtualAuthenticator(options);((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);// Since the authenticator was removed, any operation using it will throw an errorAssert.ThrowsException<InvalidOperationException>(()=>((WebDriver)driver).GetCredentials());} [TestMethod]publicvoidShouldBeAbleToCreateAndAddResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(Protocol.CTAP2).SetHasResidentKey(true).SetHasUserVerification(true).SetIsUserVerified(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedPK,userHandle,0);((WebDriver)driver).AddCredential(residentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,credential.Id);} [TestMethod]publicvoidShouldNotAddResidentCredentialWhenAuthenticatorUsesU2FProtocol(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};Credentialcredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedEC256PK,userHandle,0);Assert.ThrowsException<WebDriverArgumentException>(()=>((WebDriver)driver).AddCredential(credential));} [TestMethod]publicvoidShouldBeAbleToCreateAndAddNonResidentKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,nonResidentCredential.Id);} [TestMethod]publicvoidShouldBeAbleToGetCredential(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(Protocol.CTAP2).SetHasResidentKey(true).SetHasUserVerification(true).SetIsUserVerified(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedPK,userHandle,0);((WebDriver)driver).AddCredential(residentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,residentCredential.Id);Assert.AreEqual(base64EncodedPK,credential.PrivateKey);} [TestMethod]publicvoidShouldBeAbleToRemoveCredential(){((WebDriver)driver).AddVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);((WebDriver)driver).RemoveCredential(credentialId);Assert.AreEqual(0,((WebDriver)driver).GetCredentials().Count);} [TestMethod]publicvoidShouldBeAbleToRemoveAllCredentias(){((WebDriver)driver).AddVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);((WebDriver)driver).RemoveAllCredentials();Assert.AreEqual(0,((WebDriver)driver).GetCredentials().Count);} [TestMethod]publicvoidShouldBeSetVerifiedOption(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetIsUserVerified(true);Assert.IsTrue((bool)options.ToDictionary()["isUserVerified"]);}}}
importpytestfrombase64importurlsafe_b64decode,urlsafe_b64encodefromselenium.common.exceptionsimportInvalidArgumentExceptionfromselenium.webdriver.chrome.webdriverimportWebDriverfromselenium.webdriver.common.virtual_authenticatorimport(Credential,VirtualAuthenticatorOptions,)BASE64__ENCODED_PK='''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1Nc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DIR867ZG8
K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct
lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
'''@pytest.fixture(scope="module",autouse=True)defdriver():yieldWebDriver()deftest_virtual_authenticator_options():options=VirtualAuthenticatorOptions()options.is_user_verified=Trueoptions.has_user_verification=Trueoptions.is_user_consenting=Trueoptions.transport=VirtualAuthenticatorOptions.Transport.USBoptions.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=Falseassertlen(options.to_dict())==6deftest_add_authenticator(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Get list of credentialscredential_list=driver.get_credentials()assertlen(credential_list)==0deftest_remove_authenticator(driver):# Create default virtual authenticator optionoptions=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Remove virtual authenticatordriver.remove_virtual_authenticator()assertdriver.virtual_authenticator_idisNonedeftest_create_and_add_resident_key(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.CTAP2options.has_resident_key=Trueoptions.has_user_verification=Trueoptions.is_user_verified=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(resident_credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1deftest_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parameterscredential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# Expect InvalidArgumentException withpytest.raises(InvalidArgumentException):driver.add_credential(credential)deftest_create_and_add_non_resident_key(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1deftest_get_credential(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.CTAP2options.has_resident_key=Trueoptions.has_user_verfied=Trueoptions.is_user_verified=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parameterscredential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1assertcredential_list[0].id==urlsafe_b64encode(credential_id).decode()deftest_remove_credential(driver):# Create default virtual authenticator optionsoptions=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# remove the credential created from virtual authenticatordriver.remove_credential(credential.id)# credential can also be removed using Byte Array# driver.remove_credential(credential_id) assertlen(driver.get_credentials())==0deftest_remove_all_credentials(driver):# Create default virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.has_resident_key=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(resident_credential)# remove all credentials in virtual authenticatordriver.remove_all_credentials()assertlen(driver.get_credentials())==0deftest_set_user_verified():# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.is_user_verified=Trueassertoptions.to_dict().get("isUserVerified")isTrue
const{Builder}=require("selenium-webdriver");const{Credential,VirtualAuthenticatorOptions,Transport,Protocol}=require("selenium-webdriver/lib/virtual_authenticator");constassert=require('assert')const{InvalidArgumentError}=require("selenium-webdriver/lib/error");describe('Virtual authenticator',function(){constBASE64_ENCODED_PK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASC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qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi"+"uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8"+"K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct"+"lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa"+"9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH"+"zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H"+"BYGpI8g==";constbase64EncodedPK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";letoptions;letdriver;before(asyncfunction(){options=newVirtualAuthenticatorOptions();driver=awaitnewBuilder().forBrowser('chrome').build();});after(async()=>awaitdriver.quit());functionarraysEqual(array1,array2){return(array1.length===array2.length&&array1.every((item)=>array2.includes(item))&&array2.every((item)=>array1.includes(item)));}it('Register a virtual authenticator',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(false);// Register a virtual authenticator
awaitdriver.addVirtualAuthenticator(options);letcredentialList=awaitdriver.getCredentials();assert.equal(0,credentialList.length);});it('Remove authenticator',asyncfunction(){awaitdriver.addVirtualAuthenticator(options);awaitdriver.removeVirtualAuthenticator();// Since the authenticator was removed, any operation using it will throw an error
try{awaitdriver.getCredentials()}catch(e){if(einstanceofInvalidArgumentError){assert(true)}else{assert(false)}}});it('Createa and add residential key',asyncfunction(){options.setProtocol(Protocol['CTAP2']);options.setHasResidentKey(true);options.setHasUserVerification(true);options.setIsUserVerified(true);awaitdriver.addVirtualAuthenticator(options);letresidentCredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(residentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));});it('Add resident credential not supported when authenticator uses U2F protocol',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(true);awaitdriver.addVirtualAuthenticator(options);letcredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(base64EncodedPK,'base64').toString('binary'),0);try{awaitdriver.addCredential(credential)}catch(e){if(einstanceofInvalidArgumentError){assert(true)}else{assert(false)}}});it('Create and add non residential key',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(false);awaitdriver.addVirtualAuthenticator(options);letnonResidentCredential=newCredential().createNonResidentCredential(newUint8Array([1,2,3,4]),'localhost',Buffer.from(base64EncodedPK,'base64').toString('binary'),0);awaitdriver.addCredential(nonResidentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));});it('Get credential',asyncfunction(){options.setProtocol(Protocol['CTAP2']);options.setHasResidentKey(true);options.setHasUserVerification(true);options.setIsUserVerified(true);awaitdriver.addVirtualAuthenticator(options);letresidentCredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(residentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));assert.equal(BASE64_ENCODED_PK,Buffer.from(credentialList[0].privateKey(),'binary').toString('base64'));});it('Remove all credentials',asyncfunction(){awaitdriver.addVirtualAuthenticator(options);letnonResidentCredential=newCredential().createNonResidentCredential(newUint8Array([1,2,3,4]),'localhost',Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(nonResidentCredential);awaitdriver.removeAllCredentials();letcredentialList=awaitdriver.getCredentials();assert.equal(0,credentialList.length);});it('Set is user verified',asyncfunction(){options.setIsUserVerified(true);assert.equal(options.getIsUserVerified(),true);});});
packagedev.selenium.interactions;importdev.selenium.BaseChromeTest;importjava.security.spec.PKCS8EncodedKeySpec;importjava.util.Base64;importjava.util.List;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.InvalidArgumentException;importorg.openqa.selenium.virtualauthenticator.Credential;importorg.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;importorg.openqa.selenium.virtualauthenticator.VirtualAuthenticator;importorg.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;publicclassVirtualAuthenticatorTestextendsBaseChromeTest{/**
* A pkcs#8 encoded encrypted RSA private key as a base64url string.
*/privatefinalstaticStringbase64EncodedRsaPK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"+"GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5Z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iDdkz3KOHPwIjn6B"+"hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"+"WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"+"NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"+"nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";privatefinalstaticPKCS8EncodedKeySpecrsaPrivateKey=newPKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(base64EncodedRsaPK));// A pkcs#8 encoded unencrypted EC256 private key as a base64url string.Stringbase64EncodedEC256PK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";PKCS8EncodedKeySpecec256PrivateKey=newPKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));@TestpublicvoidtestVirtualOptions(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setIsUserVerified(true).setHasUserVerification(true).setIsUserConsenting(true).setTransport(VirtualAuthenticatorOptions.Transport.USB).setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);Assertions.assertEquals(6,options.toMap().size());}@TestpublicvoidtestCreateAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(0,credentialList.size());}@TestpublicvoidtestRemoveAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions();VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);((HasVirtualAuthenticator)driver).removeVirtualAuthenticator(authenticator);Assertions.assertThrows(InvalidArgumentException.class,authenticator::getCredentials);}@TestpublicvoidtestCreateAndAddResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2).setHasResidentKey(true).setHasUserVerification(true).setIsUserVerified(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.createResidentCredential(credentialId,"localhost",rsaPrivateKey,userHandle,/*signCount=*/0);authenticator.addCredential(residentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());}@TestpublicvoidtestAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);PKCS8EncodedKeySpecprivateKey=newPKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));byte[]credentialId={1,2,3,4};byte[]userHandle={1};Credentialcredential=Credential.createResidentCredential(credentialId,"localhost",privateKey,userHandle,/*signCount=*/0);Assertions.assertThrows(InvalidArgumentException.class,()->authenticator.addCredential(credential));}@TestpublicvoidtestCreateAndAddNonResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.createNonResidentCredential(credentialId,"localhost",ec256PrivateKey,/*signCount=*/0);authenticator.addCredential(nonResidentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());}@TestpublicvoidtestGetCredential(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2).setHasResidentKey(true).setHasUserVerification(true).setIsUserVerified(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.createResidentCredential(credentialId,"localhost",rsaPrivateKey,userHandle,/*signCount=*/0);authenticator.addCredential(residentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());Assertions.assertArrayEquals(rsaPrivateKey.getEncoded(),credential.getPrivateKey().getEncoded());}@TestpublicvoidtestRemoveCredential(){VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};Credentialcredential=Credential.createNonResidentCredential(credentialId,"localhost",rsaPrivateKey,0);authenticator.addCredential(credential);authenticator.removeCredential(credentialId);Assertions.assertEquals(0,authenticator.getCredentials().size());}@TestpublicvoidtestRemoveAllCredentials(){VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialresidentCredential=Credential.createNonResidentCredential(credentialId,"localhost",rsaPrivateKey,/*signCount=*/0);authenticator.addCredential(residentCredential);authenticator.removeAllCredentials();Assertions.assertEquals(0,authenticator.getCredentials().size());}@TestpublicvoidtestSetUserVerified(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setIsUserVerified(true);Assertions.assertTrue((boolean)options.toMap().get("isUserVerified"));}}
usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingMicrosoft.IdentityModel.Tokens;usingOpenQA.Selenium;usingOpenQA.Selenium.VirtualAuth;usingstaticOpenQA.Selenium.VirtualAuth.VirtualAuthenticatorOptions;usingSystem.Collections.Generic;usingSystem;namespaceSeleniumDocs.VirtualAuthentication{ [TestClass]publicclassVirtualAuthenticatorTest:BaseChromeTest{//A pkcs#8 encoded encrypted RSA private key as a base64 string.privatestaticstringbase64EncodedRSAPK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"+"GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"+"9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"+"vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"+"zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"+"XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"+"RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"+"QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"+"S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"+"ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"+"ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"+"OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"+"ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"+"hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"+"WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"+"NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"+"nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";privatestaticbyte[]bytes=System.Convert.FromBase64String(base64EncodedRSAPK);privatestringbase64EncodedPK=Base64UrlEncoder.Encode(bytes);// A pkcs#8 encoded unencrypted EC256 private key as a base64url string.privatestringbase64EncodedEC256PK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB"; [TestMethod]publicvoidVirtualOptionsShouldAllowSettingOptions(){// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetIsUserVerified(true).SetHasUserVerification(true).SetIsUserConsenting(true).SetTransport(VirtualAuthenticatorOptions.Transport.USB).SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);Assert.AreEqual(6,options.ToDictionary().Count);} [TestMethod]publicvoidShouldBeAbleToCreateAuthenticator(){// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);// Register a virtual authenticator((WebDriver)driver).AddVirtualAuthenticator(options);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(0,credentialList.Count);} [TestMethod]publicvoidShouldBeAbleToRemoveAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);StringvirtualAuthenticatorId=((WebDriver)driver).AddVirtualAuthenticator(options);((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);// Since the authenticator was removed, any operation using it will throw an errorAssert.ThrowsException<InvalidOperationException>(()=>((WebDriver)driver).GetCredentials());} [TestMethod]publicvoidShouldBeAbleToCreateAndAddResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(Protocol.CTAP2).SetHasResidentKey(true).SetHasUserVerification(true).SetIsUserVerified(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedPK,userHandle,0);((WebDriver)driver).AddCredential(residentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,credential.Id);} [TestMethod]publicvoidShouldNotAddResidentCredentialWhenAuthenticatorUsesU2FProtocol(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};Credentialcredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedEC256PK,userHandle,0);Assert.ThrowsException<WebDriverArgumentException>(()=>((WebDriver)driver).AddCredential(credential));} [TestMethod]publicvoidShouldBeAbleToCreateAndAddNonResidentKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,nonResidentCredential.Id);} [TestMethod]publicvoidShouldBeAbleToGetCredential(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(Protocol.CTAP2).SetHasResidentKey(true).SetHasUserVerification(true).SetIsUserVerified(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedPK,userHandle,0);((WebDriver)driver).AddCredential(residentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,residentCredential.Id);Assert.AreEqual(base64EncodedPK,credential.PrivateKey);} [TestMethod]publicvoidShouldBeAbleToRemoveCredential(){((WebDriver)driver).AddVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);((WebDriver)driver).RemoveCredential(credentialId);Assert.AreEqual(0,((WebDriver)driver).GetCredentials().Count);} [TestMethod]publicvoidShouldBeAbleToRemoveAllCredentias(){((WebDriver)driver).AddVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);((WebDriver)driver).RemoveAllCredentials();Assert.AreEqual(0,((WebDriver)driver).GetCredentials().Count);} [TestMethod]publicvoidShouldBeSetVerifiedOption(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetIsUserVerified(true);Assert.IsTrue((bool)options.ToDictionary()["isUserVerified"]);}}}
importpytestfrombase64importurlsafe_b64decode,urlsafe_b64encodefromselenium.common.exceptionsimportInvalidArgumentExceptionfromselenium.webdriver.chrome.webdriverimportWebDriverfromselenium.webdriver.common.virtual_authenticatorimport(Credential,VirtualAuthenticatorOptions,)BASE64__ENCODED_PK='''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/g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029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct
lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
'''@pytest.fixture(scope="module",autouse=True)defdriver():yieldWebDriver()deftest_virtual_authenticator_options():options=VirtualAuthenticatorOptions()options.is_user_verified=Trueoptions.has_user_verification=Trueoptions.is_user_consenting=Trueoptions.transport=VirtualAuthenticatorOptions.Transport.USBoptions.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=Falseassertlen(options.to_dict())==6deftest_add_authenticator(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Get list of credentialscredential_list=driver.get_credentials()assertlen(credential_list)==0deftest_remove_authenticator(driver):# Create default virtual authenticator optionoptions=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Remove virtual authenticatordriver.remove_virtual_authenticator()assertdriver.virtual_authenticator_idisNonedeftest_create_and_add_resident_key(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.CTAP2options.has_resident_key=Trueoptions.has_user_verification=Trueoptions.is_user_verified=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(resident_credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1deftest_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parameterscredential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# Expect InvalidArgumentException withpytest.raises(InvalidArgumentException):driver.add_credential(credential)deftest_create_and_add_non_resident_key(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1deftest_get_credential(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.CTAP2options.has_resident_key=Trueoptions.has_user_verfied=Trueoptions.is_user_verified=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parameterscredential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1assertcredential_list[0].id==urlsafe_b64encode(credential_id).decode()deftest_remove_credential(driver):# Create default virtual authenticator optionsoptions=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# remove the credential created from virtual authenticatordriver.remove_credential(credential.id)# credential can also be removed using Byte Array# driver.remove_credential(credential_id) assertlen(driver.get_credentials())==0deftest_remove_all_credentials(driver):# Create default virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.has_resident_key=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(resident_credential)# remove all credentials in virtual authenticatordriver.remove_all_credentials()assertlen(driver.get_credentials())==0deftest_set_user_verified():# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.is_user_verified=Trueassertoptions.to_dict().get("isUserVerified")isTrue
const{Builder}=require("selenium-webdriver");const{Credential,VirtualAuthenticatorOptions,Transport,Protocol}=require("selenium-webdriver/lib/virtual_authenticator");constassert=require('assert')const{InvalidArgumentError}=require("selenium-webdriver/lib/error");describe('Virtual authenticator',function(){constBASE64_ENCODED_PK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAA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/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi"+"uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8"+"K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct"+"lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa"+"9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH"+"zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H"+"BYGpI8g==";constbase64EncodedPK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";letoptions;letdriver;before(asyncfunction(){options=newVirtualAuthenticatorOptions();driver=awaitnewBuilder().forBrowser('chrome').build();});after(async()=>awaitdriver.quit());functionarraysEqual(array1,array2){return(array1.length===array2.length&&array1.every((item)=>array2.includes(item))&&array2.every((item)=>array1.includes(item)));}it('Register a virtual authenticator',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(false);// Register a virtual authenticator
awaitdriver.addVirtualAuthenticator(options);letcredentialList=awaitdriver.getCredentials();assert.equal(0,credentialList.length);});it('Remove authenticator',asyncfunction(){awaitdriver.addVirtualAuthenticator(options);awaitdriver.removeVirtualAuthenticator();// Since the authenticator was removed, any operation using it will throw an error
try{awaitdriver.getCredentials()}catch(e){if(einstanceofInvalidArgumentError){assert(true)}else{assert(false)}}});it('Createa and add residential key',asyncfunction(){options.setProtocol(Protocol['CTAP2']);options.setHasResidentKey(true);options.setHasUserVerification(true);options.setIsUserVerified(true);awaitdriver.addVirtualAuthenticator(options);letresidentCredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(residentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));});it('Add resident credential not supported when authenticator uses U2F protocol',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(true);awaitdriver.addVirtualAuthenticator(options);letcredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(base64EncodedPK,'base64').toString('binary'),0);try{awaitdriver.addCredential(credential)}catch(e){if(einstanceofInvalidArgumentError){assert(true)}else{assert(false)}}});it('Create and add non residential key',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(false);awaitdriver.addVirtualAuthenticator(options);letnonResidentCredential=newCredential().createNonResidentCredential(newUint8Array([1,2,3,4]),'localhost',Buffer.from(base64EncodedPK,'base64').toString('binary'),0);awaitdriver.addCredential(nonResidentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));});it('Get credential',asyncfunction(){options.setProtocol(Protocol['CTAP2']);options.setHasResidentKey(true);options.setHasUserVerification(true);options.setIsUserVerified(true);awaitdriver.addVirtualAuthenticator(options);letresidentCredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(residentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));assert.equal(BASE64_ENCODED_PK,Buffer.from(credentialList[0].privateKey(),'binary').toString('base64'));});it('Remove all credentials',asyncfunction(){awaitdriver.addVirtualAuthenticator(options);letnonResidentCredential=newCredential().createNonResidentCredential(newUint8Array([1,2,3,4]),'localhost',Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(nonResidentCredential);awaitdriver.removeAllCredentials();letcredentialList=awaitdriver.getCredentials();assert.equal(0,credentialList.length);});it('Set is user verified',asyncfunction(){options.setIsUserVerified(true);assert.equal(options.getIsUserVerified(),true);});});
usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingMicrosoft.IdentityModel.Tokens;usingOpenQA.Selenium;usingOpenQA.Selenium.VirtualAuth;usingstaticOpenQA.Selenium.VirtualAuth.VirtualAuthenticatorOptions;usingSystem.Collections.Generic;usingSystem;namespaceSeleniumDocs.VirtualAuthentication{ [TestClass]publicclassVirtualAuthenticatorTest:BaseChromeTest{//A pkcs#8 encoded encrypted RSA private key as a base64 string.privatestaticstringbase64EncodedRSAPK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"+"GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"+"9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0w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"WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"+"NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"+"nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";privatestaticbyte[]bytes=System.Convert.FromBase64String(base64EncodedRSAPK);privatestringbase64EncodedPK=Base64UrlEncoder.Encode(bytes);// A pkcs#8 encoded unencrypted EC256 private key as a base64url string.privatestringbase64EncodedEC256PK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB"; [TestMethod]publicvoidVirtualOptionsShouldAllowSettingOptions(){// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetIsUserVerified(true).SetHasUserVerification(true).SetIsUserConsenting(true).SetTransport(VirtualAuthenticatorOptions.Transport.USB).SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);Assert.AreEqual(6,options.ToDictionary().Count);} [TestMethod]publicvoidShouldBeAbleToCreateAuthenticator(){// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);// Register a virtual authenticator((WebDriver)driver).AddVirtualAuthenticator(options);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(0,credentialList.Count);} [TestMethod]publicvoidShouldBeAbleToRemoveAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);StringvirtualAuthenticatorId=((WebDriver)driver).AddVirtualAuthenticator(options);((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);// Since the authenticator was removed, any operation using it will throw an errorAssert.ThrowsException<InvalidOperationException>(()=>((WebDriver)driver).GetCredentials());} [TestMethod]publicvoidShouldBeAbleToCreateAndAddResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(Protocol.CTAP2).SetHasResidentKey(true).SetHasUserVerification(true).SetIsUserVerified(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedPK,userHandle,0);((WebDriver)driver).AddCredential(residentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,credential.Id);} [TestMethod]publicvoidShouldNotAddResidentCredentialWhenAuthenticatorUsesU2FProtocol(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};Credentialcredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedEC256PK,userHandle,0);Assert.ThrowsException<WebDriverArgumentException>(()=>((WebDriver)driver).AddCredential(credential));} [TestMethod]publicvoidShouldBeAbleToCreateAndAddNonResidentKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,nonResidentCredential.Id);} [TestMethod]publicvoidShouldBeAbleToGetCredential(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(Protocol.CTAP2).SetHasResidentKey(true).SetHasUserVerification(true).SetIsUserVerified(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedPK,userHandle,0);((WebDriver)driver).AddCredential(residentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,residentCredential.Id);Assert.AreEqual(base64EncodedPK,credential.PrivateKey);} [TestMethod]publicvoidShouldBeAbleToRemoveCredential(){((WebDriver)driver).AddVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);((WebDriver)driver).RemoveCredential(credentialId);Assert.AreEqual(0,((WebDriver)driver).GetCredentials().Count);} [TestMethod]publicvoidShouldBeAbleToRemoveAllCredentias(){((WebDriver)driver).AddVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);((WebDriver)driver).RemoveAllCredentials();Assert.AreEqual(0,((WebDriver)driver).GetCredentials().Count);} [TestMethod]publicvoidShouldBeSetVerifiedOption(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetIsUserVerified(true);Assert.IsTrue((bool)options.ToDictionary()["isUserVerified"]);}}}
packagedev.selenium.interactions;importdev.selenium.BaseChromeTest;importjava.security.spec.PKCS8EncodedKeySpec;importjava.util.Base64;importjava.util.List;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.InvalidArgumentException;importorg.openqa.selenium.virtualauthenticator.Credential;importorg.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;importorg.openqa.selenium.virtualauthenticator.VirtualAuthenticator;importorg.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;publicclassVirtualAuthenticatorTestextendsBaseChromeTest{/**
* A pkcs#8 encoded encrypted RSA private key as a base64url string.
*/privatefinalstaticStringbase64EncodedRsaPK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"+"GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"+"9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"+"vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"+"zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"+"XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"+"RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"+"QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"+"S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"+"ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"+"ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"+"OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"+"ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"+"hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"+"WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"+"NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"+"nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";privatefinalstaticPKCS8EncodedKeySpecrsaPrivateKey=newPKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(base64EncodedRsaPK));// A pkcs#8 encoded unencrypted EC256 private key as a base64url string.Stringbase64EncodedEC256PK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";PKCS8EncodedKeySpecec256PrivateKey=newPKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));@TestpublicvoidtestVirtualOptions(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setIsUserVerified(true).setHasUserVerification(true).setIsUserConsenting(true).setTransport(VirtualAuthenticatorOptions.Transport.USB).setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);Assertions.assertEquals(6,options.toMap().size());}@TestpublicvoidtestCreateAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(0,credentialList.size());}@TestpublicvoidtestRemoveAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions();VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);((HasVirtualAuthenticator)driver).removeVirtualAuthenticator(authenticator);Assertions.assertThrows(InvalidArgumentException.class,authenticator::getCredentials);}@TestpublicvoidtestCreateAndAddResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2).setHasResidentKey(true).setHasUserVerification(true).setIsUserVerified(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.createResidentCredential(credentialId,"localhost",rsaPrivateKey,userHandle,/*signCount=*/0);authenticator.addCredential(residentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());}@TestpublicvoidtestAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);PKCS8EncodedKeySpecprivateKey=newPKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));byte[]credentialId={1,2,3,4};byte[]userHandle={1};Credentialcredential=Credential.createResidentCredential(credentialId,"localhost",privateKey,userHandle,/*signCount=*/0);Assertions.assertThrows(InvalidArgumentException.class,()->authenticator.addCredential(credential));}@TestpublicvoidtestCreateAndAddNonResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.createNonResidentCredential(credentialId,"localhost",ec256PrivateKey,/*signCount=*/0);authenticator.addCredential(nonResidentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());}@TestpublicvoidtestGetCredential(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2).setHasResidentKey(true).setHasUserVerification(true).setIsUserVerified(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.createResidentCredential(credentialId,"localhost",rsaPrivateKey,userHandle,/*signCount=*/0);authenticator.addCredential(residentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());Assertions.assertArrayEquals(rsaPrivateKey.getEncoded(),credential.getPrivateKey().getEncoded());}@TestpublicvoidtestRemoveCredential(){VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};Credentialcredential=Credential.createNonResidentCredential(credentialId,"localhost",rsaPrivateKey,0);authenticator.addCredential(credential);authenticator.removeCredential(credentialId);Assertions.assertEquals(0,authenticator.getCredentials().size());}@TestpublicvoidtestRemoveAllCredentials(){VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialresidentCredential=Credential.createNonResidentCredential(credentialId,"localhost",rsaPrivateKey,/*signCount=*/0);authenticator.addCredential(residentCredential);authenticator.removeAllCredentials();Assertions.assertEquals(0,authenticator.getCredentials().size());}@TestpublicvoidtestSetUserVerified(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setIsUserVerified(true);Assertions.assertTrue((boolean)options.toMap().get("isUserVerified"));}}
importpytestfrombase64importurlsafe_b64decode,urlsafe_b64encodefromselenium.common.exceptionsimportInvalidArgumentExceptionfromselenium.webdriver.chrome.webdriverimportWebDriverfromselenium.webdriver.common.virtual_authenticatorimport(Credential,VirtualAuthenticatorOptions,)BASE64__ENCODED_PK='''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TL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ypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct
lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
'''@pytest.fixture(scope="module",autouse=True)defdriver():yieldWebDriver()deftest_virtual_authenticator_options():options=VirtualAuthenticatorOptions()options.is_user_verified=Trueoptions.has_user_verification=Trueoptions.is_user_consenting=Trueoptions.transport=VirtualAuthenticatorOptions.Transport.USBoptions.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=Falseassertlen(options.to_dict())==6deftest_add_authenticator(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Get list of credentialscredential_list=driver.get_credentials()assertlen(credential_list)==0deftest_remove_authenticator(driver):# Create default virtual authenticator optionoptions=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Remove virtual authenticatordriver.remove_virtual_authenticator()assertdriver.virtual_authenticator_idisNonedeftest_create_and_add_resident_key(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.CTAP2options.has_resident_key=Trueoptions.has_user_verification=Trueoptions.is_user_verified=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(resident_credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1deftest_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parameterscredential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# Expect InvalidArgumentException withpytest.raises(InvalidArgumentException):driver.add_credential(credential)deftest_create_and_add_non_resident_key(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1deftest_get_credential(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.CTAP2options.has_resident_key=Trueoptions.has_user_verfied=Trueoptions.is_user_verified=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parameterscredential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1assertcredential_list[0].id==urlsafe_b64encode(credential_id).decode()deftest_remove_credential(driver):# Create default virtual authenticator optionsoptions=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# remove the credential created from virtual authenticatordriver.remove_credential(credential.id)# credential can also be removed using Byte Array# driver.remove_credential(credential_id) assertlen(driver.get_credentials())==0deftest_remove_all_credentials(driver):# Create default virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.has_resident_key=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(resident_credential)# remove all credentials in virtual authenticatordriver.remove_all_credentials()assertlen(driver.get_credentials())==0deftest_set_user_verified():# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.is_user_verified=Trueassertoptions.to_dict().get("isUserVerified")isTrue
packagedev.selenium.interactions;importdev.selenium.BaseChromeTest;importjava.security.spec.PKCS8EncodedKeySpec;importjava.util.Base64;importjava.util.List;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.InvalidArgumentException;importorg.openqa.selenium.virtualauthenticator.Credential;importorg.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;importorg.openqa.selenium.virtualauthenticator.VirtualAuthenticator;importorg.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;publicclassVirtualAuthenticatorTestextendsBaseChromeTest{/**
* A pkcs#8 encoded encrypted RSA private key as a base64url string.
*/privatefinalstaticStringbase64EncodedRsaPK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"+"GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"+"9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"+"vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"+"zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"+"XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"+"RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"+"QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"+"S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"+"ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"+"ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"+"OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"+"ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"+"hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"+"WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"+"NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"+"nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";privatefinalstaticPKCS8EncodedKeySpecrsaPrivateKey=newPKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(base64EncodedRsaPK));// A pkcs#8 encoded unencrypted EC256 private key as a base64url string.Stringbase64EncodedEC256PK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";PKCS8EncodedKeySpecec256PrivateKey=newPKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));@TestpublicvoidtestVirtualOptions(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setIsUserVerified(true).setHasUserVerification(true).setIsUserConsenting(true).setTransport(VirtualAuthenticatorOptions.Transport.USB).setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);Assertions.assertEquals(6,options.toMap().size());}@TestpublicvoidtestCreateAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(0,credentialList.size());}@TestpublicvoidtestRemoveAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions();VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);((HasVirtualAuthenticator)driver).removeVirtualAuthenticator(authenticator);Assertions.assertThrows(InvalidArgumentException.class,authenticator::getCredentials);}@TestpublicvoidtestCreateAndAddResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2).setHasResidentKey(true).setHasUserVerification(true).setIsUserVerified(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.createResidentCredential(credentialId,"localhost",rsaPrivateKey,userHandle,/*signCount=*/0);authenticator.addCredential(residentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());}@TestpublicvoidtestAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);PKCS8EncodedKeySpecprivateKey=newPKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));byte[]credentialId={1,2,3,4};byte[]userHandle={1};Credentialcredential=Credential.createResidentCredential(credentialId,"localhost",privateKey,userHandle,/*signCount=*/0);Assertions.assertThrows(InvalidArgumentException.class,()->authenticator.addCredential(credential));}@TestpublicvoidtestCreateAndAddNonResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.createNonResidentCredential(credentialId,"localhost",ec256PrivateKey,/*signCount=*/0);authenticator.addCredential(nonResidentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());}@TestpublicvoidtestGetCredential(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2).setHasResidentKey(true).setHasUserVerification(true).setIsUserVerified(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.createResidentCredential(credentialId,"localhost",rsaPrivateKey,userHandle,/*signCount=*/0);authenticator.addCredential(residentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());Assertions.assertArrayEquals(rsaPrivateKey.getEncoded(),credential.getPrivateKey().getEncoded());}@TestpublicvoidtestRemoveCredential(){VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};Credentialcredential=Credential.createNonResidentCredential(credentialId,"localhost",rsaPrivateKey,0);authenticator.addCredential(credential);authenticator.removeCredential(credentialId);Assertions.assertEquals(0,authenticator.getCredentials().size());}@TestpublicvoidtestRemoveAllCredentials(){VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialresidentCredential=Credential.createNonResidentCredential(credentialId,"localhost",rsaPrivateKey,/*signCount=*/0);authenticator.addCredential(residentCredential);authenticator.removeAllCredentials();Assertions.assertEquals(0,authenticator.getCredentials().size());}@TestpublicvoidtestSetUserVerified(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setIsUserVerified(true);Assertions.assertTrue((boolean)options.toMap().get("isUserVerified"));}}
usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingMicrosoft.IdentityModel.Tokens;usingOpenQA.Selenium;usingOpenQA.Selenium.VirtualAuth;usingstaticOpenQA.Selenium.VirtualAuth.VirtualAuthenticatorOptions;usingSystem.Collections.Generic;usingSystem;namespaceSeleniumDocs.VirtualAuthentication{ [TestClass]publicclassVirtualAuthenticatorTest:BaseChromeTest{//A pkcs#8 encoded encrypted RSA private key as a base64 string.privatestaticstringbase64EncodedRSAPK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"+"GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoE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+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"+"WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"+"NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"+"nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";privatestaticbyte[]bytes=System.Convert.FromBase64String(base64EncodedRSAPK);privatestringbase64EncodedPK=Base64UrlEncoder.Encode(bytes);// A pkcs#8 encoded unencrypted EC256 private key as a base64url string.privatestringbase64EncodedEC256PK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB"; [TestMethod]publicvoidVirtualOptionsShouldAllowSettingOptions(){// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetIsUserVerified(true).SetHasUserVerification(true).SetIsUserConsenting(true).SetTransport(VirtualAuthenticatorOptions.Transport.USB).SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);Assert.AreEqual(6,options.ToDictionary().Count);} [TestMethod]publicvoidShouldBeAbleToCreateAuthenticator(){// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);// Register a virtual authenticator((WebDriver)driver).AddVirtualAuthenticator(options);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(0,credentialList.Count);} [TestMethod]publicvoidShouldBeAbleToRemoveAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);StringvirtualAuthenticatorId=((WebDriver)driver).AddVirtualAuthenticator(options);((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);// Since the authenticator was removed, any operation using it will throw an errorAssert.ThrowsException<InvalidOperationException>(()=>((WebDriver)driver).GetCredentials());} [TestMethod]publicvoidShouldBeAbleToCreateAndAddResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(Protocol.CTAP2).SetHasResidentKey(true).SetHasUserVerification(true).SetIsUserVerified(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedPK,userHandle,0);((WebDriver)driver).AddCredential(residentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,credential.Id);} [TestMethod]publicvoidShouldNotAddResidentCredentialWhenAuthenticatorUsesU2FProtocol(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};Credentialcredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedEC256PK,userHandle,0);Assert.ThrowsException<WebDriverArgumentException>(()=>((WebDriver)driver).AddCredential(credential));} [TestMethod]publicvoidShouldBeAbleToCreateAndAddNonResidentKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,nonResidentCredential.Id);} [TestMethod]publicvoidShouldBeAbleToGetCredential(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(Protocol.CTAP2).SetHasResidentKey(true).SetHasUserVerification(true).SetIsUserVerified(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedPK,userHandle,0);((WebDriver)driver).AddCredential(residentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,residentCredential.Id);Assert.AreEqual(base64EncodedPK,credential.PrivateKey);} [TestMethod]publicvoidShouldBeAbleToRemoveCredential(){((WebDriver)driver).AddVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);((WebDriver)driver).RemoveCredential(credentialId);Assert.AreEqual(0,((WebDriver)driver).GetCredentials().Count);} [TestMethod]publicvoidShouldBeAbleToRemoveAllCredentias(){((WebDriver)driver).AddVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);((WebDriver)driver).RemoveAllCredentials();Assert.AreEqual(0,((WebDriver)driver).GetCredentials().Count);} [TestMethod]publicvoidShouldBeSetVerifiedOption(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetIsUserVerified(true);Assert.IsTrue((bool)options.ToDictionary()["isUserVerified"]);}}}
importpytestfrombase64importurlsafe_b64decode,urlsafe_b64encodefromselenium.common.exceptionsimportInvalidArgumentExceptionfromselenium.webdriver.chrome.webdriverimportWebDriverfromselenium.webdriver.common.virtual_authenticatorimport(Credential,VirtualAuthenticatorOptions,)BASE64__ENCODED_PK='''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV
oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ
FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq
GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0
+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM
8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD
/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ
5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe
pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol
L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d
xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi
uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8
K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct
lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
'''@pytest.fixture(scope="module",autouse=True)defdriver():yieldWebDriver()deftest_virtual_authenticator_options():options=VirtualAuthenticatorOptions()options.is_user_verified=Trueoptions.has_user_verification=Trueoptions.is_user_consenting=Trueoptions.transport=VirtualAuthenticatorOptions.Transport.USBoptions.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=Falseassertlen(options.to_dict())==6deftest_add_authenticator(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Get list of credentialscredential_list=driver.get_credentials()assertlen(credential_list)==0deftest_remove_authenticator(driver):# Create default virtual authenticator optionoptions=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Remove virtual authenticatordriver.remove_virtual_authenticator()assertdriver.virtual_authenticator_idisNonedeftest_create_and_add_resident_key(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.CTAP2options.has_resident_key=Trueoptions.has_user_verification=Trueoptions.is_user_verified=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(resident_credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1deftest_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parameterscredential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# Expect InvalidArgumentException withpytest.raises(InvalidArgumentException):driver.add_credential(credential)deftest_create_and_add_non_resident_key(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1deftest_get_credential(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.CTAP2options.has_resident_key=Trueoptions.has_user_verfied=Trueoptions.is_user_verified=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parameterscredential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1assertcredential_list[0].id==urlsafe_b64encode(credential_id).decode()deftest_remove_credential(driver):# Create default virtual authenticator optionsoptions=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# remove the credential created from virtual authenticatordriver.remove_credential(credential.id)# credential can also be removed using Byte Array# driver.remove_credential(credential_id) assertlen(driver.get_credentials())==0deftest_remove_all_credentials(driver):# Create default virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.has_resident_key=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(resident_credential)# remove all credentials in virtual authenticatordriver.remove_all_credentials()assertlen(driver.get_credentials())==0deftest_set_user_verified():# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.is_user_verified=Trueassertoptions.to_dict().get("isUserVerified")isTrue
const{Builder}=require("selenium-webdriver");const{Credential,VirtualAuthenticatorOptions,Transport,Protocol}=require("selenium-webdriver/lib/virtual_authenticator");constassert=require('assert')const{InvalidArgumentError}=require("selenium-webdriver/lib/error");describe('Virtual authenticator',function(){constBASE64_ENCODED_PK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV"+"oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ"+"FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq"+"GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0"+"+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM"+"8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD"+"/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQ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ZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";letoptions;letdriver;before(asyncfunction(){options=newVirtualAuthenticatorOptions();driver=awaitnewBuilder().forBrowser('chrome').build();});after(async()=>awaitdriver.quit());functionarraysEqual(array1,array2){return(array1.length===array2.length&&array1.every((item)=>array2.includes(item))&&array2.every((item)=>array1.includes(item)));}it('Register a virtual authenticator',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(false);// Register a virtual authenticator
awaitdriver.addVirtualAuthenticator(options);letcredentialList=awaitdriver.getCredentials();assert.equal(0,credentialList.length);});it('Remove authenticator',asyncfunction(){awaitdriver.addVirtualAuthenticator(options);awaitdriver.removeVirtualAuthenticator();// Since the authenticator was removed, any operation using it will throw an error
try{awaitdriver.getCredentials()}catch(e){if(einstanceofInvalidArgumentError){assert(true)}else{assert(false)}}});it('Createa and add residential key',asyncfunction(){options.setProtocol(Protocol['CTAP2']);options.setHasResidentKey(true);options.setHasUserVerification(true);options.setIsUserVerified(true);awaitdriver.addVirtualAuthenticator(options);letresidentCredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(residentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));});it('Add resident credential not supported when authenticator uses U2F protocol',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(true);awaitdriver.addVirtualAuthenticator(options);letcredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(base64EncodedPK,'base64').toString('binary'),0);try{awaitdriver.addCredential(credential)}catch(e){if(einstanceofInvalidArgumentError){assert(true)}else{assert(false)}}});it('Create and add non residential key',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(false);awaitdriver.addVirtualAuthenticator(options);letnonResidentCredential=newCredential().createNonResidentCredential(newUint8Array([1,2,3,4]),'localhost',Buffer.from(base64EncodedPK,'base64').toString('binary'),0);awaitdriver.addCredential(nonResidentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));});it('Get credential',asyncfunction(){options.setProtocol(Protocol['CTAP2']);options.setHasResidentKey(true);options.setHasUserVerification(true);options.setIsUserVerified(true);awaitdriver.addVirtualAuthenticator(options);letresidentCredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(residentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));assert.equal(BASE64_ENCODED_PK,Buffer.from(credentialList[0].privateKey(),'binary').toString('base64'));});it('Remove all credentials',asyncfunction(){awaitdriver.addVirtualAuthenticator(options);letnonResidentCredential=newCredential().createNonResidentCredential(newUint8Array([1,2,3,4]),'localhost',Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(nonResidentCredential);awaitdriver.removeAllCredentials();letcredentialList=awaitdriver.getCredentials();assert.equal(0,credentialList.length);});it('Set is user verified',asyncfunction(){options.setIsUserVerified(true);assert.equal(options.getIsUserVerified(),true);});});
packagedev.selenium.interactions;importdev.selenium.BaseChromeTest;importjava.security.spec.PKCS8EncodedKeySpec;importjava.util.Base64;importjava.util.List;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.InvalidArgumentException;importorg.openqa.selenium.virtualauthenticator.Credential;importorg.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;importorg.openqa.selenium.virtualauthenticator.VirtualAuthenticator;importorg.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;publicclassVirtualAuthenticatorTestextendsBaseChromeTest{/**
* A pkcs#8 encoded encrypted RSA private key as a base64url string.
*/privatefinalstaticStringbase64EncodedRsaPK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"+"GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"+"9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"+"vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"+"zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"+"XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"+"RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"+"QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"+"S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"+"ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"+"ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"+"OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"+"ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"+"hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"+"WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"+"NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"+"nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";privatefinalstaticPKCS8EncodedKeySpecrsaPrivateKey=newPKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(base64EncodedRsaPK));// A pkcs#8 encoded unencrypted EC256 private key as a base64url string.Stringbase64EncodedEC256PK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";PKCS8EncodedKeySpecec256PrivateKey=newPKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));@TestpublicvoidtestVirtualOptions(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setIsUserVerified(true).setHasUserVerification(true).setIsUserConsenting(true).setTransport(VirtualAuthenticatorOptions.Transport.USB).setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);Assertions.assertEquals(6,options.toMap().size());}@TestpublicvoidtestCreateAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(0,credentialList.size());}@TestpublicvoidtestRemoveAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions();VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);((HasVirtualAuthenticator)driver).removeVirtualAuthenticator(authenticator);Assertions.assertThrows(InvalidArgumentException.class,authenticator::getCredentials);}@TestpublicvoidtestCreateAndAddResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2).setHasResidentKey(true).setHasUserVerification(true).setIsUserVerified(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.createResidentCredential(credentialId,"localhost",rsaPrivateKey,userHandle,/*signCount=*/0);authenticator.addCredential(residentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());}@TestpublicvoidtestAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);PKCS8EncodedKeySpecprivateKey=newPKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));byte[]credentialId={1,2,3,4};byte[]userHandle={1};Credentialcredential=Credential.createResidentCredential(credentialId,"localhost",privateKey,userHandle,/*signCount=*/0);Assertions.assertThrows(InvalidArgumentException.class,()->authenticator.addCredential(credential));}@TestpublicvoidtestCreateAndAddNonResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.U2F).setHasResidentKey(false);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.createNonResidentCredential(credentialId,"localhost",ec256PrivateKey,/*signCount=*/0);authenticator.addCredential(nonResidentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());}@TestpublicvoidtestGetCredential(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2).setHasResidentKey(true).setHasUserVerification(true).setIsUserVerified(true);VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.createResidentCredential(credentialId,"localhost",rsaPrivateKey,userHandle,/*signCount=*/0);authenticator.addCredential(residentCredential);List<Credential>credentialList=authenticator.getCredentials();Assertions.assertEquals(1,credentialList.size());Credentialcredential=credentialList.get(0);Assertions.assertArrayEquals(credentialId,credential.getId());Assertions.assertArrayEquals(rsaPrivateKey.getEncoded(),credential.getPrivateKey().getEncoded());}@TestpublicvoidtestRemoveCredential(){VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};Credentialcredential=Credential.createNonResidentCredential(credentialId,"localhost",rsaPrivateKey,0);authenticator.addCredential(credential);authenticator.removeCredential(credentialId);Assertions.assertEquals(0,authenticator.getCredentials().size());}@TestpublicvoidtestRemoveAllCredentials(){VirtualAuthenticatorauthenticator=((HasVirtualAuthenticator)driver).addVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialresidentCredential=Credential.createNonResidentCredential(credentialId,"localhost",rsaPrivateKey,/*signCount=*/0);authenticator.addCredential(residentCredential);authenticator.removeAllCredentials();Assertions.assertEquals(0,authenticator.getCredentials().size());}@TestpublicvoidtestSetUserVerified(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().setIsUserVerified(true);Assertions.assertTrue((boolean)options.toMap().get("isUserVerified"));}}
usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingMicrosoft.IdentityModel.Tokens;usingOpenQA.Selenium;usingOpenQA.Selenium.VirtualAuth;usingstaticOpenQA.Selenium.VirtualAuth.VirtualAuthenticatorOptions;usingSystem.Collections.Generic;usingSystem;namespaceSeleniumDocs.VirtualAuthentication{ [TestClass]publicclassVirtualAuthenticatorTest:BaseChromeTest{//A pkcs#8 encoded encrypted RSA private key as a base64 string.privatestaticstringbase64EncodedRSAPK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"+"GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2r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3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"+"WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"+"NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"+"nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";privatestaticbyte[]bytes=System.Convert.FromBase64String(base64EncodedRSAPK);privatestringbase64EncodedPK=Base64UrlEncoder.Encode(bytes);// A pkcs#8 encoded unencrypted EC256 private key as a base64url string.privatestringbase64EncodedEC256PK="MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"+"hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB"; [TestMethod]publicvoidVirtualOptionsShouldAllowSettingOptions(){// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetIsUserVerified(true).SetHasUserVerification(true).SetIsUserConsenting(true).SetTransport(VirtualAuthenticatorOptions.Transport.USB).SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);Assert.AreEqual(6,options.ToDictionary().Count);} [TestMethod]publicvoidShouldBeAbleToCreateAuthenticator(){// Create virtual authenticator optionsVirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);// Register a virtual authenticator((WebDriver)driver).AddVirtualAuthenticator(options);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(0,credentialList.Count);} [TestMethod]publicvoidShouldBeAbleToRemoveAuthenticator(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);StringvirtualAuthenticatorId=((WebDriver)driver).AddVirtualAuthenticator(options);((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);// Since the authenticator was removed, any operation using it will throw an errorAssert.ThrowsException<InvalidOperationException>(()=>((WebDriver)driver).GetCredentials());} [TestMethod]publicvoidShouldBeAbleToCreateAndAddResidentialKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(Protocol.CTAP2).SetHasResidentKey(true).SetHasUserVerification(true).SetIsUserVerified(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedPK,userHandle,0);((WebDriver)driver).AddCredential(residentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,credential.Id);} [TestMethod]publicvoidShouldNotAddResidentCredentialWhenAuthenticatorUsesU2FProtocol(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};Credentialcredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedEC256PK,userHandle,0);Assert.ThrowsException<WebDriverArgumentException>(()=>((WebDriver)driver).AddCredential(credential));} [TestMethod]publicvoidShouldBeAbleToCreateAndAddNonResidentKey(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F).SetHasResidentKey(false);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,nonResidentCredential.Id);} [TestMethod]publicvoidShouldBeAbleToGetCredential(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetProtocol(Protocol.CTAP2).SetHasResidentKey(true).SetHasUserVerification(true).SetIsUserVerified(true);((WebDriver)driver).AddVirtualAuthenticator(options);byte[]credentialId={1,2,3,4};byte[]userHandle={1};CredentialresidentCredential=Credential.CreateResidentCredential(credentialId,"localhost",base64EncodedPK,userHandle,0);((WebDriver)driver).AddCredential(residentCredential);List<Credential>credentialList=((WebDriver)driver).GetCredentials();Assert.AreEqual(1,credentialList.Count);Credentialcredential=credentialList[0];CollectionAssert.AreEqual(credentialId,residentCredential.Id);Assert.AreEqual(base64EncodedPK,credential.PrivateKey);} [TestMethod]publicvoidShouldBeAbleToRemoveCredential(){((WebDriver)driver).AddVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);((WebDriver)driver).RemoveCredential(credentialId);Assert.AreEqual(0,((WebDriver)driver).GetCredentials().Count);} [TestMethod]publicvoidShouldBeAbleToRemoveAllCredentias(){((WebDriver)driver).AddVirtualAuthenticator(newVirtualAuthenticatorOptions());byte[]credentialId={1,2,3,4};CredentialnonResidentCredential=Credential.CreateNonResidentCredential(credentialId,"localhost",base64EncodedEC256PK,0);((WebDriver)driver).AddCredential(nonResidentCredential);((WebDriver)driver).RemoveAllCredentials();Assert.AreEqual(0,((WebDriver)driver).GetCredentials().Count);} [TestMethod]publicvoidShouldBeSetVerifiedOption(){VirtualAuthenticatorOptionsoptions=newVirtualAuthenticatorOptions().SetIsUserVerified(true);Assert.IsTrue((bool)options.ToDictionary()["isUserVerified"]);}}}
importpytestfrombase64importurlsafe_b64decode,urlsafe_b64encodefromselenium.common.exceptionsimportInvalidArgumentExceptionfromselenium.webdriver.chrome.webdriverimportWebDriverfromselenium.webdriver.common.virtual_authenticatorimport(Credential,VirtualAuthenticatorOptions,)BASE64__ENCODED_PK='''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV
oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ
FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq
GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0
+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM
8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD
/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ
5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe
pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol
L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d
xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi
uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8
K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct
lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
'''@pytest.fixture(scope="module",autouse=True)defdriver():yieldWebDriver()deftest_virtual_authenticator_options():options=VirtualAuthenticatorOptions()options.is_user_verified=Trueoptions.has_user_verification=Trueoptions.is_user_consenting=Trueoptions.transport=VirtualAuthenticatorOptions.Transport.USBoptions.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=Falseassertlen(options.to_dict())==6deftest_add_authenticator(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Get list of credentialscredential_list=driver.get_credentials()assertlen(credential_list)==0deftest_remove_authenticator(driver):# Create default virtual authenticator optionoptions=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# Remove virtual authenticatordriver.remove_virtual_authenticator()assertdriver.virtual_authenticator_idisNonedeftest_create_and_add_resident_key(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.CTAP2options.has_resident_key=Trueoptions.has_user_verification=Trueoptions.is_user_verified=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(resident_credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1deftest_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parameterscredential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# Expect InvalidArgumentException withpytest.raises(InvalidArgumentException):driver.add_credential(credential)deftest_create_and_add_non_resident_key(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.U2Foptions.has_resident_key=False# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1deftest_get_credential(driver):# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.protocol=VirtualAuthenticatorOptions.Protocol.CTAP2options.has_resident_key=Trueoptions.has_user_verfied=Trueoptions.is_user_verified=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parameterscredential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# get list of all the registered credentials credential_list=driver.get_credentials()assertlen(credential_list)==1assertcredential_list[0].id==urlsafe_b64encode(credential_id).decode()deftest_remove_credential(driver):# Create default virtual authenticator optionsoptions=VirtualAuthenticatorOptions()# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Non Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a non resident credential using above parameterscredential=Credential.create_non_resident_credential(credential_id,rp_id,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(credential)# remove the credential created from virtual authenticatordriver.remove_credential(credential.id)# credential can also be removed using Byte Array# driver.remove_credential(credential_id) assertlen(driver.get_credentials())==0deftest_remove_all_credentials(driver):# Create default virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.has_resident_key=True# Register a virtual authenticatordriver.add_virtual_authenticator(options)# parameters for Resident Credentialcredential_id=bytearray({1,2,3,4})rp_id="localhost"user_handle=bytearray({1})privatekey=urlsafe_b64decode(BASE64__ENCODED_PK)sign_count=0# create a resident credential using above parametersresident_credential=Credential.create_resident_credential(credential_id,rp_id,user_handle,privatekey,sign_count)# add the credential created to virtual authenticatordriver.add_credential(resident_credential)# remove all credentials in virtual authenticatordriver.remove_all_credentials()assertlen(driver.get_credentials())==0deftest_set_user_verified():# Create virtual authenticator optionsoptions=VirtualAuthenticatorOptions()options.is_user_verified=Trueassertoptions.to_dict().get("isUserVerified")isTrue
const{Builder}=require("selenium-webdriver");const{Credential,VirtualAuthenticatorOptions,Transport,Protocol}=require("selenium-webdriver/lib/virtual_authenticator");constassert=require('assert')const{InvalidArgumentError}=require("selenium-webdriver/lib/error");describe('Virtual authenticator',function(){constBASE64_ENCODED_PK="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"+"MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV"+"oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ"+"FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq"+"GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0"+"+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM"+"8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD"+"/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/Xcmp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2jwU"+"RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";letoptions;letdriver;before(asyncfunction(){options=newVirtualAuthenticatorOptions();driver=awaitnewBuilder().forBrowser('chrome').build();});after(async()=>awaitdriver.quit());functionarraysEqual(array1,array2){return(array1.length===array2.length&&array1.every((item)=>array2.includes(item))&&array2.every((item)=>array1.includes(item)));}it('Register a virtual authenticator',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(false);// Register a virtual authenticator
awaitdriver.addVirtualAuthenticator(options);letcredentialList=awaitdriver.getCredentials();assert.equal(0,credentialList.length);});it('Remove authenticator',asyncfunction(){awaitdriver.addVirtualAuthenticator(options);awaitdriver.removeVirtualAuthenticator();// Since the authenticator was removed, any operation using it will throw an error
try{awaitdriver.getCredentials()}catch(e){if(einstanceofInvalidArgumentError){assert(true)}else{assert(false)}}});it('Createa and add residential key',asyncfunction(){options.setProtocol(Protocol['CTAP2']);options.setHasResidentKey(true);options.setHasUserVerification(true);options.setIsUserVerified(true);awaitdriver.addVirtualAuthenticator(options);letresidentCredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(residentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));});it('Add resident credential not supported when authenticator uses U2F protocol',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(true);awaitdriver.addVirtualAuthenticator(options);letcredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(base64EncodedPK,'base64').toString('binary'),0);try{awaitdriver.addCredential(credential)}catch(e){if(einstanceofInvalidArgumentError){assert(true)}else{assert(false)}}});it('Create and add non residential key',asyncfunction(){options.setProtocol(Protocol['U2F']);options.setHasResidentKey(false);awaitdriver.addVirtualAuthenticator(options);letnonResidentCredential=newCredential().createNonResidentCredential(newUint8Array([1,2,3,4]),'localhost',Buffer.from(base64EncodedPK,'base64').toString('binary'),0);awaitdriver.addCredential(nonResidentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));});it('Get credential',asyncfunction(){options.setProtocol(Protocol['CTAP2']);options.setHasResidentKey(true);options.setHasUserVerification(true);options.setIsUserVerified(true);awaitdriver.addVirtualAuthenticator(options);letresidentCredential=newCredential().createResidentCredential(newUint8Array([1,2,3,4]),'localhost',newUint8Array([1]),Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(residentCredential);letcredentialList=awaitdriver.getCredentials();assert.equal(1,credentialList.length);letcredential_id=credentialList[0].id();lettest_id=newUint8Array([1,2,3,4]);assert(arraysEqual(credential_id,test_id));assert.equal(BASE64_ENCODED_PK,Buffer.from(credentialList[0].privateKey(),'binary').toString('base64'));});it('Remove all credentials',asyncfunction(){awaitdriver.addVirtualAuthenticator(options);letnonResidentCredential=newCredential().createNonResidentCredential(newUint8Array([1,2,3,4]),'localhost',Buffer.from(BASE64_ENCODED_PK,'base64').toString('binary'),0);awaitdriver.addCredential(nonResidentCredential);awaitdriver.removeAllCredentials();letcredentialList=awaitdriver.getCredentials();assert.equal(0,credentialList.length);});it('Set is user verified',asyncfunction(){options.setIsUserVerified(true);assert.equal(options.getIsUserVerified(),true);});});