Você pode ler o título da página atual no navegador:
1416
Show full example
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);});});
Você pode ler a URL atual na barra de endereço do navegador usando:
2527
Show full example
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);});});
A primeira coisa que você vai querer fazer depois de iniciar um navegador é
abrir o seu site. Isso pode ser feito em uma única linha, utilize o seguinte comando:
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");});});
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");});});
WebDriver fornece uma API para trabalhar com os três tipos nativos de
mensagens pop-up oferecidas pelo JavaScript. Esses pop-ups são estilizados pelo
navegador e oferecem personalização limitada.
Alertas
O mais simples deles é referido como um alerta, que mostra um
mensagem personalizada e um único botão que dispensa o alerta, rotulado
na maioria dos navegadores como OK. Ele também pode ser dispensado na maioria dos navegadores
pressionando o botão Fechar, mas isso sempre fará a mesma coisa que
o botão OK. Veja um exemplo de alerta .
O WebDriver pode obter o texto do pop-up e aceitar ou dispensar esses
alertas.
5058
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();}}
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()
# 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()
Confirmação
Uma caixa de confirmação é semelhante a um alerta, exceto que o usuário também pode escolher
cancelar a mensagem. Veja
uma amostra de confirmação .
Este exemplo também mostra uma abordagem diferente para armazenar um alerta:
6573
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();}}
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();
2736
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()
Prompt
Os prompts são semelhantes às caixas de confirmação, exceto que também incluem um texto de
entrada. Semelhante a trabalhar com elementos de formulário, você pode
usar o sendKeys do WebDriver para preencher uma resposta. Isso substituirá
completamente o espaço de texto de exemplo. Pressionar o botão Cancelar não enviará nenhum texto.
Veja um exemplo de prompt .
7989
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();}}
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();
4049
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 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()
3 - Trabalhando com cookies
Um cookie é um pequeno pedaço de dado enviado de um site e armazenado no seu computador.
Os cookies são usados principalmente para reconhecer o usuário e carregar as informações armazenadas.
A API WebDriver fornece uma maneira de interagir com cookies com métodos integrados:
Add Cookie
É usado para adicionar um cookie ao contexto de navegação atual.
Add Cookie aceita apenas um conjunto de objetos JSON serializáveis definidos. Aqui é o link para a lista de valores-chave JSON aceitos.
Em primeiro lugar, você precisa estar no domínio para qual o cookie será
valido. Se você está tentando predefinir cookies antes
de começar a interagir com um site e sua página inicial é grande / demora um pouco para carregar
uma alternativa é encontrar uma página menor no site (normalmente a página 404 é pequena,
por exemplo http://example.com/some404page)
2933
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();}}
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'# Adds the cookie into current browser contextdriver.manage.add_cookie(name:"key",value:"value")ensuredriver.quitend
1719
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()}}
Get Named Cookie
Retorna os dados do cookie serializado correspondentes ao nome do cookie entre todos os cookies associados.
3743
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();}}
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:"foo",value:"bar")# Get cookie details with named cookie 'foo'putsdriver.manage.cookie_named('foo')ensuredriver.quitend
3439
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()}}
Get All Cookies
Retorna ‘dados de cookie serializados com sucesso’ para o contexto de navegação atual.
Se o navegador não estiver mais disponível, ele retornará um erro.
5167
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();}}
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")# Get all available cookiesputsdriver.manage.all_cookiesensuredriver.quitend
4852
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()}}
Delete Cookie
Exclui os dados do cookie que correspondem ao nome do cookie fornecido.
7378
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();}}
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
6063
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"))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()}}
Delete All Cookies
Exclui todos os cookies do contexto de navegação atual.
99106
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();}}
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")# deletes all cookiesdriver.manage.delete_all_cookiesensuredriver.quitend
7679
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"))// deletes all cookies
driver.manage().deleteAllCookies()}finally{driver.quit()}}
Same-Site Cookie Attribute
Permite que um usuário instrua os navegadores a controlar se os cookies
são enviados junto com a solicitação iniciada por sites de terceiros.
É usado para evitar ataques CSRF (Cross-Site Request Forgery).
O atributo de cookie Same-Site aceita dois parâmetros como instruções
Strict:
Quando o atributo sameSite é definido como Strict,
o cookie não será enviado junto com
solicitações iniciadas por sites de terceiros.
Lax:
Quando você define um atributo cookie sameSite como Lax,
o cookie será enviado junto com uma solicitação GET
iniciada por um site de terceiros.
Nota: a partir de agora, esse recurso está disponível no Chrome (versão 80+),
Firefox (versão 79+) e funciona com Selenium 4 e versões posteriores.
111122
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();}}
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
2327
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();});});
Frames são um meio obsoleto de construir um layout de site a partir de
vários documentos no mesmo domínio. É improvável que você trabalhe com eles
a menos que você esteja trabalhando com um webapp pré-HTML5. Iframes permitem
a inserção de um documento de um domínio totalmente diferente, e são
ainda comumente usado.
Se você precisa trabalhar com frames ou iframes, o WebDriver permite que você
trabalhe com eles da mesma maneira. Considere um botão dentro de um iframe.
Se inspecionarmos o elemento usando as ferramentas de desenvolvimento do navegador, podemos
ver o seguinte:
# This won't workdriver.find_element(:tag_name,'button').click
// This won't work
awaitdriver.findElement(By.css('button')).click();
//This won't work
driver.findElement(By.tagName("button")).click()
No entanto, se não houver botões fora do iframe, você pode
em vez disso, obter um erro no such element. Isso acontece porque o Selenium é
ciente apenas dos elementos no documento de nível superior. Para interagir com
o botão, precisamos primeiro mudar para o quadro, de forma semelhante
a como alternamos janelas. WebDriver oferece três maneiras de mudar para
um frame.
Usando um WebElement
Alternar usando um WebElement é a opção mais flexível. Você pode
encontrar o quadro usando seu seletor preferido e mudar para ele.
3747
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();}}
# Licensed to the Software Freedom Conservancy (SFC) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information# regarding copyright ownership. The SFC licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0# Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied. See the License for the# specific language governing permissions and limitations# under the License.fromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy#set chrome and launch web pagedriver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/iframes.html")# --- Switch to iframe using WebElement ---iframe=driver.find_element(By.ID,"iframe1")driver.switch_to.frame(iframe)assert"We Leave From Here"indriver.page_sourceemail_element=driver.find_element(By.ID,"email")email_element.send_keys("admin@selenium.dev")email_element.clear()driver.switch_to.default_content()# --- Switch to iframe using name or ID ---iframe1=driver.find_element(By.NAME,"iframe1-name")# (This line doesn't switch, just locates)driver.switch_to.frame(iframe)assert"We Leave From Here"indriver.page_sourceemail=driver.find_element(By.ID,"email")email.send_keys("admin@selenium.dev")email.clear()driver.switch_to.default_content()# --- Switch to iframe using index ---driver.switch_to.frame(0)assert"We Leave From Here"indriver.page_source# --- Final page content check ---driver.switch_to.default_content()assert"This page has iframes"indriver.page_source#quit the driverdriver.quit()#demo code for conference
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{ [TestClass]publicclassFramesTest{ [TestMethod]publicvoidTestFrames(){WebDriverdriver=newChromeDriver();driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromMilliseconds(500);// Navigate to Urldriver.Url="https://www.selenium.dev/selenium/web/iframes.html";//switch To IFrame using Web ElementIWebElementiframe=driver.FindElement(By.Id("iframe1"));//Switch to the framedriver.SwitchTo().Frame(iframe);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));//Now we can type text into email fieldIWebElementemailE=driver.FindElement(By.Id("email"));emailE.SendKeys("admin@selenium.dev");emailE.Clear();driver.SwitchTo().DefaultContent();//switch To IFrame using name or iddriver.FindElement(By.Name("iframe1-name"));//Switch to the framedriver.SwitchTo().Frame(iframe);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));IWebElementemail=driver.FindElement(By.Id("email"));//Now we can type text into email fieldemail.SendKeys("admin@selenium.dev");email.Clear();driver.SwitchTo().DefaultContent();//switch To IFrame using indexdriver.SwitchTo().Frame(0);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));//leave framedriver.SwitchTo().DefaultContent();Assert.AreEqual(true,driver.PageSource.Contains("This page has iframes"));//quit the browserdriver.Quit();}}}
# 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()
Usando um name ou ID
Se o seu frame ou iframe tiver um atributo id ou name, ele pode ser
usado alternativamente. Se o name ou ID não for exclusivo na página, o
primeiro encontrado será utilizado.
4959
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();}}
# Licensed to the Software Freedom Conservancy (SFC) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information# regarding copyright ownership. The SFC licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0# Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied. See the License for the# specific language governing permissions and limitations# under the License.fromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy#set chrome and launch web pagedriver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/iframes.html")# --- Switch to iframe using WebElement ---iframe=driver.find_element(By.ID,"iframe1")driver.switch_to.frame(iframe)assert"We Leave From Here"indriver.page_sourceemail_element=driver.find_element(By.ID,"email")email_element.send_keys("admin@selenium.dev")email_element.clear()driver.switch_to.default_content()# --- Switch to iframe using name or ID ---iframe1=driver.find_element(By.NAME,"iframe1-name")# (This line doesn't switch, just locates)driver.switch_to.frame(iframe)assert"We Leave From Here"indriver.page_sourceemail=driver.find_element(By.ID,"email")email.send_keys("admin@selenium.dev")email.clear()driver.switch_to.default_content()# --- Switch to iframe using index ---driver.switch_to.frame(0)assert"We Leave From Here"indriver.page_source# --- Final page content check ---driver.switch_to.default_content()assert"This page has iframes"indriver.page_source#quit the driverdriver.quit()#demo code for conference
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{ [TestClass]publicclassFramesTest{ [TestMethod]publicvoidTestFrames(){WebDriverdriver=newChromeDriver();driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromMilliseconds(500);// Navigate to Urldriver.Url="https://www.selenium.dev/selenium/web/iframes.html";//switch To IFrame using Web ElementIWebElementiframe=driver.FindElement(By.Id("iframe1"));//Switch to the framedriver.SwitchTo().Frame(iframe);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));//Now we can type text into email fieldIWebElementemailE=driver.FindElement(By.Id("email"));emailE.SendKeys("admin@selenium.dev");emailE.Clear();driver.SwitchTo().DefaultContent();//switch To IFrame using name or iddriver.FindElement(By.Name("iframe1-name"));//Switch to the framedriver.SwitchTo().Frame(iframe);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));IWebElementemail=driver.FindElement(By.Id("email"));//Now we can type text into email fieldemail.SendKeys("admin@selenium.dev");email.Clear();driver.SwitchTo().DefaultContent();//switch To IFrame using indexdriver.SwitchTo().Frame(0);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));//leave framedriver.SwitchTo().DefaultContent();Assert.AreEqual(true,driver.PageSource.Contains("This page has iframes"));//quit the browserdriver.Quit();}}}
# Switch by IDdriver.switch_to.frame'buttonframe'# Now, Click on the buttondriver.find_element(:tag_name,'button').click
// 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()
Usando um índice
Também é possível usar o índice do frame, podendo ser
consultado usando window.frames em JavaScript.
6164
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();}}
# 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)
6164
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)
Deixando um frame
Para deixar um iframe ou frameset, volte para o conteúdo padrão
como a seguir:
6568
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();}}
# Licensed to the Software Freedom Conservancy (SFC) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information# regarding copyright ownership. The SFC licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0# Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied. See the License for the# specific language governing permissions and limitations# under the License.fromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy#set chrome and launch web pagedriver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/iframes.html")# --- Switch to iframe using WebElement ---iframe=driver.find_element(By.ID,"iframe1")driver.switch_to.frame(iframe)assert"We Leave From Here"indriver.page_sourceemail_element=driver.find_element(By.ID,"email")email_element.send_keys("admin@selenium.dev")email_element.clear()driver.switch_to.default_content()# --- Switch to iframe using name or ID ---iframe1=driver.find_element(By.NAME,"iframe1-name")# (This line doesn't switch, just locates)driver.switch_to.frame(iframe)assert"We Leave From Here"indriver.page_sourceemail=driver.find_element(By.ID,"email")email.send_keys("admin@selenium.dev")email.clear()driver.switch_to.default_content()# --- Switch to iframe using index ---driver.switch_to.frame(0)assert"We Leave From Here"indriver.page_source# --- Final page content check ---driver.switch_to.default_content()assert"This page has iframes"indriver.page_source#quit the driverdriver.quit()#demo code for conference
// Licensed to the Software Freedom Conservancy (SFC) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The SFC licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.usingSystem;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceSeleniumDocs.Interactions{ [TestClass]publicclassFramesTest{ [TestMethod]publicvoidTestFrames(){WebDriverdriver=newChromeDriver();driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromMilliseconds(500);// Navigate to Urldriver.Url="https://www.selenium.dev/selenium/web/iframes.html";//switch To IFrame using Web ElementIWebElementiframe=driver.FindElement(By.Id("iframe1"));//Switch to the framedriver.SwitchTo().Frame(iframe);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));//Now we can type text into email fieldIWebElementemailE=driver.FindElement(By.Id("email"));emailE.SendKeys("admin@selenium.dev");emailE.Clear();driver.SwitchTo().DefaultContent();//switch To IFrame using name or iddriver.FindElement(By.Name("iframe1-name"));//Switch to the framedriver.SwitchTo().Frame(iframe);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));IWebElementemail=driver.FindElement(By.Id("email"));//Now we can type text into email fieldemail.SendKeys("admin@selenium.dev");email.Clear();driver.SwitchTo().DefaultContent();//switch To IFrame using indexdriver.SwitchTo().Frame(0);Assert.AreEqual(true,driver.PageSource.Contains("We Leave From Here"));//leave framedriver.SwitchTo().DefaultContent();Assert.AreEqual(true,driver.PageSource.Contains("This page has iframes"));//quit the browserdriver.Quit();}}}
# 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.
1318
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();}}
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 getPageRanges() and setPageRanges() methods, you can get/set the range of pages to print — e.g. “2-4”.
2227
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();}}
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.
3136
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();}}
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.
4049
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();}}
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 getScale() and setScale() methods, you can get/set the scale of the page you wish to print — e.g. 1.0 is 100% or default, 0.25 is 25%, etc.
5258
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();}}
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 getBackground() and setBackground() methods, you can get/set whether background colors and images appear — boolean true or false.
6267
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();}}
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 getShrinkToFit() and setShrinkToFit() methods, you can get/set whether the page will shrink-to-fit content on the page — boolean true or false.
7176
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();}}
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
O WebDriver não faz distinção entre janelas e guias. E se
seu site abre uma nova guia ou janela, o Selenium permitirá que você trabalhe
usando um identificador. Cada janela tem um identificador único que permanece
persistente em uma única sessão. Você pode pegar o identificador atual usando:
1521
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}}
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}}}
Clicar em um link que abre em uma
nova janela focará a nova janela ou guia na tela, mas o WebDriver não saberá qual
janela que o sistema operacional considera ativa. Para trabalhar com a nova janela
você precisará mudar para ela. Se você tiver apenas duas guias ou janelas abertas,
e você sabe com qual janela você iniciou, pelo processo de eliminação
você pode percorrer as janelas ou guias que o WebDriver pode ver e alternar
para aquela que não é o original.
No entanto, o Selenium 4 fornece uma nova API NewWindow
que cria uma nova guia (ou) nova janela e muda automaticamente para ela.
2130
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"))
2231
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"))
Fechando uma janela ou guia
Quando você fechar uma janela ou guia e que não é a
última janela ou guia aberta em seu navegador, você deve fechá-la e alternar
de volta para a janela que você estava usando anteriormente. Supondo que você seguiu a
amostra de código na seção anterior, você terá o identificador da janela
anterior armazenado em uma variável. Junte isso e você obterá:
3035
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)
3136
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}}}
#Close the tab or windowdriver.close#Switch back to the old tab or windowdriver.switch_to.windoworiginal_window
//Close the tab or window
awaitdriver.close();//Switch back to the old tab or window
awaitdriver.switchTo().window(originalWindow);
//Close the tab or window
driver.close()//Switch back to the old tab or window
driver.switchTo().window(originalWindow)
Esquecer de voltar para outro gerenciador de janela após fechar uma
janela deixará o WebDriver em execução na página agora fechada e
acionara uma No Such Window Exception. Você deve trocar
de volta para um identificador de janela válido para continuar a execução.
Criar nova janela (ou) nova guia e alternar
Cria uma nova janela (ou) guia e focará a nova janela ou guia na tela.
Você não precisa mudar para trabalhar com a nova janela (ou) guia. Se você tiver mais de duas janelas
(ou) guias abertas diferentes da nova janela, você pode percorrer as janelas ou guias que o WebDriver pode ver
e mudar para aquela que não é a original.
Nota: este recurso funciona com Selenium 4 e versões posteriores.
3543
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')
3644
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}}}
require'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
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/ruby/spec/interactions/windows_spec.rb#L9" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
require'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
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/ruby/spec/interactions/windows_spec.rb#L15" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
Opens a new tab and switches to new tab
6971
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);});});
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)
Sair do navegador no final de uma sessão
Quando você terminar a sessão do navegador, você deve chamar a função quit(),
em vez de fechar:
4346
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}}
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}}}
Fechar todas as janelas e guias associadas a essa sessão do WebDriver
Fechar o processo do navegador
Fechar o processo do driver em segundo plano
Notificar o Selenium Grid de que o navegador não está mais em uso para que possa
ser usado por outra sessão (se você estiver usando Selenium Grid)
A falha em encerrar deixará processos e portas extras em segundo plano
rodando em sua máquina, o que pode causar problemas mais tarde.
Algumas estruturas de teste oferecem métodos e anotações em que você pode ligar para derrubar no final de um teste.
/**
* 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();}
/**
* Example using Mocha
* https://mochajs.org/#hooks
*/after('Tear down',asyncfunction(){awaitdriver.quit();});
/**
* Example using JUnit
* https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/AfterAll.html
*/@AfterAllfuntearDown(){driver.quit()}
Se não estiver executando o WebDriver em um contexto de teste, você pode considerar o uso do
try/finally que é oferecido pela maioria das linguagens para que uma exceção
ainda limpe a sessão do WebDriver.
O WebDriver do Python agora suporta o gerenciador de contexto python,
que ao usar a palavra-chave with pode encerrar automaticamente o
driver no fim da execução.
withwebdriver.Firefox()asdriver:# WebDriver code here...# WebDriver will automatically quit after indentation
Gerenciamento de janelas
A resolução da tela pode impactar como seu aplicativo da web é renderizado, então
WebDriver fornece mecanismos para mover e redimensionar a janela do navegador.
Coletar o tamanho da janela
Obtém o tamanho da janela do navegador em pixels.
//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
Access each dimension individually
9294
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);});});
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
Busca as coordenadas da coordenada superior esquerda da janela do navegador.
// 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
Access each dimension individually
107109
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);});});
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
Definir posição da janela
Move a janela para a posição escolhida.
// 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)
Maximizar janela
Aumenta a janela. Para a maioria dos sistemas operacionais, a janela irá preencher
a tela, sem bloquear os próprios menus do sistema operacional e
barras de ferramentas.
driver.manage().window().maximize();
driver.maximize_window()
driver.Manage().Window.Maximize();
driver.manage.window.maximize
awaitdriver.manage().window().maximize();
driver.manage().window().maximize()
Minimizar janela
Minimiza a janela do contexto de navegação atual.
O comportamento exato deste comando é específico para
gerenciadores de janela individuais.
Minimizar Janela normalmente oculta a janela na bandeja do sistema.
Nota: este recurso funciona com Selenium 4 e versões posteriores.
driver.manage().window().minimize();
driver.minimize_window()
driver.Manage().Window.Minimize();
driver.manage.window.minimize
awaitdriver.manage().window().minimize();
driver.manage().window().minimize()
Janela em tamanho cheio
Preenche a tela inteira, semelhante a pressionar F11 na maioria dos navegadores.
driver.manage().window().fullscreen();
driver.fullscreen_window()
driver.Manage().Window.FullScreen();
driver.manage.window.full_screen
awaitdriver.manage().window().fullscreen();
driver.manage().window().fullscreen()
TakeScreenshot
Usado para capturar a tela do contexto de navegação atual.
O endpoint WebDriver screenshot
retorna a captura de tela codificada no formato Base64.
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
5560
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);});});
Usado para capturar a imagem de um elemento para o contexto de navegação atual.
O endpoint WebDriver screenshot
retorna a captura de tela codificada no formato Base64.
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
4349
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);});});
Executa o snippet de código JavaScript no
contexto atual de um frame ou janela selecionada.
//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')")
3238
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')")
Imprimir Página
Imprime a página atual dentro do navegador
Nota: isto requer que navegadores Chromium estejam no modo sem cabeçalho
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);});});
Aplicações web podem habilitar um mecanismo de autenticação baseado em chaves públicas conhecido como Web Authentication para autenticar usuários sem usar uma senha.
Web Authentication define APIs que permitem ao usuário criar uma credencial e registra-la com um autenticador.
Um autenticador pode ser um dispositivo ou um software que guarde as chaves públicas do usuário e as acesse caso seja pedido.
Como o nome sugere, Virtual Authenticator emula esses autenticadores para testes.
Virtual Authenticator Options
Um Autenticador Virtual tem uma série de propriedades.
Essas propriedades são mapeadas como VirtualAuthenticatorOptions nos bindings do Selenium.
5462
Show full example
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
Cria um novo autenticador virtual com as propriedades fornecidas.
6774
Show full example
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);});});
Remove o autenticador virtual adicionado anteriormente.
8587
Show full example
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);});});
Cria uma resident (stateful) credential com os requeridos parâmetros.
99104
Show full example
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);});});
Cria uma resident (stateless) credential com os requeridos parâmetros.
142146
Show full example
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);});});
Retorna a lista de credenciais que o autenticador possui.
156172
Show full example
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);});});
Remove a credencial do autenticador baseado na id da credencial passado.
188199
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"]);}}}
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);});});
Diz se o autenticador simulará sucesso ou falha na verificação de usuário.
210213
Show full example
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);});});