org.openqa.selenium.WebDriver类的使用及代码示例

x33g5p2x  于2022-02-02 转载在 其他  
字(18.1k)|赞(0)|评价(0)|浏览(350)

本文整理了Java中org.openqa.selenium.WebDriver类的一些代码示例,展示了WebDriver类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。WebDriver类的具体详情如下:
包路径:org.openqa.selenium.WebDriver
类名称:WebDriver

WebDriver介绍

[英]The main interface to use for testing, which represents an idealised web browser. The methods in this class fall into three categories:

  • Control of the browser itself
  • Selection of WebElements
  • Debugging aids

Key methods are WebDriver#get(String), which is used to load a new web page, and the various methods similar to WebDriver#findElement(By), which is used to find WebElements.

Currently, you will need to instantiate implementations of this class directly. It is hoped that you write your tests against this interface so that you may "swap in" a more fully featured browser when there is a requirement for one.

Note that all methods that use XPath to locate elements will throw a RuntimeExceptionshould there be an error thrown by the underlying XPath engine.
[中]用于测试的主界面,代表理想化的web浏览器。本课程中的方法分为三类:
*浏览器本身的控制
*网络元素的选择
*调试辅助工具
关键方法是WebDriver#get(String),用于加载新网页,以及与WebDriver#findElement(By)类似的各种方法,后者用于查找WebElements。
目前,您需要直接实例化这个类的实现。希望您针对该界面编写测试,以便在需要时可以“交换”功能更全面的浏览器。
请注意,所有使用XPath定位元素的方法都会抛出RuntimeExceptions,如果底层XPath引擎抛出错误。

代码示例

代码示例来源:origin: cloudfoundry/uaa

private void navigateToForcePasswordChange() {
  updateUserToForcePasswordChange(restTemplate, baseUrl, adminAccessToken, userId);
  webDriver.get(baseUrl+"/login");
  webDriver.findElement(By.name("username")).sendKeys(userEmail);
  webDriver.findElement(By.name("password")).sendKeys("secr3T");
  webDriver.findElement(By.xpath("//input[@value='Sign in']")).click();
  assertThat(webDriver.findElement(By.cssSelector("h1")).getText(),
    containsString("Force Change Password"));
  assertEquals(baseUrl+"/force_password_change", webDriver.getCurrentUrl());
}

代码示例来源:origin: cloudfoundry/uaa

private void performLogin(String username) {
  webDriver.get(zoneUrl + "/logout.do");
  webDriver.manage().deleteAllCookies();
  webDriver.get(zoneUrl + "/login");
  webDriver.findElement(By.name("username")).sendKeys(username);
  webDriver.findElement(By.name("password")).sendKeys(USER_PASSWORD);
  webDriver.findElement(By.xpath("//input[@value='Sign in']")).click();
}

代码示例来源:origin: apache/geode

@Override
public void after() {
 driver.quit();
}

代码示例来源:origin: selenide/selenide

@Override
public WebDriver apply(WebDriver driver) {
 try {
  return driver.switchTo().frame(driver.findElement(locator));
 } catch (NoSuchFrameException e) {
  return null;
 } catch (WebDriverException e) {
  return null;
 }
}

代码示例来源:origin: selenide/selenide

@Override
public WebDriver apply(WebDriver driver) {
 try {
  List<String> windowHandles = new ArrayList<>(driver.getWindowHandles());
  return driver.switchTo().window(windowHandles.get(index));
 } catch (IndexOutOfBoundsException windowWithIndexNotFound) {
  return null;
 }
}

代码示例来源:origin: selenide/selenide

/**
 * Switch to window/tab by name/handle/title except some windows handles
 * @param title title of window/tab
 */
protected static WebDriver windowByTitle(WebDriver driver, String title) {
 Set<String> windowHandles = driver.getWindowHandles();
 for (String windowHandle : windowHandles) {
  driver.switchTo().window(windowHandle);
  if (title.equals(driver.getTitle())) {
   return driver;
  }
 }
 throw new NoSuchWindowException("Window with title not found: " + title);
}

代码示例来源:origin: org.gatein.pc/pc-embed

@Test
@RunAsClient
@InSequence(1)
public void testInteraction(@ArquillianResource URL deploymentURL) throws Exception
{
 URL url = renderURL(deploymentURL, EventOverflowPortlet.class);
 driver.get(url.toString());
 WebElement link = driver.findElement(By.id("url"));
 url = new URL(link.getAttribute("href"));
 HttpURLConnection conn = (HttpURLConnection)url.openConnection();
 Assert.assertEquals(500, conn.getResponseCode());
}

代码示例来源:origin: cloudfoundry/uaa

@Test
  public void testEmailDomainRegisteredWithIDPDoesNotAllowAccountCreation() throws Exception {
    String adminToken = IntegrationTestUtils.getClientCredentialsToken(baseUrl, "admin", "adminsecret");
    IdentityProvider<OIDCIdentityProviderDefinition> oidcProvider = new IdentityProvider().setName("oidc_provider").setActive(true).setType(OriginKeys.OIDC10).setOriginKey(OriginKeys.OIDC10).setConfig(new OIDCIdentityProviderDefinition());
    oidcProvider.getConfig().setAuthUrl(new URL("http://example.com"));
    oidcProvider.getConfig().setShowLinkText(false);
    oidcProvider.getConfig().setTokenUrl(new URL("http://localhost:8080/uaa/idp_login"));
    oidcProvider.getConfig().setTokenKeyUrl(new URL("http://localhost:8080/uaa/idp_login"));
    oidcProvider.getConfig().setEmailDomain(Collections.singletonList("example.com"));
    oidcProvider.getConfig().setRelyingPartyId("client_id");
    oidcProvider.getConfig().setRelyingPartySecret("client_secret");
    IntegrationTestUtils.createOrUpdateProvider(adminToken, baseUrl, oidcProvider);
    try {

      startCreateUserFlow("test");

      assertEquals("Account sign-up is not required for this email domain. Please login with the identity provider", webDriver.findElement(By.cssSelector(".alert-error")).getText());
      webDriver.findElement(By.xpath("//input[@value='Login with provider']")).click();
      assertThat(webDriver.getCurrentUrl(), startsWith(oidcProvider.getConfig().getAuthUrl().toString()));
    } finally {
      IntegrationTestUtils.deleteProvider(adminToken, baseUrl, OriginKeys.UAA, OriginKeys.OIDC10);
    }
  }
}

代码示例来源:origin: cloudfoundry/uaa

@Test
public void login_with_wrong_keys() throws Exception {
  identityProvider.getConfig().setTokenKeyUrl(new URL("https://login.microsoftonline.com/9bc40aaf-e150-4c30-bb3c-a8b3b677266e/discovery/v2.0/keys"));
  updateProvider();
  webDriver.get(zoneUrl + "/login");
  webDriver.findElement(By.linkText("My OIDC Provider")).click();
  Assert.assertThat(webDriver.getCurrentUrl(), containsString(baseUrl));
  webDriver.findElement(By.name("username")).sendKeys("marissa");
  webDriver.findElement(By.name("password")).sendKeys("koala");
  webDriver.findElement(By.xpath("//input[@value='Sign in']")).click();
  Assert.assertThat(webDriver.getCurrentUrl(), containsString(zoneUrl + "/oauth_error?error=There+was+an+error+when+authenticating+against+the+external+identity+provider"));
  List<String> cookies = IntegrationTestUtils.getAccountChooserCookies(zoneUrl, webDriver);
  assertThat(cookies, not(Matchers.hasItem(startsWith("Saved-Account-"))));
}

代码示例来源:origin: TEAMMATES/teammates

.withInstructorInstitution(institute)
                        .toAbsoluteString();
String expectedJoinLinkUrlFileName = new URL(expectedjoinUrl).getFile();
String actualJoinLink = homePage.getJoinLink(homePage.getMessageFromResultTable(2));
String actualJoinLinkUrlFileName = new URL(actualJoinLink).getFile();
browser.driver.get(joinLink);
InstructorCourseJoinConfirmationPage confirmationPage =
    AppPage.createCorrectLoginPageType(browser)
confirmationPage.clickCancelButton();
browser.driver.get(joinLink);
confirmationPage = AppPage.createCorrectLoginPageType(browser)
          .loginAsJoiningInstructor(TestProperties.TEST_INSTRUCTOR_ACCOUNT,

代码示例来源:origin: org.juzu/juzu-core

@Test
 @RunAsClient
 public void test() throws Exception {
  driver.get(applicationURL().toString());
  System.out.println(driver.getPageSource());
  WebDriverWait wait = new WebDriverWait(driver, 5);
  wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html[@bar]")));
  WebElement elt = driver.findElement(By.tagName("html"));
  assertEquals("<bar>foo_value</bar>", elt.getAttribute("bar"));
 }
}

代码示例来源:origin: org.gatein.pc/pc-embed

@Test
@RunAsClient
@InSequence(1)
public void testInteraction(@ArquillianResource URL deploymentURL) throws Exception
{
 URL url = renderURL(deploymentURL, RenderURLPortlet.class);
 driver.get(url.toString());
 WebElement link = driver.findElement(By.id("url"));
 link.click();
}

代码示例来源:origin: cloudfoundry/uaa

URL inviteLink = response.getBody().getNewInvites().get(0).getInviteLink();
webDriver.get(inviteLink.toString());
webDriver.findElement(By.xpath("//h1[contains(text(), 'Welcome')]"));
webDriver.findElement(By.name("username")).clear();
webDriver.findElement(By.name("username")).sendKeys("marissa");
webDriver.findElement(By.name("password")).sendKeys("koala");
webDriver.findElement(By.xpath("//input[@value='Sign in']")).click();
webDriver.get("https://oidc10.oms.identity.team/logout.do");
IntegrationTestUtils.deleteProvider(getZoneAdminToken(baseUrl, serverRunning), baseUrl, "uaa", "puppy-invite");

代码示例来源:origin: org.juzu/juzu-doc-tutorial-examples

@Test
@RunAsClient
public void testWeather3() throws Exception {
 URL url = getApplicationURL("weather3");
 driver.get(url.toString());
 WebElement body = driver.findElement(By.tagName("body"));
 assertTrue(body.getText().contains("temperature in marseille"));
 assertTrue(body.getText().contains("10 degrees"));
}

代码示例来源:origin: cloudfoundry/uaa

public void performLogin(String idpZoneId, String idpZoneUserEmail, String idpZoneUrl, IdentityZone spZone, String spZoneUrl, SamlIdentityProviderDefinition samlIdentityProviderDefinition) {
    webDriver.get(baseUrl + "/logout.do");
    webDriver.get(spZoneUrl + "/logout.do");
    webDriver.get(idpZoneUrl+ "/logout.do");
    webDriver.get(spZoneUrl + "/");
    assertEquals(spZone.getName(), webDriver.getTitle());
    Cookie beforeLogin = webDriver.manage().getCookieNamed("JSESSIONID");
    assertNotNull(beforeLogin);
    assertNotNull(beforeLogin.getValue());
      .findElements(By.xpath("//a[text()='" + samlIdentityProviderDefinition.getLinkText() + "']"));
    assertNotNull(elements);
    assertEquals(1, elements.size());
    assertNotNull(element);
    element.click();
  try {
    webDriver.findElement(By.xpath("//h1[contains(text(), 'Welcome to The Twiglet Zone[" + idpZoneId + "]!')]"));
    webDriver.findElement(By.name("username")).clear();
    webDriver.findElement(By.name("username")).sendKeys(idpZoneUserEmail);
    webDriver.findElement(By.name("password")).sendKeys("secr3T");
    webDriver.findElement(By.xpath("//input[@value='Sign in']")).click();
    assertThat(webDriver.findElement(By.cssSelector("h1")).getText(), containsString("Where to?"));
    Cookie afterLogin = webDriver.manage().getCookieNamed("JSESSIONID");
    assertNotNull(afterLogin);
    assertNotNull(afterLogin.getValue());

代码示例来源:origin: cloudfoundry/uaa

webDriver.get(appUrl);
webDriver.findElement(By.name("username")).sendKeys(user.getUserName());
webDriver.findElement(By.name("password")).sendKeys(user.getPassword());
webDriver.findElement(By.xpath("//input[@value='Sign in']")).click();
Assert.assertEquals("Application Authorization", webDriver.findElement(By.cssSelector("h1")).getText());
webDriver.findElement(By.xpath("//label[text()='Change your password']/preceding-sibling::input")).click();
webDriver.findElement(By.xpath("//label[text()='Read user IDs and retrieve users by ID']/preceding-sibling::input")).click();
webDriver.findElement(By.xpath("//label[text()='Read about your clouds.']/preceding-sibling::input"));
webDriver.findElement(By.xpath("//button[text()='Authorize']")).click();
Assert.assertEquals("Sample Home Page", webDriver.findElement(By.cssSelector("h1")).getText());
webDriver.get(baseUrl + "/profile");
Assert.assertFalse(webDriver.findElement(By.xpath("//input[@value='app-password.write']")).isSelected());
Assert.assertFalse(webDriver.findElement(By.xpath("//input[@value='app-scim.userids']")).isSelected());
Assert.assertTrue(webDriver.findElement(By.xpath("//input[@value='app-cloud_controller.read']")).isSelected());
Assert.assertTrue(webDriver.findElement(By.xpath("//input[@value='app-cloud_controller.write']")).isSelected());
webDriver.findElement(By.xpath("//input[@value='app-password.write']")).click();
webDriver.findElement(By.xpath("//input[@value='app-scim.userids']")).click();
webDriver.findElement(By.xpath("//button[text()='Update']")).click();
Assert.assertTrue(webDriver.findElement(By.xpath("//input[@value='app-password.write']")).isSelected());

代码示例来源:origin: cloudfoundry/uaa

private void beginPasswordReset(String username) {
  webDriver.get(baseUrl + "/login");
  Assert.assertEquals("Cloud Foundry", webDriver.getTitle());
  webDriver.findElement(By.linkText("Reset password")).click();
  Assert.assertEquals("Reset Password", webDriver.findElement(By.tagName("h1")).getText());
  // Enter email address
  webDriver.findElement(By.name("username")).sendKeys(username);
  webDriver.findElement(By.xpath("//input[@value='Send reset password link']")).click();
  Assert.assertEquals("Instructions Sent", webDriver.findElement(By.tagName("h1")).getText());
}

代码示例来源:origin: cloudfoundry/uaa

@Test
public void testAccountChooserPopulatesUsernameNotEmailWhenOriginIsUAAorLDAP() throws Exception {
  String userUAA = "{\"userId\":\"1\",\"username\":\"userUAA\",\"origin\":\"uaa\",\"email\":\"user@uaa.org\"}";
  String userLDAP = "{\"userId\":\"2\",\"username\":\"userLDAP\",\"origin\":\"ldap\",\"email\":\"user@ldap.org\"}";
  String userExternal = "{\"userId\":\"3\",\"username\":\"userExternal\",\"origin\":\"external\",\"email\":\"user@external.org\"}";
  String zoneUrl = createDiscoveryZone();
  webDriver.get(zoneUrl);
  webDriver.manage().deleteAllCookies();
  JavascriptExecutor js = (JavascriptExecutor) webDriver;
  js.executeScript("document.cookie = \"Saved-Account-1=" + URLEncoder.encode(userUAA, StandardCharsets.UTF_8.name()) + ";path=/;domain=testzone3.localhost\"");
  js.executeScript("document.cookie = \"Saved-Account-2=" + URLEncoder.encode(userLDAP, StandardCharsets.UTF_8.name()) + ";path=/;domain=testzone3.localhost\"");
  js.executeScript("document.cookie = \"Saved-Account-3=" + URLEncoder.encode(userExternal, StandardCharsets.UTF_8.name()) + ";path=/;domain=testzone3.localhost\"");
  webDriver.navigate().refresh();
  assertEquals(3, webDriver.findElements(By.cssSelector("span.email-address")).size());
  webDriver.findElement(By.xpath("//span[contains(text(), 'userUAA')]")).click();
  assertEquals("userUAA", webDriver.findElement(By.id("username")).getAttribute("value"));
  webDriver.navigate().back();
  webDriver.findElement(By.xpath("//span[contains(text(), 'userLDAP')]")).click();
  assertEquals("userLDAP", webDriver.findElement(By.id("username")).getAttribute("value"));
  webDriver.navigate().back();
  webDriver.findElement(By.xpath("//span[contains(text(), 'userExternal')]")).click();
  assertEquals("user@external.org", webDriver.findElement(By.id("username")).getAttribute("value"));
  webDriver.manage().deleteAllCookies();
}

代码示例来源:origin: cloudfoundry/uaa

@Test
public void testBannerFunctionalityInDiscoveryPage() {
  String zoneId = "testzone3";
  RestTemplate identityClient = IntegrationTestUtils.getClientCredentialsTemplate(
    IntegrationTestUtils.getClientCredentialsResource(baseUrl, new String[]{"zones.write", "zones.read", "scim.zones"}, "identity", "identitysecret")
  );
  IdentityZoneConfiguration config = new IdentityZoneConfiguration();
  config.setIdpDiscoveryEnabled(true);
  Banner banner = new Banner();
  banner.setText("test banner");
  banner.setBackgroundColor("#444");
  banner.setTextColor("#111");
  config.setBranding(new BrandingInformation());
  config.getBranding().setBanner(banner);
  IntegrationTestUtils.createZoneOrUpdateSubdomain(identityClient, baseUrl, zoneId, zoneId, config);
  String zoneUrl = baseUrl.replace("localhost",zoneId+".localhost");
  webDriver.get(zoneUrl);
  webDriver.manage().deleteAllCookies();
  webDriver.navigate().refresh();
  assertEquals("test banner", webDriver.findElement(By.cssSelector(".banner-header span")).getText());
  assertEquals("rgba(68, 68, 68, 1)", webDriver.findElement(By.cssSelector(".banner-header")).getCssValue("background-color"));
  assertEquals("rgba(17, 17, 17, 1)", webDriver.findElement(By.cssSelector(".banner-header span")).getCssValue("color"));
  String base64Val = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAATBJREFUeNqk008og3Ecx/HNnrJSu63kIC5qKRe7KeUiOSulTHJUTrsr0y5ycFaEgyQXElvt5KDYwU0uO2hSUy4KoR7v7/qsfmjPHvzq1e/XU8/39/3zPFHf9yP/WV7jED24nGRbxDFWUAsToM05zyKFLG60d/wmQBxWzwyOlMU1phELEyCmtPeRQRoVbKOM0VYB6q0QW+3IYQpJFFDEYFCAiMqwNY857Ko3SxjGBTbRXb+xMUamcMbWh148YwJvOHSCdyqTAdxZo72ADGwKT98C9CChcxUPQSVYLz50toae4Fy9WcAISl7AiN/RhS1N5RV5rOLxx5eom90pvGAI/VjHMm6bfspK18a1gXvsqM41XDVL052C1Tim56cYd/rR+mdSrXGluxfm5S8Z/HV9CjAAvQZLXoa5mpgAAAAASUVORK5CYII=";
  banner.setLogo(base64Val);
  IntegrationTestUtils.createZoneOrUpdateSubdomain(identityClient, baseUrl, zoneId, zoneId, config);
  webDriver.get(zoneUrl);
  assertEquals("data:image/png;base64," + base64Val, webDriver.findElement(By.cssSelector(".banner-header img")).getAttribute("src"));
  assertEquals(2, webDriver.findElement(By.cssSelector(".banner-header")).findElements(By.xpath(".//*")).size());
}

代码示例来源:origin: cloudfoundry/uaa

@Test
public void testQRCodeValidation() {
  performLogin(username);
  assertEquals(zoneUrl + "/login/mfa/register", webDriver.getCurrentUrl());
  webDriver.findElement(By.id("Next")).click();
  assertEquals(zoneUrl + "/login/mfa/verify", webDriver.getCurrentUrl());
  webDriver.findElement(By.name("code")).sendKeys("1111111111111111112222");
  webDriver.findElement(By.id("verify_code_btn")).click();
  assertEquals("Incorrect code, please try again.", webDriver.findElement(By.cssSelector("form .error-color")).getText());
}

相关文章