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()}}
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()}}
全てのクッキーの削除
現在のブラウジングコンテキストの全ての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();});});
//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')# Switch to the framedriver.switch_to.frameiframe# Now, Click on the buttondriver.find_element(:tag_name,'button').click
// Store the web element
constiframe=driver.findElement(By.css('#modal > iframe'));// Switch to the frame
awaitdriver.switchTo().frame(iframe);// Now we can click the button
awaitdriver.findElement(By.css('button')).click();
//Store the web element
valiframe=driver.findElement(By.cssSelector("#modal>iframe"))//Switch to the frame
driver.switchTo().frame(iframe)//Now we can click the button
driver.findElement(By.tagName("button")).click()
//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();}}}
// Using the ID
awaitdriver.switchTo().frame('buttonframe');// Or using the name instead
awaitdriver.switchTo().frame('myframe');// Now we can click the button
awaitdriver.findElement(By.css('button')).click();
//Using the ID
driver.switchTo().frame("buttonframe")//Or using the name instead
driver.switchTo().frame("myframe")//Now we can click the button
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 the second framedriver.switch_to.frame(1)
//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();}}}
// Switches to the second frame
awaitdriver.switchTo().frame(1);
// Switches to the second frame
driver.switchTo().frame(1)
Frameを終了する
iFrameまたはFrameセットを終了するには、次のようにデフォルトのコンテンツに切り替えます。
//leave framedriver.switchTo().defaultContent();
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 back to default contentdriver.switch_to.default_content()
//leave framedriver.SwitchTo().DefaultContent();
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();}}}
# Return to the top leveldriver.switch_to.default_content
// Return to the top level
awaitdriver.switchTo().defaultContent();
// Return to the top level
driver.switchTo().defaultContent()
5 - Print Page
Printing a webpage is a common task, whether for sharing information or maintaining archives.
Selenium simplifies this process through its PrintOptions, PrintsPage, and browsingContext
classes, which provide a flexible and intuitive interface for automating the printing of web pages.
These classes enable you to configure printing preferences, such as page layout, margins, and scaling,
ensuring that the output meets your specific requirements.
Configuring
Orientation
Using the getOrientation() and setOrientation() methods, you can get/set the page orientation — either PORTRAIT or LANDSCAPE.
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
Using the getPageSize() and setPageSize() methods, you can get/set the paper size to print — e.g. “A0”, “A6”, “Legal”, “Tabloid”, etc.
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
Using the getPageMargin() and setPageMargin() methods, you can set the margin sizes of the page you wish to print — i.e. top, bottom, left, and right margins.
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
Once you’ve configured your PrintOptions, you’re ready to print the page. To do this,
you can invoke the print function, which generates a PDF representation of the web page.
The resulting PDF can be saved to your local storage for further use or distribution.
Using PrintsPage(), the print command will return the PDF data in base64-encoded format, which can be decoded
and written to a file in your desired location, and using BrowsingContext() will return a String.
There may currently be multiple implementations depending on your language of choice. For example, with Java you
have the ability to print using either BrowingContext() or PrintsPage(). Both take PrintOptions() objects as a
parameter.
Note: BrowsingContext() is part of Selenium’s BiDi implementation. To enable BiDi see Enabling Bidi
// 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}}}
//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}}
fromseleniumimportwebdriverfromselenium.webdriver.support.uiimportWebDriverWaitfromselenium.webdriver.supportimportexpected_conditionsasEC# Start the driverwithwebdriver.Firefox()asdriver:# Open URLdriver.get("https://seleniumhq.github.io")# Setup wait for laterwait=WebDriverWait(driver,10)# Store the ID of the original windoworiginal_window=driver.current_window_handle# Check we don't have other windows open alreadyassertlen(driver.window_handles)==1# Click the link which opens in a new windowdriver.find_element(By.LINK_TEXT,"new window").click()# Wait for the new window or tabwait.until(EC.number_of_windows_to_be(2))# Loop through until we find a new window handleforwindow_handleindriver.window_handles:ifwindow_handle!=original_window:driver.switch_to.window(window_handle)break# Wait for the new tab to finish loading contentwait.until(EC.title_is("SeleniumHQ Browser Automation"))
//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}}}
#Store the ID of the original windoworiginal_window=driver.window_handle#Check we don't have other windows open alreadyassert(driver.window_handles.length==1,'Expected one window')#Click the link which opens in a new windowdriver.find_element(link:'new window').click#Wait for the new window or tabwait.until{driver.window_handles.length==2}#Loop through until we find a new window handledriver.window_handles.eachdo|handle|ifhandle!=original_windowdriver.switch_to.windowhandlebreakendend#Wait for the new tab to finish loading contentwait.until{driver.title=='Selenium documentation'}
//Store the ID of the original window
constoriginalWindow=awaitdriver.getWindowHandle();//Check we don't have other windows open already
assert((awaitdriver.getAllWindowHandles()).length===1);//Click the link which opens in a new window
awaitdriver.findElement(By.linkText('new window')).click();//Wait for the new window or tab
awaitdriver.wait(async()=>(awaitdriver.getAllWindowHandles()).length===2,10000);//Loop through until we find a new window handle
constwindows=awaitdriver.getAllWindowHandles();windows.forEach(asynchandle=>{if(handle!==originalWindow){awaitdriver.switchTo().window(handle);}});//Wait for the new tab to finish loading content
awaitdriver.wait(until.titleIs('Selenium documentation'),10000);
//Store the ID of the original window
valoriginalWindow=driver.getWindowHandle()//Check we don't have other windows open already
assert(driver.getWindowHandles().size()===1)//Click the link which opens in a new window
driver.findElement(By.linkText("new window")).click()//Wait for the new window or tab
wait.until(numberOfWindowsToBe(2))//Loop through until we find a new window handle
for(windowHandleindriver.getWindowHandles()){if(!originalWindow.contentEquals(windowHandle)){driver.switchTo().window(windowHandle)break}}//Wait for the new tab to finish loading content
wait.until(titleIs("Selenium documentation"))
//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}}
#Close the tab or windowdriver.close()#Switch back to the old tab or windowdriver.switch_to.window(original_window)
//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.switch_to.new_window('tab')# Opens a new window and switches to new windowdriver.switch_to.new_window('window')
//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);});});
// Opens a new tab and switches to new tab
driver.switchTo().newWindow(WindowType.TAB)// Opens a new window and switches to new window
driver.switchTo().newWindow(WindowType.WINDOW)
セッションの終了時にブラウザーを終了する
ブラウザーセッションを終了したら、closeではなく、quitを呼び出す必要があります。
//quitting driverdriver.quit();//closeallwindows
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}}
//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}}}
/**
* Example using JUnit
* https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/AfterAll.html
*/@AfterAllpublicstaticvoidtearDown(){driver.quit();}
/*
Example using Visual Studio's UnitTesting
https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.aspx
*/[TestCleanup]publicvoidTearDown(){driver.Quit();}
//Access each dimension individuallyintwidth=driver.manage().window().getSize().getWidth();intheight=driver.manage().window().getSize().getHeight();//Or store the dimensions and query them laterDimensionsize=driver.manage().window().getSize();intwidth1=size.getWidth();intheight1=size.getHeight();
# Access each dimension individuallywidth=driver.get_window_size().get("width")height=driver.get_window_size().get("height")# Or store the dimensions and query them latersize=driver.get_window_size()width1=size.get("width")height1=size.get("height")
//Access each dimension individuallyintwidth=driver.Manage().Window.Size.Width;intheight=driver.Manage().Window.Size.Height;//Or store the dimensions and query them laterSystem.Drawing.Sizesize=driver.Manage().Window.Size;intwidth1=size.Width;intheight1=size.Height;
# Access each dimension individuallywidth=driver.manage.window.size.widthheight=driver.manage.window.size.height# Or store the dimensions and query them latersize=driver.manage.window.sizewidth1=size.widthheight1=size.height
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 individually
valwidth=driver.manage().window().size.widthvalheight=driver.manage().window().size.height//Or store the dimensions and query them later
valsize=driver.manage().window().sizevalwidth1=size.widthvalheight1=size.height
// Access each dimension individuallyintx=driver.manage().window().getPosition().getX();inty=driver.manage().window().getPosition().getY();// Or store the dimensions and query them laterPointposition=driver.manage().window().getPosition();intx1=position.getX();inty1=position.getY();
# Access each dimension individuallyx=driver.get_window_position().get('x')y=driver.get_window_position().get('y')# Or store the dimensions and query them laterposition=driver.get_window_position()x1=position.get('x')y1=position.get('y')
//Access each dimension individuallyintx=driver.Manage().Window.Position.X;inty=driver.Manage().Window.Position.Y;//Or store the dimensions and query them laterPointposition=driver.Manage().Window.Position;intx1=position.X;inty1=position.Y;
#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);});});
// Access each dimension individually
valx=driver.manage().window().position.xvaly=driver.manage().window().position.y// Or store the dimensions and query them later
valposition=driver.manage().window().positionvalx1=position.xvaly1=position.y
## ウィンドウの位置設定
選択した位置にウィンドウを移動します。
// Move the window to the top left of the primary monitordriver.manage().window().setPosition(newPoint(0,0));
# Move the window to the top left of the primary monitordriver.set_window_position(0,0)
// Move the window to the top left of the primary monitordriver.Manage().Window.Position=newPoint(0,0);
driver.manage.window.move_to(0,0)
// Move the window to the top left of the primary monitor
awaitdriver.manage().window().setRect({x:0,y:0});
// Move the window to the top left of the primary monitor
driver.manage().window().position=Point(0,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);});});
Page being translated from English to Japanese.
Do you speak Japanese? Help us to translate
it by sending us pull requests!
Web applications can enable a public key-based authentication mechanism known as Web Authentication to authenticate users in a passwordless manner.
Web Authentication defines APIs that allows a user to create a public-key credential and register it with an authenticator.
An authenticator can be a hardware device or a software entity that stores user’s public-key credentials and retrieves them on request.
As the name suggests, Virtual Authenticator emulates such authenticators for testing.
Virtual Authenticator Options
A Virtual Authenticatior has a set of properties.
These properties are mapped as VirtualAuthenticatorOptions in the Selenium bindings.
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+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/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
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="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()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/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
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/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==";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/"+"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+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+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/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==";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/"+"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+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+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/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==";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/"+"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+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
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/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==";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/"+"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+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/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/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==";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/"+"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+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/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/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==";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/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"]);}}}
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/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
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+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/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/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==";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/"+"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+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/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/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==";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);});});