org.openqa.selenium.NoSuchWindowException Java Examples

The following examples show how to use org.openqa.selenium.NoSuchWindowException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EncapsulateOperation.java    From LuckyFrameClient with GNU Affero General Public License v3.0 6 votes vote down vote up
private static ExpectedCondition<WebDriver> windowToBeAvailableAndSwitchToIt(final String nameOrHandleOrTitle) {
    return driver -> {
        try {
            if (null != driver){
            	return driver.switchTo().window(nameOrHandleOrTitle);
            } else{
            	return null;
            }
                
        } catch (NoSuchWindowException windowWithNameOrHandleNotFound) {
            try {
                return windowByTitle(driver, nameOrHandleOrTitle);
            } catch (NoSuchWindowException windowWithTitleNotFound) {
                if (ChangString.isInteger(nameOrHandleOrTitle)){
                	return windowByIndex(driver, Integer.parseInt(nameOrHandleOrTitle));
                } else{
                	return null;
                }                       
            }
        }
    };
}
 
Example #2
Source File: ErrorHandlerTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void testThrowsCorrectExceptionTypes() {
  assertThrowsCorrectExceptionType(ErrorCodes.NO_SUCH_WINDOW, NoSuchWindowException.class);
  assertThrowsCorrectExceptionType(ErrorCodes.NO_SUCH_FRAME, NoSuchFrameException.class);
  assertThrowsCorrectExceptionType(ErrorCodes.NO_SUCH_ELEMENT, NoSuchElementException.class);
  assertThrowsCorrectExceptionType(
      ErrorCodes.UNKNOWN_COMMAND, UnsupportedCommandException.class);
  assertThrowsCorrectExceptionType(
      ErrorCodes.METHOD_NOT_ALLOWED, UnsupportedCommandException.class);
  assertThrowsCorrectExceptionType(
      ErrorCodes.STALE_ELEMENT_REFERENCE, StaleElementReferenceException.class);
  assertThrowsCorrectExceptionType(
      ErrorCodes.ELEMENT_NOT_VISIBLE, ElementNotVisibleException.class);
  assertThrowsCorrectExceptionType(
      ErrorCodes.INVALID_ELEMENT_STATE, InvalidElementStateException.class);
  assertThrowsCorrectExceptionType(
      ErrorCodes.XPATH_LOOKUP_ERROR, InvalidSelectorException.class);
  assertThrowsCorrectExceptionType(ErrorCodes.INVALID_ELEMENT_COORDINATES,
      InvalidCoordinatesException.class);
}
 
Example #3
Source File: FluentWaitTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void timeoutMessageIncludesLastIgnoredException() {
  final NoSuchWindowException exception = new NoSuchWindowException("");

  when(mockClock.instant()).thenReturn(EPOCH, EPOCH.plusMillis(500), EPOCH.plusMillis(1500), EPOCH.plusMillis(2500));
  when(mockCondition.apply(mockDriver))
    .thenThrow(exception)
    .thenReturn(null);

  Wait<WebDriver> wait = new FluentWait<>(mockDriver, mockClock, mockSleeper)
    .withTimeout(Duration.ofMillis(0))
    .pollingEvery(Duration.ofSeconds(2))
    .ignoring(NoSuchWindowException.class);

  assertThatExceptionOfType(TimeoutException.class)
      .isThrownBy(() -> wait.until(mockCondition))
      .satisfies(expected -> assertThat(exception).isSameAs(expected.getCause()));
}
 
Example #4
Source File: FluentWaitTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void propagatesUnIgnoredExceptions() {
  final NoSuchWindowException exception = new NoSuchWindowException("");

  when(mockClock.instant()).thenReturn(EPOCH);
  when(mockCondition.apply(mockDriver)).thenThrow(exception);

  Wait<WebDriver> wait = new FluentWait<>(mockDriver, mockClock, mockSleeper)
    .withTimeout(Duration.ofMillis(0))
    .pollingEvery(Duration.ofSeconds(2))
    .ignoring(NoSuchElementException.class, NoSuchFrameException.class);

  assertThatExceptionOfType(NoSuchWindowException.class)
      .isThrownBy(() -> wait.until(mockCondition))
      .satisfies(expected -> assertThat(expected).isSameAs(exception));
}
 
Example #5
Source File: RemoteWebDriver.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public WebDriver window(String windowHandleOrName) {
  try {
    execute(DriverCommand.SWITCH_TO_WINDOW(windowHandleOrName));
    return RemoteWebDriver.this;
  } catch (NoSuchWindowException nsw) {
    // simulate search by name
    String original = getWindowHandle();
    for (String handle : getWindowHandles()) {
      switchTo().window(handle);
      if (windowHandleOrName.equals(executeScript("return window.name"))) {
        return RemoteWebDriver.this; // found by name
      }
    }
    switchTo().window(original);
    throw nsw;
  }
}
 
Example #6
Source File: TakeScreenshotTest.java    From darcy-webdriver with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void shouldThrowFindableNotPresentExceptionIfDriverIsNotPresent() throws IOException {
    TargetedWebDriver driver = mock(TargetedWebDriver.class);
    OutputStream outputStream = mock(OutputStream.class);
    Browser browser = new WebDriverBrowser(driver,
            new StubWebDriverParentContext(),
            new StubWebDriverElementContext());

    when(driver.getScreenshotAs(OutputType.BYTES))
            .thenThrow(NoSuchWindowException.class);
    try {
        browser.takeScreenshot(outputStream);
        fail("Expected FindableNotPresentException to be thrown");
    } catch (Exception e) {
        assertThat("Expected FindableNotPresentException to be thrown",
                e.getClass(), equalTo(FindableNotPresentException.class));
    }

    verify(outputStream).close();
}
 
Example #7
Source File: WebDriverAftBase.java    From rice with Educational Community License v2.0 6 votes vote down vote up
protected void closeAndQuitWebDriver() {
    if (driver != null) {
        if (WebDriverUtils.dontTearDownPropertyNotSet() && WebDriverUtils.dontTearDownOnFailure(isPassed())) {
            try {
                acceptAlertIfPresent();
                driver.close();
            } catch (NoSuchWindowException nswe) {
                System.out.println("NoSuchWindowException closing WebDriver " + nswe.getMessage());
            } finally {
                if (driver != null) {
                    driver.quit();
                }
            }
        }
    } else {
        System.out.println("WebDriver is null for " + this.getClass().toString() + " if using a remote hub did you include the port?");
    }
}
 
Example #8
Source File: JiraIssueCreation.java    From rice with Educational Community License v2.0 6 votes vote down vote up
private void closeAndQuitWebDriver() {
    if (driver != null) {
        if (WebDriverUtils.dontTearDownPropertyNotSet() && WebDriverUtils.dontTearDownOnFailure(passed)) {
            try {
                driver.close();
            } catch (NoSuchWindowException nswe) {
                System.out.println("NoSuchWindowException closing WebDriver " + nswe.getMessage());
            } finally {
                if (driver != null) {
                    driver.quit();
                }
            }
        }
    } else {
        System.out.println("WebDriver is null for " + this.getClass().toString());
    }
}
 
Example #9
Source File: JenkinsJsonJobResultsBase.java    From rice with Educational Community License v2.0 6 votes vote down vote up
protected void closeAndQuitWebDriver() {
    if (driver != null) {
        if (WebDriverUtils.dontTearDownPropertyNotSet() && WebDriverUtils.dontTearDownOnFailure(passed)) {
            try {
                driver.close();
            } catch (NoSuchWindowException nswe) {
                System.out.println("NoSuchWindowException closing WebDriver " + nswe.getMessage());
            } finally {
                if (driver != null) {
                    driver.quit();
                }
            }
        }
    } else {
        System.out.println("WebDriver is null for " + this.getClass().toString());
    }
}
 
Example #10
Source File: DriverHelper.java    From carina with Apache License 2.0 5 votes vote down vote up
public void switchWindow() throws NoSuchWindowException {
    WebDriver drv = getDriver();
    Set<String> handles = drv.getWindowHandles();
    String current = drv.getWindowHandle();
    if (handles.size() > 1) {
        handles.remove(current);
    }
    String newTab = handles.iterator().next();
    drv.switchTo().window(newTab);
}
 
Example #11
Source File: AlertActionsTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
void testIsAlertPresentNoSuchWindowException()
{
    when(webDriver.switchTo()).thenReturn(targetLocator);
    doThrow(NoSuchWindowException.class).when(targetLocator).alert();
    boolean answer = alertActions.isAlertPresent(webDriver);
    assertFalse(answer);
    verify(windowsActions).switchToPreviousWindow();
}
 
Example #12
Source File: WebDriverWaitTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void shouldSilentlyCaptureNoSuchWindowExceptions() {

  final ExpectedCondition<WebElement> condition = mock(ExpectedCondition.class);
  when(condition.apply(mockDriver))
      .thenThrow(new NoSuchWindowException("foo"))
      .thenReturn(mockElement);

  TickingClock clock = new TickingClock();
  Wait<WebDriver> wait =
      new WebDriverWait(mockDriver, Duration.ofSeconds(5), Duration.ofMillis(500), clock, clock);
  wait.until(condition);
}
 
Example #13
Source File: ViewWebDriverTargetTest.java    From darcy-webdriver with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected = NoSuchWindowException.class)
public void shouldThrowNoSuchWindowExceptionIfViewIsNotLoadedInAnyWindow() {
    View view = new NeverLoadedView();

    WebDriverTarget target = WebDriverTargets.withViewLoaded(view, context);

    target.switchTo(locator);
}
 
Example #14
Source File: WebDriverBrowser.java    From darcy-webdriver with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Wrapper for interacting with a targeted driver that may or may not actually be present.
 * Returns a result.
 */
private <T> T attemptAndGet(Supplier<T> action) {
    try {
        return action.get();
    } catch (NoSuchFrameException | NoSuchWindowException | NoSuchSessionException e) {
        throw new FindableNotPresentException(this, e);
    }
}
 
Example #15
Source File: WebDriverBrowser.java    From darcy-webdriver with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Wrapper for interacting with a targeted driver that may or may not actually be present.
 */
private void attempt(Runnable action) {
    try {
        action.run();
    } catch (NoSuchFrameException | NoSuchWindowException | NoSuchSessionException e) {
        throw new FindableNotPresentException(this, e);
    }
}
 
Example #16
Source File: WebDriverTargets.java    From darcy-webdriver with GNU General Public License v3.0 5 votes vote down vote up
private String findWindow(TargetLocator targetLocator) {
    for (String windowHandle : targetLocator.defaultContent().getWindowHandles()) {
        if (urlMatcher.matches(targetLocator.window(windowHandle).getCurrentUrl())) {
            return windowHandle;
        }
    }

    throw new NoSuchWindowException("No window in driver found which has url matching: " + urlMatcher);
}
 
Example #17
Source File: WebDriverTargets.java    From darcy-webdriver with GNU General Public License v3.0 5 votes vote down vote up
private String findWindow(TargetLocator targetLocator) {
    for (String windowHandle : targetLocator.defaultContent().getWindowHandles()) {
        if (targetLocator.window(windowHandle).getTitle().equals(title)) {
            return windowHandle;
        }
    }

    throw new NoSuchWindowException("No window in driver found which has title: " + title);
}
 
Example #18
Source File: WebDriverTargets.java    From darcy-webdriver with GNU General Public License v3.0 5 votes vote down vote up
private String findWindow(TargetLocator targetLocator) {
    for (String windowHandle : targetLocator.defaultContent().getWindowHandles()) {
        Browser forWindowHandle = By.id(windowHandle).find(Browser.class, parentContext);

        view.setContext(forWindowHandle);

        if (view.isLoaded()) {
            return windowHandle;
        }
    }

    throw new NoSuchWindowException("No window in driver found which has " + view + " "
            + "currently loaded.");
}
 
Example #19
Source File: SeleniumHelper.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
public int getCurrentTabIndex(List<String> tabHandles) {
    try {
        String currentHandle = driver().getWindowHandle();
        return tabHandles.indexOf(currentHandle);
    } catch (NoSuchWindowException e) {
        return -1;
    }
}
 
Example #20
Source File: WebDriverBrowserTest.java    From webtester-core with Apache License 2.0 5 votes vote down vote up
@Test(expected = NoSuchWindowException.class)
public void testExceptionHandlingInCaseAWindowIsNotFoundForTheGivenNameOrHandle() {

    TargetLocator locator = mockTargetLocator();
    NoSuchWindowException exception = createSeleniumExceptionOfClass(NoSuchWindowException.class);
    doThrow(exception).when(locator).window(NAME_OR_HANDLE);

    try {
        cut.setFocusOnWindow(NAME_OR_HANDLE);
    } finally {
        verifyLastEventFiredWasExceptionEventOf(exception);
    }

}
 
Example #21
Source File: FocusSetterTest.java    From webtester2-core with Apache License 2.0 5 votes vote down vote up
@Test
void switchingToWindowByUnknownNameOrHandleThrowsException() {
    NoSuchWindowException exception = mock(NoSuchWindowException.class);
    when(webDriver.switchTo().window("fooBar")).thenThrow(exception);
    assertThrows(NoSuchWindowException.class, () -> {
        cut.onWindow("fooBar");
    });
    verify(events).fireExceptionEvent(exception);
    verifyNoMoreInteractions(events);
}
 
Example #22
Source File: JavaDriverTest.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
public void windowThrowsExceptionWhenNotExisting() throws Throwable {
    driver = new JavaDriver();
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            frame.setVisible(true);
        }
    });
    try {
        driver.switchTo().window("My Dialog1");
        throw new MissingException(NoSuchWindowException.class);
    } catch (NoSuchWindowException e) {
    }
}
 
Example #23
Source File: HTMLFormElementTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void targetChangedAfterSubmitCall() throws Exception {
    final String html = "<html><head><script>\n"
        + "function test() {\n"
        + "  var f = document.forms[0];\n"
        + "  f.submit();\n"
        + "  f.target = 'foo2';\n"
        + "}\n"
        + "</script></head><body>\n"
        + "<form action='page1.html' name='myForm' target='foo1'>\n"
        + "  <input name='myField' value='some value'>\n"
        + "</form>\n"
        + "<div id='clickMe' onclick='test()'>click me</div></body></html>";

    getMockWebConnection().setDefaultResponse("<html><head>"
            + "<script>document.title = 'Name: ' + window.name</script></head></html>");
    final WebDriver driver = loadPage2(html);
    driver.findElement(By.id("clickMe")).click();

    try {
        driver.switchTo().window("foo2");
        fail("Window foo2 found");
    }
    catch (final NoSuchWindowException e) {
        // ok
    }
    driver.switchTo().window("foo1");
    assertTitle(driver, "Name: foo1");
}
 
Example #24
Source File: EncapsulateOperation.java    From LuckyFrameClient with GNU Affero General Public License v3.0 5 votes vote down vote up
private static WebDriver windowByTitle(WebDriver driver, String title) {
    String original = driver.getWindowHandle();
    Set<String> windowHandles = driver.getWindowHandles();
    for (String windowHandle : windowHandles) {
        driver.switchTo().window(windowHandle);
        if (title.equals(driver.getTitle())) {
            return driver;
        }
    }
    if (0 < windowHandles.size()){
    	driver.switchTo().window(original);
    } 
    throw new NoSuchWindowException("Window with title[" + title + "] not found");
}
 
Example #25
Source File: WindowUrlWebDriverTargetTest.java    From darcy-webdriver with GNU General Public License v3.0 4 votes vote down vote up
@Test(expected = NoSuchWindowException.class)
public void shouldThrowNoSuchWindowExceptionIfNoWindowsCanBeFoundMatchingTheUrlMatcher() {
    WebDriverTarget target = WebDriverTargets.windowByUrl(equalTo("awesome window"));

    target.switchTo(locator);
}
 
Example #26
Source File: WindowTitleWebDriverTargetTest.java    From darcy-webdriver with GNU General Public License v3.0 4 votes vote down vote up
@Test(expected = NoSuchWindowException.class)
public void shouldThrowNoSuchWindowExceptionIfNoWindowsCanBeFoundWithTitle() {
    WebDriverTarget target = WebDriverTargets.windowByTitle("awesome window");

    target.switchTo(locator);
}
 
Example #27
Source File: ErrorHandlerTest.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Test
public void testStatusCodesRaisedBackToStatusMatches() {
  Map<Integer, Class<?>> exceptions = new HashMap<>();
  exceptions.put(ErrorCodes.NO_SUCH_SESSION, NoSuchSessionException.class);
  exceptions.put(ErrorCodes.NO_SUCH_ELEMENT, NoSuchElementException.class);
  exceptions.put(ErrorCodes.NO_SUCH_FRAME, NoSuchFrameException.class);
  exceptions.put(ErrorCodes.UNKNOWN_COMMAND, UnsupportedCommandException.class);
  exceptions.put(ErrorCodes.STALE_ELEMENT_REFERENCE, StaleElementReferenceException.class);
  exceptions.put(ErrorCodes.ELEMENT_NOT_VISIBLE, ElementNotVisibleException.class);
  exceptions.put(ErrorCodes.INVALID_ELEMENT_STATE, InvalidElementStateException.class);
  exceptions.put(ErrorCodes.UNHANDLED_ERROR, WebDriverException.class);
  exceptions.put(ErrorCodes.ELEMENT_NOT_SELECTABLE, ElementNotSelectableException.class);
  exceptions.put(ErrorCodes.JAVASCRIPT_ERROR, JavascriptException.class);
  exceptions.put(ErrorCodes.XPATH_LOOKUP_ERROR, InvalidSelectorException.class);
  exceptions.put(ErrorCodes.TIMEOUT, TimeoutException.class);
  exceptions.put(ErrorCodes.NO_SUCH_WINDOW, NoSuchWindowException.class);
  exceptions.put(ErrorCodes.INVALID_COOKIE_DOMAIN, InvalidCookieDomainException.class);
  exceptions.put(ErrorCodes.UNABLE_TO_SET_COOKIE, UnableToSetCookieException.class);
  exceptions.put(ErrorCodes.UNEXPECTED_ALERT_PRESENT, UnhandledAlertException.class);
  exceptions.put(ErrorCodes.NO_ALERT_PRESENT, NoAlertPresentException.class);
  exceptions.put(ErrorCodes.ASYNC_SCRIPT_TIMEOUT, ScriptTimeoutException.class);
  exceptions.put(ErrorCodes.INVALID_ELEMENT_COORDINATES, InvalidCoordinatesException.class);
  exceptions.put(ErrorCodes.IME_NOT_AVAILABLE, ImeNotAvailableException.class);
  exceptions.put(ErrorCodes.IME_ENGINE_ACTIVATION_FAILED, ImeActivationFailedException.class);
  exceptions.put(ErrorCodes.INVALID_SELECTOR_ERROR, InvalidSelectorException.class);
  exceptions.put(ErrorCodes.SESSION_NOT_CREATED, SessionNotCreatedException.class);
  exceptions.put(ErrorCodes.MOVE_TARGET_OUT_OF_BOUNDS, MoveTargetOutOfBoundsException.class);
  exceptions.put(ErrorCodes.INVALID_XPATH_SELECTOR, InvalidSelectorException.class);
  exceptions.put(ErrorCodes.INVALID_XPATH_SELECTOR_RETURN_TYPER, InvalidSelectorException.class);

  for (Map.Entry<Integer, Class<?>> exception : exceptions.entrySet()) {
    assertThatExceptionOfType(WebDriverException.class)
        .isThrownBy(() -> handler.throwIfResponseFailed(createResponse(exception.getKey()), 123))
        .satisfies(e -> {
          assertThat(e.getClass().getSimpleName()).isEqualTo(exception.getValue().getSimpleName());

          // all of the special invalid selector exceptions are just mapped to the generic invalid selector
          int expected = e instanceof InvalidSelectorException
                         ? ErrorCodes.INVALID_SELECTOR_ERROR : exception.getKey();
          assertThat(new ErrorCodes().toStatusCode(e)).isEqualTo(expected);
        });
  }
}
 
Example #28
Source File: FocusSetter.java    From webtester2-core with Apache License 2.0 3 votes vote down vote up
/**
 * Sets the browser's focus to the window with the given name or handle.
 * <p>
 * <b>Tip:</b> A handle for the current window can be got by using the {@link CurrentWindow#getHandle()} method.
 *
 * @param nameOrHandle the name or handle of the window to focus on
 * @throws NoSuchWindowException in case there is no window with the given name or handle
 * @see Browser#currentWindow()
 * @see CurrentWindow#getHandle()
 * @see WebDriver.TargetLocator#window(String)
 * @since 2.0
 */
public void onWindow(String nameOrHandle) throws NoSuchWindowException {
    ActionTemplate.browser(browser())
        .execute(browser -> doOnWindow(browser, nameOrHandle))
        .fireEvent(browser -> new SwitchedToWindowEvent(nameOrHandle));
    log.debug("focused on window with name or handle: {}", nameOrHandle);
}