org.openqa.selenium.NoSuchElementException Java Examples

The following examples show how to use org.openqa.selenium.NoSuchElementException. 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 Project: hifive-pitalium   Author: hifive   File: HideMultiElementsTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 複数セレクタで複数の要素を指定して非表示にするが、そのうちのいずれかは存在しない要素である。
 * 
 * @ptl.expect エラーが発生せず、非表示に指定した要素が写っていないこと。
 */
@Test
public void multiTargets_notExist() throws Exception {
	openBasicColorPage();

	ScreenshotArgument arg = ScreenshotArgument.builder("s").addNewTarget().addHiddenElementsById("not-exists")
			.addHiddenElementsById("colorColumn1").addHiddenElementsById("colorColumn2").build();
	if (BrowserType.SAFARI.equals(capabilities.getBrowserName())) {
		expectedException.expect(NoSuchElementException.class);
	}
	assertionView.assertView(arg);

	// Check
	// 特定の色のピクセルが存在しないこと
	BufferedImage image = loadTargetResults("s").get(0).getImage().get();
	int width = image.getWidth();
	int height = image.getHeight();
	for (int x = 0; x < width; x++) {
		for (int y = 0; y < height; y++) {
			Color actual = Color.valueOf(image.getRGB(x, y));
			assertThat(actual, is(not(anyOf(equalTo(Color.GREEN), equalTo(Color.BLUE)))));
		}
	}
}
 
Example #2
Source Project: keycloak   Author: keycloak   File: SelectAuthenticatorPage.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean isCurrent() {
    // Check the title
    if (!DroneUtils.getCurrentDriver().getTitle().startsWith("Log in to ") && !DroneUtils.getCurrentDriver().getTitle().startsWith("Anmeldung bei ")) {
        return false;
    }

    // Check the authenticators-choice available
    try {
        driver.findElement(By.id("kc-select-credential-form"));
    } catch (NoSuchElementException nfe) {
        return false;
    }

    return true;
}
 
Example #3
Source Project: kurento-room   Author: Kurento   File: RoomClientBrowserTest.java    License: Apache License 2.0 6 votes vote down vote up
public WebElement findElement(String label, Browser browser, String id) {
  try {
    return new WebDriverWait(browser.getWebDriver(), testTimeout, POLLING_LATENCY)
        .until(ExpectedConditions.presenceOfElementLocated(By.id(id)));
  } catch (TimeoutException e) {
    log.warn("Timeout when waiting for element {} to exist in browser {}", id, label);
    int originalTimeout = 60;
    try {
      originalTimeout = browser.getTimeout();
      log.debug("Original browser timeout (s): {}, set to 10", originalTimeout);
      browser.setTimeout(10);
      browser.changeTimeout(10);
      WebElement elem = browser.getWebDriver().findElement(By.id(id));
      log.info("Additional findElement call was able to locate {} in browser {}", id, label);
      return elem;
    } catch (NoSuchElementException e1) {
      log.debug("Additional findElement call couldn't locate {} in browser {} ({})", id, label,
          e1.getMessage());
      throw new NoSuchElementException("Element with id='" + id + "' not found after "
          + testTimeout + " seconds in browser " + label);
    } finally {
      browser.setTimeout(originalTimeout);
      browser.changeTimeout(originalTimeout);
    }
  }
}
 
Example #4
Source Project: hifive-pitalium   Author: hifive   File: ExcludeInFrameTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * BODYを撮影する際にiframe内外のs存在しない要素を除外する。
 * 
 * @ptl.expect エラーが発生せず、除外領域が保存されていないこと。
 */
@Test
public void captureBody_excludeNotExistElementInsideAndOutsideFrame() throws Exception {
	openIFramePage();

	ScreenshotArgument arg = ScreenshotArgument.builder("s").addNewTarget().moveTarget(true).scrollTarget(false)
			.addExcludeByClassName("not-exists").addExcludeByClassName("not-exists").inFrameByClassName("content")
			.build();
	if (BrowserType.SAFARI.equals(capabilities.getBrowserName())) {
		expectedException.expect(NoSuchElementException.class);
	}
	assertionView.assertView(arg);

	// Check
	TargetResult result = loadTargetResults("s").get(0);
	assertThat(result.getExcludes(), is(empty()));
}
 
Example #5
Source Project: webtester-core   Author: testIT-WebTester   File: Select.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the first selected option's value. If nothing is selected
 * <code>null</code> is returned.
 *
 * @return the value of the first selected option.
 * @since 0.9.0
 */
public String getFirstSelectedValue() {
    return executeAction(new PageObjectCallbackWithReturnValue<String>() {

        @Override
        public String execute(PageObject pageObject) {
            try {
                return getFirstSelectedOption().getAttribute("value");
            } catch (NoSuchElementException e) {
                logger.warn(logMessage(NOTHING_SELECTED_VALUE));
                return null;
            }
        }

    });
}
 
Example #6
Source Project: hifive-pitalium   Author: hifive   File: NoSuchElementTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 存在しない要素を指定して撮影する。
 * 
 * @ptl.expect AssertionErrorが発生すること。
 */
@Test
public void noSuchElement() throws Exception {
	openBasicTextPage();

	ScreenshotArgument arg = ScreenshotArgument.builder("s").addNewTargetById("notExists").build();

	if (BrowserType.SAFARI.equals(capabilities.getBrowserName())) {
		expectedException.expect(NoSuchElementException.class);
	} else {
		expectedException.expect(AssertionError.class);
		expectedException.expectMessage("Invalid selector found");
	}
	assertionView.assertView(arg);
	fail();
}
 
Example #7
Source Project: selenium   Author: SeleniumHQ   File: AugmenterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void proxyShouldNotAppearInStackTraces() {
  // This will force the class to be enhanced
  final Capabilities caps = new ImmutableCapabilities("magic.numbers", true);

  DetonatingDriver driver = new DetonatingDriver();
  driver.setCapabilities(caps);

  WebDriver returned = getAugmenter()
    .addDriverAugmentation(
      "magic.numbers",
      HasMagicNumbers.class,
      (c, exe) -> () -> 42)
    .augment(driver);

  assertThatExceptionOfType(NoSuchElementException.class)
    .isThrownBy(() -> returned.findElement(By.id("ignored")));
}
 
Example #8
Source Project: keycloak   Author: keycloak   File: WebAuthnRegisterPage.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isAIA() {
    try {
        registerAIAButton.getText();
        cancelAIAButton.getText();
        return true;
    } catch (NoSuchElementException e) {
        return false;
    }
}
 
Example #9
Source Project: keycloak   Author: keycloak   File: AbstractShowTokensPage.java    License: Apache License 2.0 5 votes vote down vote up
public String getAccessTokenString() {
    try {
        return accessTokenString.getText();
    } catch (NoSuchElementException nsee) {
        log.warn("No accessTokenString element found on the page");
    }

    return null;
}
 
Example #10
Source Project: selenium   Author: SeleniumHQ   File: AjaxElementLocatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAlwaysDoAtLeastOneAttemptAtFindingTheElement() throws Exception {
  Field f = Page.class.getDeclaredField("first");
  final WebDriver driver = mock(WebDriver.class);
  final By by = new ByIdOrName("first");

  when(driver.findElement(by)).thenThrow(new NoSuchElementException("bar"));

  ElementLocator locator = new MonkeyedAjaxElementLocator(clock, driver, f, 0);

  assertThatExceptionOfType(NoSuchElementException.class)
      .isThrownBy(locator::findElement);

  verify(driver, atLeast(2)).findElement(by);
}
 
Example #11
Source Project: hifive-pitalium   Author: hifive   File: DomSelectorTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * driver -> ???
 */
@Test
public void findElement_driver_notFound() throws Exception {
	expectedException.expect(NoSuchElementException.class);

	DomSelector selector = new DomSelector(SelectorType.TAG_NAME, "none");
	selector.findElement(driver);
}
 
Example #12
Source Project: keycloak   Author: keycloak   File: OneTimeCode.java    License: Apache License 2.0 5 votes vote down vote up
public boolean isOtpLabelPresent() {
    try {
        return otpInputLabel.isDisplayed();
    } catch (NoSuchElementException e) {
        return false;
    }
}
 
Example #13
Source Project: hifive-pitalium   Author: hifive   File: HideSingleElementTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 単体セレクタで存在しない要素を指定して非表示にする。
 * 
 * @ptl.expect エラーが発生しないこと。
 */
@Test
public void notExists() throws Exception {
	openBasicColorPage();

	ScreenshotArgument arg = ScreenshotArgument.builder("s").addNewTarget().addHiddenElementsById("not-exists")
			.build();
	if (BrowserType.SAFARI.equals(capabilities.getBrowserName())) {
		expectedException.expect(NoSuchElementException.class);
	}
	assertionView.assertView(arg);

	// エラーとならない
}
 
Example #14
Source Project: qaf   Author: qmetry   File: ByAny.java    License: MIT License 5 votes vote down vote up
@Override
public WebElement findElement(SearchContext context) {
	List<WebElement> elements = findElements(context);
	if (elements.isEmpty()) {
		throw new NoSuchElementException("Cannot locate an element using " + toString());
	}
	return elements.get(0);
}
 
Example #15
Source Project: keycloak   Author: keycloak   File: FeedbackMessage.java    License: Apache License 2.0 5 votes vote down vote up
public boolean isPresent() {
    try {
        return alertRoot.isDisplayed();
    }
    catch (NoSuchElementException e) {
        return false;
    }
}
 
Example #16
Source Project: teammates   Author: TEAMMATES   File: InstructorCoursesPage.java    License: GNU General Public License v2.0 5 votes vote down vote up
private int getCourseCount() {
    try {
        return activeCoursesTable.findElements(By.cssSelector("tbody tr")).size();
    } catch (NoSuchElementException e) {
        return 0;
    }
}
 
Example #17
Source Project: user-registration-V2   Author: ewolff   File: RegisterierungTest.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isElementPresent(By by) {
	try {
		driver.findElement(by);
		return true;
	} catch (NoSuchElementException e) {
		return false;
	}
}
 
Example #18
Source Project: webtester-core   Author: testIT-WebTester   File: PageObject.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return whether or not the {@linkplain PageObject} exists and is
 * currently visible
 * @since 0.9.0
 */
public boolean isVisible() {
    return executeAction(new PageObjectCallbackWithReturnValue<Boolean>() {

        @Override
        public Boolean execute(PageObject pageObject) {
            try {
                return pageObject.getWebElement().isDisplayed();
            } catch (NoSuchElementException e) {
                return Boolean.FALSE;
            }
        }

    });
}
 
Example #19
Source Project: keycloak   Author: keycloak   File: UIUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Contains some browser-specific tweaks for getting an element text.
 *
 * @param element
 * @return
 */
public static String getTextFromElement(WebElement element) {
    String text = element.getText();
    if (getCurrentDriver() instanceof SafariDriver) {
        try {
            // Safari on macOS doesn't comply with WebDriver specs yet again - getText() retrieves hidden text by CSS.
            text = element.findElement(By.xpath("./span[not(contains(@class,'ng-hide'))]")).getText();
        }
        catch (NoSuchElementException e) {
            // no op
        }
        return text.trim(); // Safari on macOS sometimes for no obvious reason surrounds the text with spaces
    }
    return text;
}
 
Example #20
Source Project: carina   Author: qaprosoft   File: AndroidUtils.java    License: Apache License 2.0 5 votes vote down vote up
/** Scroll Timeout check
 * @param startTime - Long initial time for timeout count down
 **/
public static void checkTimeout(long startTime){
    long elapsed = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())-startTime;

    if (elapsed > SCROLL_TIMEOUT) {
        throw new NoSuchElementException("Scroll timeout has been reached..");
    }
}
 
Example #21
Source Project: base-framework   Author: biliroy   File: Selenium2.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 判断页面内是否存在Element.
 */
public boolean isElementPresent(By by) {
	try {
		driver.findElement(by);
		return true;
	} catch (NoSuchElementException e) {
		return false;
	}
}
 
Example #22
Source Project: htmlunit   Author: HtmlUnit   File: HtmlPage3Test.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
@Alerts(DEFAULT = "error",
        CHROME = "Something")
@NotYetImplemented({IE, FF, FF68, FF60})
public void shouldBeAbleToFindElementByXPathInXmlDocument() throws Exception {
    final String html = "<?xml version='1.0' encoding='UTF-8'?>\n"
        + "<html xmlns='http://www.w3.org/1999/xhtml'\n"
        + "      xmlns:svg='http://www.w3.org/2000/svg'\n"
        + "      xmlns:xlink='http://www.w3.org/1999/xlink'>\n"
        + "<body>\n"
        + "  <svg:svg id='chart_container' height='220' width='400'>\n"
        + "    <svg:text y='16' x='200' text-anchor='middle'>Something</svg:text>\n"
        + "  </svg:svg>\n"
        + "</body>\n"
        + "</html>\n";

    final WebDriver driver = loadPage2(html, URL_FIRST, "application/xhtml+xml", ISO_8859_1, null);
    String actual;
    try {
        final WebElement element = driver.findElement(By.xpath("//svg:svg//svg:text"));
        actual = element.getText();
    }
    catch (final NoSuchElementException e) {
        actual = "error";
    }
    assertEquals(getExpectedAlerts()[0], actual);
}
 
Example #23
Source Project: ambari-logsearch   Author: apache   File: LogSearchUISteps.java    License: Apache License 2.0 5 votes vote down vote up
@Then("element does not exist with xpath: $xpath")
public void doNotFindByXPath(@Named("xpath") String xPath) {
  try {
    LOG.info("Check that element does not exist with xpath: {}", xPath);
    home.findElement(By.xpath(xPath));
    Assert.fail(String.format("Element is found. xPath: '%s'", xPath));
  } catch (NoSuchElementException e) {
    // success
  }
}
 
Example #24
Source Project: oxTrust   Author: GluuFederation   File: AbstractPage.java    License: MIT License 5 votes vote down vote up
public void fluentWait(int seconds) {
	try {
		Wait<WebDriver> wait = new FluentWait<WebDriver>(webDriver).withTimeout(seconds, TimeUnit.SECONDS)
				.pollingEvery(5, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);

		wait.until(new Function<WebDriver, WebElement>() {
			public WebElement apply(WebDriver driver) {
				return driver.findElement(locator);
			}
		});
	} catch (Exception e) {

	}
}
 
Example #25
Source Project: ambari-logsearch   Author: apache   File: LogSearchUISteps.java    License: Apache License 2.0 5 votes vote down vote up
private void closeTourPopup() {
  LOG.info("Close Tour popup if needed.");
  try {
    home.findElement(By.cssSelector("div.modal-footer > button.btn.btn-default")).click();
  } catch (NoSuchElementException ex) {
    // do nothing - no popup
  }
}
 
Example #26
Source Project: mamute   Author: caelum   File: ForgotPasswordPage.java    License: Apache License 2.0 5 votes vote down vote up
public boolean emailWasSent() {
    try {
    	List<WebElement> confirmations = allByClassName("confirmation");
    	return !confirmations.isEmpty();
    } catch (NoSuchElementException e) {
        return true;
    }
}
 
Example #27
Source Project: demo-java   Author: saucelabs-training   File: GuineaPigPage.java    License: MIT License 5 votes vote down vote up
public boolean isOnPage() {
    try {
        getSubmittedCommentText();
        return true;
    } catch (NoSuchElementException ex) {
        return false;
    }
}
 
Example #28
Source Project: movieapp-dialog   Author: germanattanasio   File: BaseUI.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * isVisible - Checks whether the given locator matches a visible WebElement
 * @param locator The locator for the element
 * @return true if the element is found and visible
 */
public boolean isVisible(String locator) {
	boolean found = false;
       try{
           WebElement element = findElement(locator);
           if(element.isDisplayed()){
           	logger.info("INFO: Element " + locator + " found and is visible");
           	found = true;
           }
       }catch (NoSuchElementException err){
       	//Ignore
       }
       return found;
}
 
Example #29
Source Project: selenium   Author: SeleniumHQ   File: PageFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotThrowANoSuchElementExceptionWhenUsedWithAFluentWait() {
  driver = mock(WebDriver.class);
  when(driver.findElement(ArgumentMatchers.any())).thenThrow(new NoSuchElementException("because"));

  TickingClock clock = new TickingClock();
  Wait<WebDriver> wait = new WebDriverWait(driver, Duration.ofSeconds(1), Duration.ofMillis(1001), clock, clock);

  PublicPage page = new PublicPage();
  PageFactory.initElements(driver, page);
  WebElement element = page.q;

  assertThatExceptionOfType(TimeoutException.class)
      .isThrownBy(() -> wait.until(ExpectedConditions.visibilityOf(element)));
}
 
Example #30
Source Project: product-iots   Author: wso2   File: GraphHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Check the graph path is visible or not.
 *
 * @param graph : web element of the graph
 * @return : True if the path is visible. False otherwise
 */
public boolean isPathAvailable(WebElement graph) {
    try {
        WebElement graphContainer = getGraph(graph, uiElementMapper.getElement("iot.stat.graph.class.name"));
        return graphContainer != null && graphContainer.findElement(By.tagName("path")).isDisplayed();
    } catch (NoSuchElementException e) {
        log.error(String.format("No element found. \n %s", e.getMessage()));
        return false;
    }
}