Best Selenium code snippet using org.openqa.selenium.remote.CommandPayload
Source:RemoteWebDriverUnitTest.java
...65 public void canHandleGetCommand() {66 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);67 fixture.driver.get("http://some.host.com");68 fixture.verifyCommands(69 new CommandPayload(70 DriverCommand.GET, ImmutableMap.of("url", "http://some.host.com")));71 }72 @Test73 public void canHandleGetCurrentUrlCommand() {74 WebDriverFixture fixture = new WebDriverFixture(75 echoCapabilities, valueResponder("http://some.host.com"));76 assertThat(fixture.driver.getCurrentUrl()).isEqualTo("http://some.host.com");77 fixture.verifyCommands(78 new CommandPayload(DriverCommand.GET_CURRENT_URL, emptyMap()));79 }80 @Test81 public void canHandleGetTitleCommand() {82 WebDriverFixture fixture = new WebDriverFixture(83 echoCapabilities, valueResponder("Hello, world!"));84 assertThat(fixture.driver.getTitle()).isEqualTo("Hello, world!");85 fixture.verifyCommands(86 new CommandPayload(DriverCommand.GET_TITLE, emptyMap()));87 }88 @Test89 public void canHandleGetPageSourceCommand() {90 WebDriverFixture fixture = new WebDriverFixture(91 echoCapabilities, valueResponder("Hello, world!"));92 assertThat(fixture.driver.getPageSource()).isEqualTo("Hello, world!");93 fixture.verifyCommands(94 new CommandPayload(DriverCommand.GET_PAGE_SOURCE, emptyMap()));95 }96 @Test97 public void canHandleExecuteScriptCommand() {98 WebDriverFixture fixture = new WebDriverFixture(99 echoCapabilities, valueResponder("Hello, world!"));100 fixture.driver.setLogLevel(Level.WARNING);101 Object result = fixture.driver.executeScript("return 1", 1, "2");102 assertThat(result).isEqualTo("Hello, world!");103 fixture.verifyCommands(104 new CommandPayload(DriverCommand.EXECUTE_SCRIPT, ImmutableMap.of(105 "script", "return 1", "args", Arrays.asList(1, "2"))));106 }107 @Test108 public void canHandleExecuteAsyncScriptCommand() {109 WebDriverFixture fixture = new WebDriverFixture(110 echoCapabilities, valueResponder("Hello, world!"));111 assertThat(fixture.driver.executeAsyncScript("return 1", 1, "2"))112 .isEqualTo("Hello, world!");113 fixture.verifyCommands(114 new CommandPayload(DriverCommand.EXECUTE_ASYNC_SCRIPT, ImmutableMap.of(115 "script", "return 1", "args", Arrays.asList(1, "2"))));116 }117 @Test118 public void canHandleFindElementOSSCommand() {119 WebDriverFixture fixture = new WebDriverFixture(120 echoCapabilities,121 valueResponder(ImmutableMap.of("ELEMENT", UUID.randomUUID().toString())));122 assertThat(fixture.driver.findElement(By.id("cheese"))).isNotNull();123 fixture.verifyCommands(124 new CommandPayload(DriverCommand.FIND_ELEMENT, ImmutableMap.of(125 "using", "id", "value", "cheese")));126 }127 @Test128 public void canHandleFindElementW3CCommand() {129 WebDriverFixture fixture = new WebDriverFixture(130 echoCapabilities,131 valueResponder(ImmutableMap.of(ELEMENT_KEY, UUID.randomUUID().toString())));132 assertThat(fixture.driver.findElement(By.id("cheese"))).isNotNull();133 fixture.verifyCommands(134 new CommandPayload(DriverCommand.FIND_ELEMENT, ImmutableMap.of(135 "using", "id", "value", "cheese")));136 }137 @Test138 public void canHandleFindElementCommandWithNonStandardLocator() {139 WebElement element1 = mock(WebElement.class);140 WebElement element2 = mock(WebElement.class);141 By locator = new By() {142 @Override143 public List<WebElement> findElements(SearchContext context) {144 return Arrays.asList(element1, element2);145 }146 };147 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities);148 assertThat(fixture.driver.findElement(locator)).isSameAs(element1);149 fixture.verifyNoCommands();150 }151 @Test152 public void canHandleFindElementsOSSCommand() {153 WebDriverFixture fixture = new WebDriverFixture(154 echoCapabilities,155 valueResponder(Arrays.asList(156 ImmutableMap.of("ELEMENT", UUID.randomUUID().toString()),157 ImmutableMap.of("ELEMENT", UUID.randomUUID().toString()))));158 assertThat(fixture.driver.findElements(By.id("cheese"))).hasSize(2);159 fixture.verifyCommands(160 new CommandPayload(DriverCommand.FIND_ELEMENTS, ImmutableMap.of(161 "using", "id", "value", "cheese")));162 }163 @Test164 public void canHandleFindElementsW3CCommand() {165 WebDriverFixture fixture = new WebDriverFixture(166 echoCapabilities,167 valueResponder(Arrays.asList(168 ImmutableMap.of(ELEMENT_KEY, UUID.randomUUID().toString()),169 ImmutableMap.of(ELEMENT_KEY, UUID.randomUUID().toString()))));170 assertThat(fixture.driver.findElements(By.id("cheese"))).hasSize(2);171 fixture.verifyCommands(172 new CommandPayload(DriverCommand.FIND_ELEMENTS, ImmutableMap.of(173 "using", "id", "value", "cheese")));174 }175 @Test176 public void canHandleFindElementsCommandWithNonStandardLocator() {177 WebElement element1 = mock(WebElement.class);178 WebElement element2 = mock(WebElement.class);179 By locator = new By() {180 @Override181 public List<WebElement> findElements(SearchContext context) {182 return Arrays.asList(element1, element2);183 }184 };185 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities);186 assertThat(fixture.driver.findElements(locator)).containsExactly(element1, element2);187 fixture.verifyNoCommands();188 }189 @Test190 public void returnsEmptyListIfRemoteEndReturnsNullFromFindElements() {191 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);192 List<WebElement> result = fixture.driver.findElements(By.id("id"));193 assertThat(result).isNotNull().isEmpty();194 }195 @Test196 public void throwsIfRemoteEndReturnsNullFromFindElement() {197 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);198 assertThatExceptionOfType(NoSuchElementException.class)199 .isThrownBy(() -> fixture.driver.findElement(By.cssSelector("id")));200 }201 @Test202 public void canHandleGetWindowHandleCommand() {203 WebDriverFixture fixture = new WebDriverFixture(204 echoCapabilities, valueResponder("Hello, world!"));205 assertThat(fixture.driver.getWindowHandle()).isEqualTo("Hello, world!");206 fixture.verifyCommands(207 new CommandPayload(DriverCommand.GET_CURRENT_WINDOW_HANDLE, emptyMap()));208 }209 @Test210 public void canHandleGetWindowHandlesCommand() {211 WebDriverFixture fixture = new WebDriverFixture(212 echoCapabilities, valueResponder(Arrays.asList("window 1", "window 2")));213 assertThat(fixture.driver.getWindowHandles()).hasSize(2).contains("window 1", "window 2");214 fixture.verifyCommands(215 new CommandPayload(DriverCommand.GET_WINDOW_HANDLES, emptyMap()));216 }217 @Test218 public void canHandleCloseCommand() {219 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);220 fixture.driver.close();221 fixture.verifyCommands(222 new CommandPayload(DriverCommand.CLOSE, emptyMap()));223 }224 @Test225 public void canHandleQuitCommand() {226 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);227 fixture.driver.quit();228 assertThat(fixture.driver.getSessionId()).isNull();229 fixture.verifyCommands(230 new CommandPayload(DriverCommand.QUIT, emptyMap()));231 }232 @Test233 public void canHandleQuitCommandAfterQuit() {234 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);235 fixture.driver.quit();236 assertThat(fixture.driver.getSessionId()).isNull();237 fixture.verifyCommands(238 new CommandPayload(DriverCommand.QUIT, emptyMap()));239 fixture.driver.quit();240 verifyNoMoreInteractions(fixture.executor);241 }242 @Test243 public void canHandleSwitchToWindowCommand() {244 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);245 WebDriver driver2 = fixture.driver.switchTo().window("window1");246 assertThat(driver2).isSameAs(fixture.driver);247 fixture.verifyCommands(248 new CommandPayload(DriverCommand.SWITCH_TO_WINDOW, ImmutableMap.of("handle", "window1")));249 }250 @Test251 public void canHandleSwitchToNewWindowCommand() {252 WebDriverFixture fixture = new WebDriverFixture(253 echoCapabilities, valueResponder(ImmutableMap.of("handle", "new window")));254 WebDriver driver2 = fixture.driver.switchTo().newWindow(WindowType.TAB);255 assertThat(driver2).isSameAs(fixture.driver);256 fixture.verifyCommands(257 new CommandPayload(DriverCommand.GET_CURRENT_WINDOW_HANDLE, emptyMap()),258 new CommandPayload(DriverCommand.SWITCH_TO_NEW_WINDOW, ImmutableMap.of("type", "tab")),259 new CommandPayload(DriverCommand.SWITCH_TO_WINDOW, ImmutableMap.of("handle", "new window")));260 }261 @Test262 public void canHandleSwitchToFrameByIndexCommand() {263 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);264 WebDriver driver2 = fixture.driver.switchTo().frame(1);265 assertThat(driver2).isSameAs(fixture.driver);266 fixture.verifyCommands(267 new CommandPayload(DriverCommand.SWITCH_TO_FRAME, ImmutableMap.of("id", 1)));268 }269 @Test270 public void canHandleSwitchToFrameByNameCommand() {271 String elementId = UUID.randomUUID().toString();272 WebDriverFixture fixture = new WebDriverFixture(273 echoCapabilities,274 valueResponder(Arrays.asList(275 ImmutableMap.of(ELEMENT_KEY, elementId),276 ImmutableMap.of(ELEMENT_KEY, UUID.randomUUID().toString()))));277 WebDriver driver2 = fixture.driver.switchTo().frame("frameName");278 assertThat(driver2).isSameAs(fixture.driver);279 fixture.verifyCommands(280 new CommandPayload(DriverCommand.FIND_ELEMENTS, ImmutableMap.of(281 "using", "css selector", "value", "frame[name='frameName'],iframe[name='frameName']")),282 new CommandPayload(DriverCommand.SWITCH_TO_FRAME, ImmutableMap.of(283 "id", ImmutableMap.of("ELEMENT", elementId, ELEMENT_KEY, elementId))));284 }285 @Test286 public void canHandleSwitchToNonExistingFrameCommand() {287 WebDriverFixture fixture = new WebDriverFixture(288 echoCapabilities, valueResponder(EMPTY_LIST));289 assertThatExceptionOfType(NoSuchFrameException.class)290 .isThrownBy(() -> fixture.driver.switchTo().frame("frameName"));291 fixture.verifyCommands(292 new CommandPayload(DriverCommand.FIND_ELEMENTS, ImmutableMap.of(293 "using", "css selector", "value", "frame[name='frameName'],iframe[name='frameName']")),294 new CommandPayload(DriverCommand.FIND_ELEMENTS, ImmutableMap.of(295 "using", "css selector", "value", "frame#frameName,iframe#frameName")));296 }297 @Test298 public void canHandleSwitchToParentFrameCommand() {299 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);300 WebDriver driver2 = fixture.driver.switchTo().parentFrame();301 assertThat(driver2).isSameAs(fixture.driver);302 fixture.verifyCommands(303 new CommandPayload(DriverCommand.SWITCH_TO_PARENT_FRAME, emptyMap()));304 }305 @Test306 public void canHandleSwitchToTopCommand() {307 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);308 WebDriver driver2 = fixture.driver.switchTo().defaultContent();309 assertThat(driver2).isSameAs(fixture.driver);310 fixture.verifyCommands(311 new CommandPayload(DriverCommand.SWITCH_TO_FRAME, Collections.singletonMap("id", null)));312 }313 @Test314 public void canHandleSwitchToAlertCommand() {315 WebDriverFixture fixture = new WebDriverFixture(316 echoCapabilities, valueResponder("Alarm!"));317 Alert alert = fixture.driver.switchTo().alert();318 assertThat(alert.getText()).isEqualTo("Alarm!");319 fixture.verifyCommands(320 new MultiCommandPayload(2, DriverCommand.GET_ALERT_TEXT, emptyMap()));321 }322 @Test323 public void canHandleAlertAcceptCommand() {324 WebDriverFixture fixture = new WebDriverFixture(325 echoCapabilities, valueResponder("Alarm!"), nullValueResponder);326 fixture.driver.switchTo().alert().accept();327 fixture.verifyCommands(328 new CommandPayload(DriverCommand.GET_ALERT_TEXT, emptyMap()),329 new CommandPayload(DriverCommand.ACCEPT_ALERT, emptyMap()));330 }331 @Test332 public void canHandleAlertDismissCommand() {333 WebDriverFixture fixture = new WebDriverFixture(334 echoCapabilities, valueResponder("Alarm!"), nullValueResponder);335 fixture.driver.switchTo().alert().dismiss();336 fixture.verifyCommands(337 new CommandPayload(DriverCommand.GET_ALERT_TEXT, emptyMap()),338 new CommandPayload(DriverCommand.DISMISS_ALERT, emptyMap()));339 }340 @Test341 public void canHandleAlertSendKeysCommand() {342 WebDriverFixture fixture = new WebDriverFixture(343 echoCapabilities, valueResponder("Are you sure?"), nullValueResponder);344 fixture.driver.switchTo().alert().sendKeys("no");345 fixture.verifyCommands(346 new CommandPayload(DriverCommand.GET_ALERT_TEXT, emptyMap()),347 new CommandPayload(DriverCommand.SET_ALERT_VALUE, ImmutableMap.of("text", "no")));348 }349 @Test350 public void canHandleRefreshCommand() {351 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);352 fixture.driver.navigate().refresh();353 fixture.verifyCommands(354 new CommandPayload(DriverCommand.REFRESH, emptyMap()));355 }356 @Test357 public void canHandleBackCommand() {358 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);359 fixture.driver.navigate().back();360 fixture.verifyCommands(361 new CommandPayload(DriverCommand.GO_BACK, emptyMap()));362 }363 @Test364 public void canHandleForwardCommand() {365 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);366 fixture.driver.navigate().forward();367 fixture.verifyCommands(368 new CommandPayload(DriverCommand.GO_FORWARD, emptyMap()));369 }370 @Test371 public void canHandleNavigateToCommand() throws IOException {372 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);373 fixture.driver.navigate().to(new URL("http://www.test.com/"));374 fixture.verifyCommands(375 new CommandPayload(DriverCommand.GET, ImmutableMap.of("url", "http://www.test.com/")));376 }377 @Test378 public void canHandleGetCookiesCommand() {379 WebDriverFixture fixture = new WebDriverFixture(380 echoCapabilities,381 valueResponder(Arrays.asList(382 ImmutableMap.of("name", "cookie1", "value", "value1", "sameSite", "Lax"),383 ImmutableMap.of("name", "cookie2", "value", "value2"))));384 Set<Cookie> cookies = fixture.driver.manage().getCookies();385 assertThat(cookies)386 .hasSize(2)387 .contains(388 new Cookie.Builder("cookie1", "value1").sameSite("Lax").build(),389 new Cookie("cookie2", "value2"));390 fixture.verifyCommands(391 new CommandPayload(DriverCommand.GET_ALL_COOKIES, ImmutableMap.of()));392 }393 @Test394 public void canHandleGetCookieNamedCommand() {395 WebDriverFixture fixture = new WebDriverFixture(396 echoCapabilities,397 valueResponder(Arrays.asList(398 ImmutableMap.of("name", "cookie1", "value", "value1"),399 ImmutableMap.of("name", "cookie2", "value", "value2"))));400 Cookie found = fixture.driver.manage().getCookieNamed("cookie2");401 assertThat(found).isEqualTo(new Cookie("cookie2", "value2"));402 fixture.verifyCommands(403 new CommandPayload(DriverCommand.GET_ALL_COOKIES, emptyMap()));404 }405 @Test406 public void canHandleAddCookieCommand() {407 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);408 Cookie cookie = new Cookie("x", "y");409 fixture.driver.manage().addCookie(cookie);410 fixture.verifyCommands(411 new CommandPayload(DriverCommand.ADD_COOKIE, ImmutableMap.of("cookie", cookie)));412 }413 @Test414 public void canHandleDeleteCookieCommand() {415 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);416 Cookie cookie = new Cookie("x", "y");417 fixture.driver.manage().deleteCookie(cookie);418 fixture.verifyCommands(419 new CommandPayload(DriverCommand.DELETE_COOKIE, ImmutableMap.of("name", "x")));420 }421 @Test422 public void canHandleDeleteAllCookiesCommand() {423 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);424 fixture.driver.manage().deleteAllCookies();425 fixture.verifyCommands(426 new CommandPayload(DriverCommand.DELETE_ALL_COOKIES, emptyMap()));427 }428 @Test429 public void canHandleGetWindowSizeCommand() {430 WebDriverFixture fixture = new WebDriverFixture(431 echoCapabilities,432 valueResponder(ImmutableMap.of("width", 400, "height", 600)));433 Dimension size = fixture.driver.manage().window().getSize();434 assertThat(size).isEqualTo(new Dimension(400, 600));435 fixture.verifyCommands(436 new CommandPayload(DriverCommand.GET_CURRENT_WINDOW_SIZE, emptyMap()));437 }438 @Test439 public void canHandleSetWindowSizeCommand() {440 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);441 fixture.driver.manage().window().setSize(new Dimension(400, 600));442 fixture.verifyCommands(443 new CommandPayload(DriverCommand.SET_CURRENT_WINDOW_SIZE,444 ImmutableMap.of("width", 400, "height", 600)));445 }446 @Test447 public void canHandleGetWindowPositionCommand() {448 WebDriverFixture fixture = new WebDriverFixture(449 echoCapabilities,450 valueResponder(ImmutableMap.of("x", 100, "y", 200)));451 Point position = fixture.driver.manage().window().getPosition();452 assertThat(position).isEqualTo(new Point(100, 200));453 fixture.verifyCommands(454 new CommandPayload(DriverCommand.GET_CURRENT_WINDOW_POSITION,455 ImmutableMap.of("windowHandle", "current")));456 }457 @Test458 public void canHandleSetWindowPositionCommand() {459 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);460 fixture.driver.manage().window().setPosition(new Point(100, 200));461 fixture.verifyCommands(462 new CommandPayload(DriverCommand.SET_CURRENT_WINDOW_POSITION,463 ImmutableMap.of("x", 100, "y", 200)));464 }465 @Test466 public void canHandleMaximizeCommand() {467 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);468 fixture.driver.manage().window().maximize();469 fixture.verifyCommands(470 new CommandPayload(DriverCommand.MAXIMIZE_CURRENT_WINDOW, emptyMap()));471 }472 @Test473 public void canHandleFullscreenCommand() {474 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);475 fixture.driver.manage().window().fullscreen();476 fixture.verifyCommands(477 new CommandPayload(DriverCommand.FULLSCREEN_CURRENT_WINDOW, emptyMap()));478 }479 @Test480 public void canHandleSetImplicitWaitCommand() {481 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);482 fixture.driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));483 fixture.verifyCommands(484 new CommandPayload(DriverCommand.SET_TIMEOUT, ImmutableMap.of("implicit", 10000L)));485 }486 @Test487 public void canHandleGetTimeoutsCommand() {488 WebDriverFixture fixture = new WebDriverFixture(489 echoCapabilities,490 valueResponder(ImmutableMap.of("implicit", 100, "script", 200, "pageLoad", 300)));491 fixture.driver.manage().timeouts().getImplicitWaitTimeout();492 fixture.verifyCommands(493 new CommandPayload(DriverCommand.GET_TIMEOUTS, emptyMap()));494 }495 @Test496 public void canHandleSetScriptTimeoutCommand() {497 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);498 fixture.driver.manage().timeouts().setScriptTimeout(Duration.ofSeconds(10));499 fixture.verifyCommands(500 new CommandPayload(DriverCommand.SET_TIMEOUT, ImmutableMap.of("script", 10000L)));501 }502 @Test503 public void canHandleSetPageLoadTimeoutCommand() {504 WebDriverFixture fixture = new WebDriverFixture(echoCapabilities, nullValueResponder);505 fixture.driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10));506 fixture.verifyCommands(507 new CommandPayload(DriverCommand.SET_TIMEOUT, ImmutableMap.of("pageLoad", 10000L)));508 }509 @Test510 public void canHandleIME() {511 WebDriverFixture fixture = new WebDriverFixture(512 echoCapabilities, valueResponder(singletonList("cheese")));513 List<String> engines = fixture.driver.manage().ime().getAvailableEngines();514 assertThat(engines).hasSize(1).contains("cheese");515 fixture.verifyCommands(516 new CommandPayload(DriverCommand.IME_GET_AVAILABLE_ENGINES, emptyMap()));517 }518 @Test519 public void canAddVirtualAuthenticator() {520 WebDriverFixture fixture = new WebDriverFixture(521 echoCapabilities, valueResponder("authId"));522 VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions();523 VirtualAuthenticator auth = fixture.driver.addVirtualAuthenticator(options);524 assertThat(auth.getId()).isEqualTo("authId");525 fixture.verifyCommands(526 new CommandPayload(DriverCommand.ADD_VIRTUAL_AUTHENTICATOR, options.toMap()));527 }528 @Test529 public void canRemoveVirtualAuthenticator() {530 WebDriverFixture fixture = new WebDriverFixture(531 echoCapabilities, nullValueResponder);532 VirtualAuthenticator auth = mock(VirtualAuthenticator.class);533 when(auth.getId()).thenReturn("authId");534 fixture.driver.removeVirtualAuthenticator(auth);535 fixture.verifyCommands(536 new CommandPayload(DriverCommand.REMOVE_VIRTUAL_AUTHENTICATOR,537 singletonMap("authenticatorId", "authId")));538 }539 @Test540 public void canHandleWebDriverExceptionThrownByCommandExecutor() {541 WebDriverFixture fixture = new WebDriverFixture(542 new ImmutableCapabilities(543 "browserName", "cheese", "platformName", "WINDOWS"),544 echoCapabilities, webDriverExceptionResponder);545 assertThatExceptionOfType(WebDriverException.class)546 .isThrownBy(fixture.driver::getCurrentUrl)547 .withMessageStartingWith("BOOM!!!")548 .withMessageContaining("Build info: ")549 .withMessageContaining(550 "Driver info: org.openqa.selenium.remote.RemoteWebDriver")551 .withMessageContaining(String.format(552 "Session ID: %s", fixture.driver.getSessionId()))553 .withMessageContaining(String.format(554 "%s", fixture.driver.getCapabilities()))555 .withMessageContaining(String.format(556 "Command: [%s, getCurrentUrl {}]", fixture.driver.getSessionId()));557 fixture.verifyCommands(558 new CommandPayload(DriverCommand.GET_CURRENT_URL, emptyMap()));559 }560 @Test561 public void canHandleGeneralExceptionThrownByCommandExecutor() {562 WebDriverFixture fixture = new WebDriverFixture(563 new ImmutableCapabilities(564 "browserName", "cheese", "platformName", "WINDOWS"),565 echoCapabilities, exceptionResponder);566 assertThatExceptionOfType(WebDriverException.class)567 .isThrownBy(fixture.driver::getCurrentUrl)568 .withMessageStartingWith("Error communicating with the remote browser. It may have died.")569 .withMessageContaining("Build info: ")570 .withMessageContaining(571 "Driver info: org.openqa.selenium.remote.RemoteWebDriver")572 .withMessageContaining(String.format(573 "Session ID: %s", fixture.driver.getSessionId()))574 .withMessageContaining(String.format(575 "%s", fixture.driver.getCapabilities()))576 .withMessageContaining(String.format(577 "Command: [%s, getCurrentUrl {}]", fixture.driver.getSessionId()))578 .havingCause()579 .withMessage("BOOM!!!");580 fixture.verifyCommands(581 new CommandPayload(DriverCommand.GET_CURRENT_URL, emptyMap()));582 }583 @Test584 public void canHandleWebDriverExceptionReturnedByCommandExecutor() {585 WebDriverFixture fixture = new WebDriverFixture(586 new ImmutableCapabilities("browserName", "cheese"),587 echoCapabilities, errorResponder("element click intercepted", new WebDriverException("BOOM!!!")));588 assertThatExceptionOfType(WebDriverException.class)589 .isThrownBy(fixture.driver::getCurrentUrl)590 .withMessageStartingWith("BOOM!!!")591 .withMessageContaining("Build info: ")592 .withMessageContaining(593 "Driver info: org.openqa.selenium.remote.RemoteWebDriver")594 .withMessageContaining(String.format(595 "Session ID: %s", fixture.driver.getSessionId()))596 .withMessageContaining(String.format(597 "%s", fixture.driver.getCapabilities()))598 .withMessageContaining(String.format(599 "Command: [%s, getCurrentUrl {}]", fixture.driver.getSessionId()));600 fixture.verifyCommands(601 new CommandPayload(DriverCommand.GET_CURRENT_URL, emptyMap()));602 }603 @Test604 public void canHandleResponseWithErrorCodeButNoExceptionReturnedByCommandExecutor() {605 WebDriverFixture fixture = new WebDriverFixture(606 new ImmutableCapabilities("browserName", "cheese"),607 echoCapabilities, errorResponder("element click intercepted", "BOOM!!!"));608 assertThatExceptionOfType(WebDriverException.class)609 .isThrownBy(fixture.driver::getCurrentUrl)610 .withMessageStartingWith("BOOM!!!")611 .withMessageContaining("Build info: ")612 .withMessageContaining(613 "Driver info: org.openqa.selenium.remote.RemoteWebDriver")614 .withMessageContaining(String.format(615 "Session ID: %s", fixture.driver.getSessionId()))616 .withMessageContaining(String.format(617 "%s", fixture.driver.getCapabilities()))618 .withMessageContaining(String.format(619 "Command: [%s, getCurrentUrl {}]", fixture.driver.getSessionId()));620 fixture.verifyCommands(621 new CommandPayload(DriverCommand.GET_CURRENT_URL, emptyMap()));622 }623 @Test624 public void noArgConstuctorEmptyCapabilitiesTest() {625 RemoteWebDriver driver = new RemoteWebDriver() {}; // anonymous subclass626 assertThat(driver.getCapabilities()).isEqualTo(new ImmutableCapabilities());627 }628}...
Source:QAFExtendedWebDriver.java
...48import org.openqa.selenium.interactions.TouchScreen;49import org.openqa.selenium.remote.Augmenter;50import org.openqa.selenium.remote.CapabilityType;51import org.openqa.selenium.remote.CommandExecutor;52import org.openqa.selenium.remote.CommandPayload;53import org.openqa.selenium.remote.DriverCommand;54import org.openqa.selenium.remote.RemoteTouchScreen;55import org.openqa.selenium.remote.RemoteWebDriver;56import org.openqa.selenium.remote.Response;57import org.openqa.selenium.remote.ScreenshotException;58import org.openqa.selenium.remote.internal.WebElementToJsonConverter;59//import org.openqa.selenium.remote.internal.WebElementToJsonConverter;60import org.openqa.selenium.support.ui.ExpectedConditions;61import com.google.common.collect.ImmutableMap;62import com.google.common.collect.Lists;63import com.qmetry.qaf.automation.core.ConfigurationManager;64import com.qmetry.qaf.automation.core.MessageTypes;65import com.qmetry.qaf.automation.core.QAFListener;66import com.qmetry.qaf.automation.keys.ApplicationProperties;67import com.qmetry.qaf.automation.ui.JsToolkit;68import com.qmetry.qaf.automation.ui.WebDriverCommandLogger;69import com.qmetry.qaf.automation.ui.WebDriverTestBase;70import com.qmetry.qaf.automation.ui.util.DynamicWait;71import com.qmetry.qaf.automation.ui.util.QAFWebDriverExpectedConditions;72import com.qmetry.qaf.automation.ui.util.QAFWebDriverWait;73import com.qmetry.qaf.automation.ui.util.QAFWebElementExpectedConditions;74import com.qmetry.qaf.automation.ui.webdriver.CommandTracker.Stage;75import com.qmetry.qaf.automation.util.LocatorUtil;76import com.qmetry.qaf.automation.util.StringMatcher;77/**78 * com.qmetry.qaf.automation.ui.webdriver.QAFWebDriver.java79 * 80 * @author chirag81 */82public class QAFExtendedWebDriver extends RemoteWebDriver implements QAFWebDriver, QAFWebDriverCommandListener {83 protected final Log logger = LogFactory.getLog(getClass());84 private WebDriverCommandLogger commandLogger;85 private Set<QAFWebDriverCommandListener> listners;86 private WebDriver underLayingDriver;87 private Capabilities capabilities;88 private QAFElementConverter qafElementConverter;89 public QAFExtendedWebDriver(URL url, Capabilities capabilities) {90 this(url, capabilities, null);91 }92 public QAFExtendedWebDriver(WebDriver driver) {93 this(driver, null);94 }95 public QAFExtendedWebDriver(URL url, Capabilities capabilities, WebDriverCommandLogger reporter) {96 super(url, capabilities);97 init(reporter);98 }99 public QAFExtendedWebDriver(CommandExecutor cmdExecutor, Capabilities capabilities,100 WebDriverCommandLogger reporter) {101 super(cmdExecutor, capabilities);102 init(reporter);103 }104 public QAFExtendedWebDriver() {105 init(null);106 }107 public QAFExtendedWebDriver(WebDriver driver, WebDriverCommandLogger reporter) {108 super();109 underLayingDriver = driver;110 setCommandExecutor(((RemoteWebDriver) driver).getCommandExecutor());111 setSessionId(((RemoteWebDriver) driver).getSessionId().toString());112 capabilities = ((RemoteWebDriver) driver).getCapabilities();113 init(reporter);114 }115 @Override116 public Capabilities getCapabilities() {117 if (capabilities == null)118 capabilities = super.getCapabilities();119 return capabilities;120 }121 public WebDriver getUnderLayingDriver() {122 if (underLayingDriver == null)123 underLayingDriver = this;124 return underLayingDriver;125 }126 private void init(WebDriverCommandLogger reporter) {127 //setElementConverter(new QAFExtendedWebElement.JsonConvertor(this));128 qafElementConverter = new QAFElementConverter(this);129 try {130 listners = new LinkedHashSet<QAFWebDriverCommandListener>();131 commandLogger = (null == reporter) ? new WebDriverCommandLogger() : reporter;132 listners.add(commandLogger);133 String[] listners = ConfigurationManager.getBundle()134 .getStringArray(ApplicationProperties.WEBDRIVER_COMMAND_LISTENERS.key);135 for (String listenr : listners) {136 registerListeners(listenr);137 }138 listners = ConfigurationManager.getBundle().getStringArray(ApplicationProperties.QAF_LISTENERS.key);139 for (String listener : listners) {140 try {141 QAFListener cls = (QAFListener) Class.forName(listener).newInstance();142 if (QAFWebDriverCommandListener.class.isAssignableFrom(cls.getClass()))143 this.listners.add((QAFWebDriverCommandListener) cls);144 } catch (Exception e) {145 logger.error("Unable to register class as driver listener: " + listener, e);146 }147 }148 onInitialize(this);149 } catch (Exception e) {150 e.printStackTrace();151 }152 }153 protected WebDriverCommandLogger getReporter() {154 return commandLogger;155 }156 public void setReporter(WebDriverCommandLogger reporter) {157 commandLogger = reporter;158 }159 @Override160 public QAFExtendedWebElement findElement(By by) {161 QAFExtendedWebElement element = (QAFExtendedWebElement) super.findElement(by);162 element.setBy(by);163 element.cacheable = true;164 return element;165 }166 /**167 * @param locator168 * - selenium 1 type locator for example "id=eleid", "name=eleName"169 * etc...170 * @return171 */172 public QAFWebElement findElement(String locator) {173 return ElementFactory.$(locator);174 }175 @SuppressWarnings("unchecked")176 public List<QAFWebElement> findElements(String loc) {177 return (List<QAFWebElement>) (List<? extends WebElement>) findElements(LocatorUtil.getBy(loc));178 }179 public QAFExtendedWebElement createElement(By by) {180 return new QAFExtendedWebElement(this, by);181 }182 public QAFExtendedWebElement createElement(String locator) {183 return new QAFExtendedWebElement(locator);184 }185 @SuppressWarnings("unchecked")186 public List<QAFWebElement> getElements(By by) {187 List<QAFWebElement> proxy;188 proxy = (List<QAFWebElement>) Proxy.newProxyInstance(this.getClass().getClassLoader(),189 new Class[] { List.class }, new QAFExtendedWebElementListHandler(this, by));190 return proxy;191 }192 public void load(QAFExtendedWebElement... elements) {193 if (elements != null) {194 for (QAFExtendedWebElement element : elements) {195 final By by = element.getBy();196 element.setId(((QAFExtendedWebElement) new QAFWebDriverWait(this).ignoring(NoSuchElementException.class,197 StaleElementReferenceException.class, RuntimeException.class)198 .until(ExpectedConditions.presenceOfElementLocated(by))).getId());199 }200 }201 }202 protected Response execute(CommandPayload payload) {203 return execute(payload.getName(), payload.getParameters());204 }205 206 private Response executeSuper(CommandPayload payload) {207 try {208 MethodHandle h1 = MethodHandles.lookup().findSpecial(getClass().getSuperclass(), "execute", MethodType.methodType(Response.class,CommandPayload.class), getClass());209 return (Response) h1.invoke(this, payload);210 211 } catch (NoSuchMethodException | NoSuchFieldException | SecurityException e) {212 return super.execute(payload.getName(), payload.getParameters());213 }catch (Throwable e) {214 if (e instanceof RuntimeException) {215 throw (RuntimeException)e;216 }217 throw new RuntimeException(e);218 }219 }220 221 private Response executeWithoutLog(CommandPayload payload) {222 // in order to compatibility with 3.x, compiled with 3.x. so method from 4.x super class will not be available. 223 // Once min version set to 4.0 we don't need executeSuper method.224 //Response response = super.execute(payload);225 Response response = executeSuper(payload);226 227 if (response == null) {228 return null;229 }230 Object value = getQafElementConverter().apply(response.getValue());231 response.setValue(value);232 return response;233 }234 private QAFElementConverter getQafElementConverter() {235 if(null==qafElementConverter)236 qafElementConverter = new QAFElementConverter(this);237 return qafElementConverter;238 }239 @Override240 protected Response execute(String driverCommand, Map<String, ?> parameters) {241 CommandTracker commandTracker = new CommandTracker(driverCommand, parameters);242 try {243 beforeCommand(this, commandTracker);244 // already handled in before command?245 if (commandTracker.getResponce() == null) {246 commandTracker.setStartTime(System.currentTimeMillis());247 commandTracker.setResponce(executeWitoutLog(commandTracker.getCommand(), commandTracker.getParameters()));248 commandTracker.setEndTime(System.currentTimeMillis());249 }250 afterCommand(this, commandTracker);251 } catch (RuntimeException wde) {252 commandTracker.setException(wde);253 onFailure(this, commandTracker);254 }255 if (commandTracker.hasException()) {256 if (commandTracker.retry) {257 commandTracker.setResponce(executeWitoutLog(commandTracker.getCommand(), commandTracker.getParameters()));258 commandTracker.setException(null);259 commandTracker.setEndTime(System.currentTimeMillis());260 } else {261 throw commandTracker.getException();262 }263 }264 return commandTracker.getResponce();265 }266 protected Response executeWitoutLog(String driverCommand, Map<String, ?> parameters) {267 return executeWithoutLog(new CommandPayload(driverCommand, parameters));268 }269 /*270 * (non-Javadoc)271 * 272 * @see org.openqa.selenium.TakesScreenshot#getScreenshotAs(org.openqa.selenium273 * .OutputType)274 */275 @Override276 public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {277 Object takeScreenshot = getCapabilities().getCapability(CapabilityType.TAKES_SCREENSHOT);278 if (null == takeScreenshot || (Boolean) takeScreenshot) {279 String base64Str = execute(DriverCommand.SCREENSHOT).getValue().toString();280 return target.convertFromBase64Png(base64Str);281 }...
Source:RemoteWebElementTest.java
...47 public void canHandleClickCommand() {48 WebElementFixture fixture = new WebElementFixture(echoCapabilities, nullValueResponder);49 fixture.element.click();50 fixture.verifyCommands(51 new CommandPayload(52 DriverCommand.CLICK_ELEMENT, ImmutableMap.of("id", fixture.element.getId())));53 }54 @Test55 public void canHandleWebDriverExceptionThrownByCommandExecutor() {56 WebElementFixture fixture = new WebElementFixture(57 new ImmutableCapabilities("browserName", "cheese", "platformName", "WINDOWS"),58 echoCapabilities, webDriverExceptionResponder);59 assertThatExceptionOfType(WebDriverException.class)60 .isThrownBy(fixture.element::click)61 .withMessageStartingWith("BOOM!!!")62 .withMessageContaining("Build info: ")63 .withMessageContaining(64 "Driver info: org.openqa.selenium.remote.RemoteWebDriver")65 .withMessageContaining(String.format(66 "Session ID: %s", fixture.driver.getSessionId()))67 .withMessageContaining(String.format(68 "%s", fixture.driver.getCapabilities()))69 .withMessageContaining(String.format(70 "Command: [%s, clickElement {id=%s}]", fixture.driver.getSessionId(), fixture.element.getId()))71 .withMessageContaining(String.format(72 "Element: [[RemoteWebDriver: cheese on WINDOWS (%s)] -> id: test]", fixture.driver.getSessionId()));73 fixture.verifyCommands(74 new CommandPayload(75 DriverCommand.CLICK_ELEMENT, ImmutableMap.of("id", fixture.element.getId())));76 }77 @Test78 public void canHandleGeneralExceptionThrownByCommandExecutor() {79 WebElementFixture fixture = new WebElementFixture(80 new ImmutableCapabilities("browserName", "cheese", "platformName", "WINDOWS"),81 echoCapabilities, exceptionResponder);82 assertThatExceptionOfType(WebDriverException.class)83 .isThrownBy(fixture.element::click)84 .withMessageStartingWith("Error communicating with the remote browser. It may have died.")85 .withMessageContaining("Build info: ")86 .withMessageContaining(87 "Driver info: org.openqa.selenium.remote.RemoteWebDriver")88 .withMessageContaining(String.format(89 "Session ID: %s", fixture.driver.getSessionId()))90 .withMessageContaining(String.format(91 "%s", fixture.driver.getCapabilities()))92 .withMessageContaining(String.format(93 "Command: [%s, clickElement {id=%s}]", fixture.driver.getSessionId(), fixture.element.getId()))94 .withMessageContaining(String.format(95 "Element: [[RemoteWebDriver: cheese on WINDOWS (%s)] -> id: test]", fixture.driver.getSessionId()))96 .havingCause()97 .withMessage("BOOM!!!");98 fixture.verifyCommands(99 new CommandPayload(100 DriverCommand.CLICK_ELEMENT, ImmutableMap.of("id", fixture.element.getId())));101 }102 @Test103 public void canHandleWebDriverExceptionReturnedByCommandExecutor() {104 WebElementFixture fixture = new WebElementFixture(105 new ImmutableCapabilities("browserName", "cheese"),106 echoCapabilities, errorResponder("element click intercepted", new WebDriverException("BOOM!!!")));107 assertThatExceptionOfType(WebDriverException.class)108 .isThrownBy(fixture.element::click)109 .withMessageStartingWith("BOOM!!!")110 .withMessageContaining("Build info: ")111 .withMessageContaining(112 "Driver info: org.openqa.selenium.remote.RemoteWebDriver")113 .withMessageContaining(String.format(114 "Session ID: %s", fixture.driver.getSessionId()))115 .withMessageContaining(String.format(116 "%s", fixture.driver.getCapabilities()))117 .withMessageContaining(String.format(118 "Command: [%s, clickElement {id=%s}]", fixture.driver.getSessionId(), fixture.element.getId()))119 .withMessageContaining(String.format(120 "Element: [[RemoteWebDriver: cheese on ANY (%s)] -> id: test]", fixture.driver.getSessionId()));121 fixture.verifyCommands(122 new CommandPayload(123 DriverCommand.CLICK_ELEMENT, ImmutableMap.of("id", fixture.element.getId())));124 }125 @Test126 public void canHandleResponseWithErrorCodeButNoExceptionReturnedByCommandExecutor() {127 WebElementFixture fixture = new WebElementFixture(128 new ImmutableCapabilities("browserName", "cheese"),129 echoCapabilities, errorResponder("element click intercepted", "BOOM!!!"));130 assertThatExceptionOfType(WebDriverException.class)131 .isThrownBy(fixture.element::click)132 .withMessageStartingWith("BOOM!!!")133 .withMessageContaining("Build info: ")134 .withMessageContaining(135 "Driver info: org.openqa.selenium.remote.RemoteWebDriver")136 .withMessageContaining(String.format(137 "Session ID: %s", fixture.driver.getSessionId()))138 .withMessageContaining(String.format(139 "%s", fixture.driver.getCapabilities()))140 .withMessageContaining(String.format(141 "Command: [%s, clickElement {id=%s}]", fixture.driver.getSessionId(), fixture.element.getId()))142 .withMessageContaining(String.format(143 "Element: [[RemoteWebDriver: cheese on ANY (%s)] -> id: test]", fixture.driver.getSessionId()));144 fixture.verifyCommands(145 new CommandPayload(146 DriverCommand.CLICK_ELEMENT, ImmutableMap.of("id", fixture.element.getId())));147 }148 @Test149 public void canHandleClearCommand() {150 WebElementFixture fixture = new WebElementFixture(echoCapabilities, nullValueResponder);151 fixture.element.clear();152 fixture.verifyCommands(153 new CommandPayload(154 DriverCommand.CLEAR_ELEMENT, ImmutableMap.of("id", fixture.element.getId())));155 }156 @Test157 public void canHandleSubmitCommand() {158 WebElementFixture fixture = new WebElementFixture(echoCapabilities, nullValueResponder);159 fixture.element.submit();160 fixture.verifyCommands(161 new CommandPayload(162 DriverCommand.SUBMIT_ELEMENT, ImmutableMap.of("id", fixture.element.getId())));163 }164 @Test165 public void canHandleSendKeysCommand() {166 WebElementFixture fixture = new WebElementFixture(echoCapabilities, nullValueResponder);167 fixture.element.setFileDetector(mock(FileDetector.class));168 fixture.element.sendKeys("test");169 fixture.verifyCommands(170 new CommandPayload(DriverCommand.SEND_KEYS_TO_ELEMENT, ImmutableMap.of(171 "id", fixture.element.getId(), "value", new CharSequence[]{"test"})));172 }173 @Test174 public void canHandleGetAttributeCommand() {175 WebElementFixture fixture = new WebElementFixture(echoCapabilities, valueResponder("test"));176 assertThat(fixture.element.getAttribute("id")).isEqualTo("test");177 fixture.verifyCommands(178 new CommandPayload(DriverCommand.GET_ELEMENT_ATTRIBUTE, ImmutableMap.of(179 "id", fixture.element.getId(), "name", "id")));180 }181 @Test182 public void canHandleGetDomAttributeCommand() {183 WebElementFixture fixture = new WebElementFixture(echoCapabilities, valueResponder("test"));184 assertThat(fixture.element.getDomAttribute("id")).isEqualTo("test");185 fixture.verifyCommands(186 new CommandPayload(DriverCommand.GET_ELEMENT_DOM_ATTRIBUTE, ImmutableMap.of(187 "id", fixture.element.getId(), "name", "id")));188 }189 @Test190 public void canHandleGetDomPropertyCommand() {191 WebElementFixture fixture = new WebElementFixture(echoCapabilities, valueResponder("test"));192 assertThat(fixture.element.getDomProperty("id")).isEqualTo("test");193 fixture.verifyCommands(194 new CommandPayload(DriverCommand.GET_ELEMENT_DOM_PROPERTY, ImmutableMap.of(195 "id", fixture.element.getId(), "name", "id")));196 }197 @Test198 public void canHandleIsSelectedCommand() {199 WebElementFixture fixture = new WebElementFixture(echoCapabilities, valueResponder(true));200 assertThat(fixture.element.isSelected()).isTrue();201 fixture.verifyCommands(202 new CommandPayload(203 DriverCommand.IS_ELEMENT_SELECTED, ImmutableMap.of("id", fixture.element.getId())));204 }205 @Test206 public void canHandleIsEnabledCommand() {207 WebElementFixture fixture = new WebElementFixture(echoCapabilities, valueResponder(true));208 assertThat(fixture.element.isEnabled()).isTrue();209 fixture.verifyCommands(210 new CommandPayload(211 DriverCommand.IS_ELEMENT_ENABLED, ImmutableMap.of("id", fixture.element.getId())));212 }213 @Test214 public void canHandleIsDisplayedCommand() {215 WebElementFixture fixture = new WebElementFixture(echoCapabilities, valueResponder(true));216 assertThat(fixture.element.isDisplayed()).isTrue();217 fixture.verifyCommands(218 new CommandPayload(219 DriverCommand.IS_ELEMENT_DISPLAYED, ImmutableMap.of("id", fixture.element.getId())));220 }221 @Test222 public void canHandleGeTextCommand() {223 WebElementFixture fixture = new WebElementFixture(echoCapabilities, valueResponder("test"));224 assertThat(fixture.element.getText()).isEqualTo("test");225 fixture.verifyCommands(226 new CommandPayload(227 DriverCommand.GET_ELEMENT_TEXT, ImmutableMap.of("id", fixture.element.getId())));228 }229 @Test230 public void canHandleGetTagNameCommand() {231 WebElementFixture fixture = new WebElementFixture(echoCapabilities, valueResponder("div"));232 assertThat(fixture.element.getTagName()).isEqualTo("div");233 fixture.verifyCommands(234 new CommandPayload(DriverCommand.GET_ELEMENT_TAG_NAME,235 ImmutableMap.of("id", fixture.element.getId())));236 }237 @Test238 public void canHandleGetLocationCommand() {239 WebElementFixture fixture = new WebElementFixture(240 echoCapabilities, valueResponder(ImmutableMap.of("x", 10, "y", 20)));241 assertThat(fixture.element.getLocation()).isEqualTo(new Point(10, 20));242 fixture.verifyCommands(243 new CommandPayload(DriverCommand.GET_ELEMENT_LOCATION,244 ImmutableMap.of("id", fixture.element.getId())));245 }246 @Test247 public void canHandleGetSizeCommand() {248 WebElementFixture fixture = new WebElementFixture(249 echoCapabilities, valueResponder(ImmutableMap.of("width", 100, "height", 200)));250 assertThat(fixture.element.getSize()).isEqualTo(new Dimension(100, 200));251 fixture.verifyCommands(252 new CommandPayload(253 DriverCommand.GET_ELEMENT_SIZE, ImmutableMap.of("id", fixture.element.getId())));254 }255 @Test256 public void canHandleGetRectCommand() {257 WebElementFixture fixture = new WebElementFixture(258 echoCapabilities,259 valueResponder(ImmutableMap.of(260 "x", 10, "y", 20, "width", 100, "height", 200)));261 assertThat(fixture.element.getRect()).isEqualTo(262 new Rectangle(new Point(10, 20), new Dimension(100, 200)));263 fixture.verifyCommands(264 new CommandPayload(DriverCommand.GET_ELEMENT_RECT,265 ImmutableMap.of("id", fixture.element.getId())));266 }267 @Test268 public void canHandleGetCssPropertyCommand() {269 WebElementFixture fixture = new WebElementFixture(echoCapabilities, valueResponder("red"));270 assertThat(fixture.element.getCssValue("color")).isEqualTo("red");271 fixture.verifyCommands(272 new CommandPayload(DriverCommand.GET_ELEMENT_VALUE_OF_CSS_PROPERTY,273 ImmutableMap.of("id", fixture.element.getId(), "propertyName", "color")));274 }275 @Test276 public void canHandleGetAriaRoleCommand() {277 WebElementFixture fixture = new WebElementFixture(echoCapabilities, valueResponder("section"));278 assertThat(fixture.element.getAriaRole()).isEqualTo("section");279 fixture.verifyCommands(280 new CommandPayload(DriverCommand.GET_ELEMENT_ARIA_ROLE,281 ImmutableMap.of("id", fixture.element.getId())));282 }283 @Test284 public void canHandleGetAccessibleNameCommand() {285 WebElementFixture fixture = new WebElementFixture(286 echoCapabilities, valueResponder("element name"));287 assertThat(fixture.element.getAccessibleName()).isEqualTo("element name");288 fixture.verifyCommands(289 new CommandPayload(DriverCommand.GET_ELEMENT_ACCESSIBLE_NAME,290 ImmutableMap.of("id", fixture.element.getId())));291 }292}...
Source:ProxyWebDriver.java
...21import org.openqa.selenium.interactions.Mouse;22import org.openqa.selenium.interactions.Sequence;23import org.openqa.selenium.print.PrintOptions;24import org.openqa.selenium.remote.CommandExecutor;25import org.openqa.selenium.remote.CommandPayload;26import org.openqa.selenium.remote.ErrorHandler;27import org.openqa.selenium.remote.ExecuteMethod;28import org.openqa.selenium.remote.FileDetector;29import org.openqa.selenium.remote.JsonToWebElementConverter;30import org.openqa.selenium.remote.RemoteWebDriver;31import org.openqa.selenium.remote.RemoteWebDriver.When;32import org.openqa.selenium.remote.Response;33import org.openqa.selenium.remote.SessionId;34import org.openqa.selenium.support.ui.WebDriverWait;35import org.openqa.selenium.virtualauthenticator.VirtualAuthenticator;36import org.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;37public class ProxyWebDriver extends RemoteWebDriver {38 RemoteWebDriver driver;39 public ProxyWebDriver(WebDriver driver) {40 this.driver=(RemoteWebDriver)driver;41 42 }43 @Override44 public ScriptKey pin(String script) {45 // TODO Auto-generated method stub46 return driver.pin(script);47 }48 @Override49 public void unpin(ScriptKey key) {50 // TODO Auto-generated method stub51 driver.unpin(key);52 }53 @Override54 public Set<ScriptKey> getPinnedScripts() {55 // TODO Auto-generated method stub56 return driver.getPinnedScripts();57 }58 59 @Override60 public Object executeAsyncScript(String script, Object... args) {61 // TODO Auto-generated method stub62 return driver.executeAsyncScript(script, args);63 }64 65 66 67 @Override68 public Object executeScript(String script, Object... args) {69 // TODO Auto-generated method stub70 RemoteWebDriver driverR=(RemoteWebDriver)driver;71 return driverR.executeScript(script, args);72 }73 @Override74 public Object executeScript(ScriptKey key, Object... args) {75 // TODO Auto-generated method stub76 return driver.executeScript(key, args);77 }78 @Override79 public SessionId getSessionId() {80 // TODO Auto-generated method stub81 return driver.getSessionId();82 }83 84 @Override85 public ErrorHandler getErrorHandler() {86 // TODO Auto-generated method stub87 return driver.getErrorHandler();88 }89 @Override90 public void setErrorHandler(ErrorHandler handler) {91 // TODO Auto-generated method stub92 driver.setErrorHandler(handler);93 }94 @Override95 public CommandExecutor getCommandExecutor() {96 // TODO Auto-generated method stub97 return driver.getCommandExecutor();98 }99 100 @Override101 public Capabilities getCapabilities() {102 // TODO Auto-generated method stub103 return driver.getCapabilities();104 }105 @Override106 public <X> X getScreenshotAs(OutputType<X> outputType) throws WebDriverException {107 // TODO Auto-generated method stub108 return driver.getScreenshotAs(outputType);109 }110 @Override111 public Pdf print(PrintOptions printOptions) throws WebDriverException {112 // TODO Auto-generated method stub113 return driver.print(printOptions);114 }115 @Override116 public List<WebElement> findElements(SearchContext context, BiFunction<String, Object, CommandPayload> findCommand,117 By locator) {118 // TODO Auto-generated method stub119 return driver.findElements(context, findCommand, locator);120 }121 122 123 @Override124 public void setLogLevel(Level level) {125 // TODO Auto-generated method stub126 driver.setLogLevel(level);127 }128 129 @Override130 public void perform(Collection<Sequence> actions) {...
Source:DockerSeleniumTest.java
...21import org.openqa.selenium.devtools.v93.network.Network;22import org.openqa.selenium.html5.LocalStorage;23import org.openqa.selenium.print.PrintOptions;24import org.openqa.selenium.remote.Command;25import org.openqa.selenium.remote.CommandPayload;26import org.openqa.selenium.remote.RemoteExecuteMethod;27import org.openqa.selenium.remote.RemoteWebDriver;28import org.openqa.selenium.remote.Response;29import org.openqa.selenium.remote.html5.RemoteWebStorage;30// Before running this, please make sure to start docker container using below command:31// docker run -d -p 4445:4444 --shm-size="2g" -v /dev/shm:/dev/shm32// selenium/standalone-chrome:4.0.0-rc-1-2021090233public class DockerSeleniumTest implements Runnable {34 public static String remote_url_chrome = "http://localhost:4444/";35 public static void main(String[] args) {36 ExecutorService executorService =37 new ThreadPoolExecutor(38 10, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());39 for (int i = 0; i < 1; i++) {40 executorService.execute(new DockerSeleniumTest());41 }42 }43 public void run() {44 ChromeOptions options = new ChromeOptions();45 options.addArguments("--headless");46 CDPRemoteDriver driver = null;47 try {48 // CDPRemoteDriver is wrapper over RemoteWebDriver which handles executeCdpCommand49 // RemoteWebDriver don't support CDPCommands.50 // RemoteWebDriver driver = new RemoteWebDriver(new URL(remote_url_chrome), options);51 driver = new CDPRemoteDriver(new URL(remote_url_chrome), options);52 System.out.println("Session started");53 driver.manage().window().maximize();54 HashMap parameters =55 new HashMap() {56 {57 put(58 "source",59 "window.localStorage.setItem('idp_tokens', '{\"acme\":{\"accessToken\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ0eXAiOiJCZWFyZXIiLCJhdWQiOiJhY2NvdW50IiwiZXhwIjoxNjMxODU4MDI3LCJpYXQiOjE2MzE4NTc3MjcsInVwbiI6InN1cmluZGVyLnJhanBhbEBsb2dyaHl0aG0uY29tIiwiaXNzIjoibG9ncmh5dGhtLWRldmVsb3BtZW50Iiwic3ViIjoiMDQyYjg2M2ItNzEyMy00ZWQ5LWI2ZjQtYmMzZDc5NTk5MmQzIiwidGVuYW50X2lkIjoiYWNtZSIsImNhcGFiaWxpdGllcyI6WyJNQU5BR0VfQVVESVQiLCJNQU5BR0VfQ09MTEVDVE9SUyIsIk1BTkFHRV9GSUxURVJTIiwiTUFOQUdFX0NPTlRFTlQiLCJNQU5BR0VfUk9MRVMiLCJNQU5BR0VfUEFTU1dPUkRfUE9MSUNJRVMiLCJNQU5BR0VfVEVOQU5UX1NFVFRJTkdTIiwiTUFOQUdFX1VTRVJTIiwiTUFOQUdFX05PVElGSUNBVElPTlMiLCJNQU5BR0VfRU5USVRJRVMiLCJFWEVDVVRFX1NFQVJDSCIsIlZJRVdfTkFWSUdBVElPTl9TVUdHRVNUSU9OUyIsIkJPUkVBU19VU0VSIl0sIm5hbWUiOiJTdXJpbmRlciBSYWpwYWwgUmFqcGFsIiwiZ2l2ZW5fbmFtZSI6IlN1cmluZGVyIFJhanBhbCIsImZhbWlseV9uYW1lIjoiUmFqcGFsIiwiZW1haWwiOiJzdXJpbmRlci5yYWpwYWxAbG9ncmh5dGhtLmNvbSIsInByZWZlcnJlZF91c2VybmFtZSI6InN1cmluZGVyLnJhanBhbEBsb2dyaHl0aG0uY29tIiwianRpIjoiYjFkMmFhZGQtYzQ5Zi00MTJkLWJkMTctMmQ2N2NlMGNiMjJhIn0.LVoOp4RnLG5pd511hT1tKCGVpOGavROWbuW0ZaXB2PbVjoxOulaxQ9ZeLqwhvUNPvpzoL7t--8bisZXBeVpAof5AgxCx0dL_B4l1l1we6FOLFLU6EkQuMYogMtIM3xHCd9AoEYmWn0jMKq-Elr6p0G8KQpLbgcstHi9AQGMluxF7hY_RPgCi36__DMK3NpgI95byn9XHhU7gSy8Ngw3QvI5z-U2frCQAz4qMNO5Rfq1QUmhX51aQNhzPYKEfxSBKYDaHjq8_gUKJFhO0zswopsMxZg4qfog-rm-1OxKgxf8wRE0eiTulMkOvE8ozNpix5PnjLarwytTO6G5a8anx4Q\",\"tenantId\":\"acme\",\"capabilities\":[\"MANAGE_AUDIT\",\"MANAGE_COLLECTORS\",\"MANAGE_FILTERS\",\"MANAGE_CONTENT\",\"MANAGE_ROLES\",\"MANAGE_PASSWORD_POLICIES\",\"MANAGE_TENANT_SETTINGS\",\"MANAGE_USERS\",\"MANAGE_NOTIFICATIONS\",\"MANAGE_ENTITIES\",\"EXECUTE_SEARCH\",\"VIEW_NAVIGATION_SUGGESTIONS\",\"BOREAS_USER\"]}}')");60 }61 };62 driver.getCommandExecutor().execute(new Command(driver.getSessionId(), new CommandPayload("executeCdpCommand", ImmutableMap63 .of("cmd", "Page.addScriptToEvaluateOnNewDocument", "params", parameters))));64 System.out.println("Navigating to url");65 driver.navigate().to("https://app.k8s.development.boreas.cloud");66 System.out.println("Waiting for page to load.");67 // This is added just to test the pdf generation. Will be changed later.68 Thread.sleep(10000);69 System.out.println("Printing PDF");70 Pdf pdf = driver.print(new PrintOptions());71 byte[] decodedBytes = Util.base64Decode(pdf.getContent());72 String fileName = "./test-" + UUID.randomUUID().toString() + ".pdf";73 System.out.printf("Writing to File: %s \n", fileName);74 Util.writeToFile(fileName, decodedBytes);75 System.out.println("Done");76 } catch (MalformedURLException | InterruptedException e) {...
Source:AppiumNewSessionCommandPayload.java
...18import com.google.common.collect.ImmutableSet;19import org.openqa.selenium.Capabilities;20import org.openqa.selenium.internal.Require;21import org.openqa.selenium.remote.AcceptedW3CCapabilityKeys;22import org.openqa.selenium.remote.CommandPayload;23import java.util.Map;24import static io.appium.java_client.internal.CapabilityHelpers.APPIUM_PREFIX;25import static org.openqa.selenium.remote.DriverCommand.NEW_SESSION;26public class AppiumNewSessionCommandPayload extends CommandPayload {27 private static final AcceptedW3CCapabilityKeys ACCEPTED_W3C_PATTERNS = new AcceptedW3CCapabilityKeys();28 /**29 * Appends "appium:" prefix to all non-prefixed non-standard capabilities.30 *31 * @param possiblyInvalidCapabilities user-provided capabilities mapping.32 * @return Fixed capabilities mapping.33 */34 private static Map<String, Object> makeW3CSafe(Capabilities possiblyInvalidCapabilities) {35 return Require.nonNull("Capabilities", possiblyInvalidCapabilities)36 .asMap().entrySet().stream()37 .collect(ImmutableMap.toImmutableMap(entry -> ACCEPTED_W3C_PATTERNS.test(entry.getKey())38 ? entry.getKey()39 : APPIUM_PREFIX + entry.getKey(),40 Map.Entry::getValue));41 }42 /**43 * Overrides the default new session behavior to44 * only handle W3C capabilities.45 *46 * @param capabilities User-provided capabilities.47 */48 public AppiumNewSessionCommandPayload(Capabilities capabilities) {49 super(NEW_SESSION, ImmutableMap.of(50 "capabilities", ImmutableSet.of(makeW3CSafe(capabilities)),51 "desiredCapabilities", capabilities52 ));53 }54}
Source:Command.java
...19import java.util.Map;20import java.util.Objects;21public class Command {22 private final SessionId sessionId;23 private final CommandPayload payload;24 public Command(SessionId sessionId, String name) {25 this(sessionId, name, new HashMap<>());26 }27 public Command(SessionId sessionId, String name, Map<String, ?> parameters) {28 this(sessionId, new CommandPayload(name, parameters));29 }30 public Command(SessionId sessionId, CommandPayload payload) {31 this.sessionId = sessionId;32 this.payload = payload;33 }34 public SessionId getSessionId() {35 return sessionId;36 }37 public String getName() {38 return payload.getName();39 }40 public Map<String, ?> getParameters() {41 return payload.getParameters();42 }43 @Override44 public String toString() {...
Source:CommandPayload.java
...15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.remote;18import java.util.Map;19public class CommandPayload {20 private final String name;21 private final Map<String, ?> parameters;22 public CommandPayload(String name, Map<String, ?> parameters) {23 this.name = name;24 this.parameters = parameters;25 }26 public String getName() {27 return name;28 }29 public Map<String, ?> getParameters() {30 return parameters;31 }32}...
CommandPayload
Using AI Code Generation
1CommandPayload payload = new CommandPayload("executeScript", ImmutableMap.of("script", "return 1 + 1"));2Response response = new Response();3response = new CommandExecutor().execute(DriverCommand.EXECUTE_SCRIPT, payload);4System.out.println(response.getValue());5Object value = response.getValue();6Long result = (Long) value;7System.out.println(result);8int status = response.getStatus();9System.out.println(status);10String state = response.getState();11System.out.println(state);12String sessionId = response.getSessionId();13System.out.println(sessionId);14Object value = response.getValue();15System.out.println(value);
LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.
Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.
What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.
Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.
Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.
How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.
Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.
Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!