Java Code Examples for org.openqa.selenium.WebElement#findElements()

The following examples show how to use org.openqa.selenium.WebElement#findElements() . 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: DesignTacoControllerBrowserTest.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore("TODO: Need to get around authentication in this test")
public void testDesignATacoPage() throws Exception {
  browser.get("http://localhost:" + port + "/design");

  List<WebElement> ingredientGroups = browser.findElementsByClassName("ingredient-group");
  assertEquals(5, ingredientGroups.size());
  
  WebElement wrapGroup = ingredientGroups.get(0);
  List<WebElement> wraps = wrapGroup.findElements(By.tagName("div"));
  assertEquals(2, wraps.size());
  assertIngredient(wrapGroup, 0, "FLTO", "Flour Tortilla");
  assertIngredient(wrapGroup, 1, "COTO", "Corn Tortilla");
  
  WebElement proteinGroup = ingredientGroups.get(1);
  List<WebElement> proteins = proteinGroup.findElements(By.tagName("div"));
  assertEquals(2, proteins.size());
  assertIngredient(proteinGroup, 0, "GRBF", "Ground Beef");
  assertIngredient(proteinGroup, 1, "CARN", "Carnitas");
}
 
Example 2
Source File: HTMLSelectElementTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void optionClick() throws Exception {
    final String html
        = "<html><body>\n"
        + "<select id='s' multiple>\n"
        + "  <option selected value='one'>One</option>\n"
        + "  <option value='two'>Two</option>\n"
        + "  <option selected value='three'>Three</option>\n"
        + "</select>\n"
        + "</body></html>";

    final WebDriver driver = loadPage2(html);
    final WebElement multiSelect = driver.findElement(By.id("s"));
    final List<WebElement> options = multiSelect.findElements(By.tagName("option"));

    assertTrue(options.get(0).isSelected());
    assertFalse(options.get(1).isSelected());
    assertTrue(options.get(2).isSelected());

    options.get(0).click();

    assertFalse(options.get(0).isSelected());
    assertFalse(options.get(1).isSelected());
    assertTrue(options.get(2).isSelected());
}
 
Example 3
Source File: QueuesBrowsePage.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Navigates the browser to 'Queue Content' page where user can see messages it contains etc.
 *
 * @param qName name of the Queue to browse
 * @return true if the navigate operation is successful, false otherwise
 */
public QueueContentPage browseQueue(final String qName) throws IOException {

    WebElement row = getTableRowByQueueName(qName);
    if (row == null) {
        log.warn("unable to find the table row for queue name: " + qName);
        return null;    // can't find the queue.
    }

    List<WebElement> columnList = row.findElements(By.tagName("td"));
    WebElement browseButton = columnList.get(2).findElement(By.tagName("a"));
    if (browseButton != null) {
        browseButton.click();
    }
    return new QueueContentPage(this.driver);
}
 
Example 4
Source File: DesignTacoControllerBrowserTest.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore("TODO: Need to get around authentication in this test")
public void testDesignATacoPage() throws Exception {
  browser.get("http://localhost:" + port + "/design");

  List<WebElement> ingredientGroups = browser.findElementsByClassName("ingredient-group");
  assertEquals(5, ingredientGroups.size());
  
  WebElement wrapGroup = ingredientGroups.get(0);
  List<WebElement> wraps = wrapGroup.findElements(By.tagName("div"));
  assertEquals(2, wraps.size());
  assertIngredient(wrapGroup, 0, "FLTO", "Flour Tortilla");
  assertIngredient(wrapGroup, 1, "COTO", "Corn Tortilla");
  
  WebElement proteinGroup = ingredientGroups.get(1);
  List<WebElement> proteins = proteinGroup.findElements(By.tagName("div"));
  assertEquals(2, proteins.size());
  assertIngredient(proteinGroup, 0, "GRBF", "Ground Beef");
  assertIngredient(proteinGroup, 1, "CARN", "Carnitas");
}
 
Example 5
Source File: JTableDialogEditTest.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
public void getCellEditor() throws Throwable {
    driver = new JavaDriver();
    WebElement cell = driver.findElement(By.cssSelector("table::mnth-cell(1,2)::editor"));
    AssertJUnit.assertEquals("button", cell.getTagName());
    cell.click();
    driver.switchTo().window("Pick a Color");
    WebElement tab = driver.findElement(By.cssSelector("tabbed-pane::all-tabs[text='RGB']"));
    tab.click();
    WebElement tabcomponent = driver.findElement(By.cssSelector("tabbed-pane::all-tabs[text='RGB']::component"));
    List<WebElement> spinners = tabcomponent.findElements(By.cssSelector("spinner"));
    List<WebElement> all = spinners.get(0).findElements(By.cssSelector("*"));
    List<String> s = new ArrayList<String>();
    for (WebElement webElement : all) {
        s.add(webElement.getTagName());
    }
    WebElement tf = spinners.get(0).findElement(By.cssSelector("formatted-text-field"));
    tf.clear();
    tf.sendKeys("234", Keys.TAB);
    driver.findElement(By.cssSelector("button[text='OK']")).click();
}
 
Example 6
Source File: FlowsTable.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public Map<String, String> getFlowsAliasesWithRequirements(){
    Map<String, String> flows = new LinkedHashMap<>();
    List<WebElement> aliases = tbody.findElements(By.xpath("//span[@class='ng-binding']"));

    for(WebElement alias : aliases)
    {
        List<WebElement> requirementsOptions = alias.findElements(By.xpath(".//../parent::*//input[@type='radio']"));
        for (WebElement requirement : requirementsOptions) {
            if (requirement.isSelected()) {
                flows.put(getTextFromElement(alias), requirement.getAttribute("value"));
            }
        }
    }
    return flows;
}
 
Example 7
Source File: OpenIdConnectClientManagePage.java    From oxTrust with MIT License 5 votes vote down vote up
public void editClient(String scope) {
	WebElement body = webDriver.findElement(By.className(CLIENTS_FORM_IDCLIENTS_LIST_ID_TABLE)).findElements(By.tagName("tbody"))
			.get(0);
	List<WebElement> listItems = body.findElements(By.tagName("tr"));
	for (WebElement element : listItems) {
		if (element.getText().contains(scope)) {
			element.findElements(By.tagName("td")).get(0).click();
			break;
		}
	}
}
 
Example 8
Source File: WithTagListPage.java    From mamute with Apache License 2.0 5 votes vote down vote up
private boolean containsTag(WebElement question, String tag) {
	List<WebElement> questionTags = question.findElements(className("tag"));
	for (WebElement currentTag : questionTags) {
		if(currentTag.getText().equals(tag)){
			return true;
		}
	}
	return false;
}
 
Example 9
Source File: LibraryFieldsActionAft.java    From rice with Educational Community License v2.0 5 votes vote down vote up
protected void testActionFieldImages() throws Exception {
    WebElement exampleDiv = navigateToExample("Demo-ActionField-Example5");
    List<WebElement> fields = exampleDiv.findElements(By.cssSelector("a.uif-actionLink"));

    assertEquals(2, fields.size());

    WebElement leftField = fields.get(0);
    WebElement rightField = fields.get(1);

    String leftFieldId = leftField.getAttribute("id");
    String rightFieldId = rightField.getAttribute("id");

    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    XPath xPathFactory = XPathFactory.newInstance().newXPath();
    Document document = builder.parse(IOUtils.toInputStream(driver.getPageSource()));

    Node leftFieldImg = (Node) xPathFactory.evaluate("//a[@id='" + leftFieldId + "']/img", document,
            XPathConstants.NODE);
    Node leftFieldImgNextSibling = leftFieldImg.getNextSibling();
    if (!leftFieldImgNextSibling.getTextContent().contains("Action Link with left image")) {
        fail("Image is not on the left of the link");
    }

    Node rightFieldText = (Node) xPathFactory.evaluate(
            "//a[@id='" + rightFieldId + "']/text()[contains(., 'Action Link with right image')]", document,
            XPathConstants.NODE);
    Node rightFieldTextNextSibling = rightFieldText.getNextSibling();
    if (!rightFieldTextNextSibling.getNodeName().equals("img")) {
        fail("Image is not on the right of the link");
    }
}
 
Example 10
Source File: DesignAndOrderTacosBrowserTest.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
private void assertIngredient(WebElement ingredientGroup, 
                              int ingredientIdx, String id, String name) {
  List<WebElement> proteins = ingredientGroup.findElements(By.tagName("div"));
  WebElement ingredient = proteins.get(ingredientIdx);
  assertEquals(id, 
      ingredient.findElement(By.tagName("input")).getAttribute("value"));
  assertEquals(name, 
      ingredient.findElement(By.tagName("span")).getText());
}
 
Example 11
Source File: DesignAndOrderTacosBrowserTest.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
private void assertDesignPageElements() {
  assertEquals(designPageUrl(), browser.getCurrentUrl());
  List<WebElement> ingredientGroups = browser.findElementsByClassName("ingredient-group");
  assertEquals(5, ingredientGroups.size());
  
  WebElement wrapGroup = browser.findElementByCssSelector("div.ingredient-group#wraps");
  List<WebElement> wraps = wrapGroup.findElements(By.tagName("div"));
  assertEquals(2, wraps.size());
  assertIngredient(wrapGroup, 0, "FLTO", "Flour Tortilla");
  assertIngredient(wrapGroup, 1, "COTO", "Corn Tortilla");
  
  WebElement proteinGroup = browser.findElementByCssSelector("div.ingredient-group#proteins");
  List<WebElement> proteins = proteinGroup.findElements(By.tagName("div"));
  assertEquals(2, proteins.size());
  assertIngredient(proteinGroup, 0, "GRBF", "Ground Beef");
  assertIngredient(proteinGroup, 1, "CARN", "Carnitas");

  WebElement cheeseGroup = browser.findElementByCssSelector("div.ingredient-group#cheeses");
  List<WebElement> cheeses = proteinGroup.findElements(By.tagName("div"));
  assertEquals(2, cheeses.size());
  assertIngredient(cheeseGroup, 0, "CHED", "Cheddar");
  assertIngredient(cheeseGroup, 1, "JACK", "Monterrey Jack");

  WebElement veggieGroup = browser.findElementByCssSelector("div.ingredient-group#veggies");
  List<WebElement> veggies = proteinGroup.findElements(By.tagName("div"));
  assertEquals(2, veggies.size());
  assertIngredient(veggieGroup, 0, "TMTO", "Diced Tomatoes");
  assertIngredient(veggieGroup, 1, "LETC", "Lettuce");

  WebElement sauceGroup = browser.findElementByCssSelector("div.ingredient-group#sauces");
  List<WebElement> sauces = proteinGroup.findElements(By.tagName("div"));
  assertEquals(2, sauces.size());
  assertIngredient(sauceGroup, 0, "SLSA", "Salsa");
  assertIngredient(sauceGroup, 1, "SRCR", "Sour Cream");
}
 
Example 12
Source File: LibraryFieldsGroupLinkAft.java    From rice with Educational Community License v2.0 5 votes vote down vote up
protected void testGroupLinkFieldDefault() throws Exception {
    jGrowl("-- testGroupLinkFieldDefault");
    WebElement exampleDiv = navigateToExample(DEMO_PAGE_ID1);
    assertTextPresent(DEMO_PAGE_HEADER1);

    WebElement field = findElement(By.cssSelector(UIF_LINK_CSS_SELECTOR), exampleDiv);
    List<WebElement> links = exampleDiv.findElements(By.className(UIF_LINK_CLASSNAME));
    assertEquals("Number of expected group field links not found on page.", 2, links.size());

    for ( WebElement link : links) {
        String href =  link.getAttribute(HREF_ATTRIBUTE);
        if ( !StringUtils.contains(href, INQUIRY)) {
            fail("Inquiry not found in link.");
        }

        if ( !(StringUtils.contains(href, GROUP_INQUIRY_KEY_ID1) ||
                (StringUtils.contains(href, GROUP_INQUIRY_KEY_NAMESPACECODE2) &&
                 StringUtils.contains(href, GROUP_INQUIRY_KEY_NAME2)))) {
            fail("Group inquiry keys not found in href.");
        }

        String linkText = link.getText();
        if ( !(StringUtils.contains(linkText, GROUP_LINKTEXT1) ||
               StringUtils.contains(linkText, GROUP_LINKTEXT2))) {
            fail("Group names in linkText not found");
        }
    }

    field = findElement(By.linkText(GROUP_LINKTEXT1), exampleDiv);
    verifyLinkDataItem(field, LABEL_GROUP_NAME, GROUP_NAME1);

    field = findElement(By.linkText(GROUP_LINKTEXT2), exampleDiv);
    verifyLinkDataItem(field, LABEL_GROUP_NAME, GROUP_NAME2);
}
 
Example 13
Source File: StatisticDataIT.java    From AisAbnormal with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void checkStatisticDataDisplayedCorrectlyForClickedCell() {
    // Check that a tab is shown for each statistic
    List<WebElement> tabs = browser.findElements(By.cssSelector("div#cell-data-tabs.tabs li"));
    assertNotNull(tabs);
    assertEquals(3, tabs.size());
    assertEquals("CourseOverGround", tabs.get(0).getText());
    assertEquals("ShipTypeAndSize", tabs.get(1).getText());
    assertEquals("SpeedOverGround", tabs.get(2).getText());

    // Check course over ground data
    browser.findElement(By.cssSelector("a#tab-CourseOverGround.ui-tabs-anchor")).click();
    WebElement cogTab = browser.findElement(By.cssSelector("div[aria-labelledby=\"tab-CourseOverGround\"]"));
    List<WebElement> cogTabDivs = cogTab.findElements(By.tagName("div"));
    assertEquals("Total ship count is 8.", cogTabDivs.get(1).getText());

    // Check ship type and size data
    browser.findElement(By.cssSelector("a#tab-ShipTypeAndSize.ui-tabs-anchor")).click();
    WebElement stsTab = browser.findElement(By.cssSelector("div[aria-labelledby=\"tab-ShipTypeAndSize\"]"));
    List<WebElement> stsTabDivs = stsTab.findElements(By.tagName("div"));
    assertEquals("Total ship count is 8.", stsTabDivs.get(1).getText());

    // Check speed over ground data
    browser.findElement(By.cssSelector("a#tab-SpeedOverGround.ui-tabs-anchor")).click();
    WebElement sogTab = browser.findElement(By.cssSelector("div[aria-labelledby=\"tab-SpeedOverGround\"]"));
    List<WebElement> sogTabDivs = sogTab.findElements(By.tagName("div"));
    assertEquals("Total ship count is 8.", sogTabDivs.get(1).getText());
}
 
Example 14
Source File: PermissionsTable.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public PolicyRepresentation toRepresentation(WebElement row) {
    PolicyRepresentation representation = null;
    List<WebElement> tds = row.findElements(tagName("td"));
    if (!(tds.isEmpty() || getTextFromElement(tds.get(1)).isEmpty())) {
        representation = new PolicyRepresentation();
        representation.setName(getTextFromElement(tds.get(1)));
        representation.setDescription(getTextFromElement(tds.get(2)));
        representation.setType(getTextFromElement(tds.get(3)));
    }
    return representation;
}
 
Example 15
Source File: DesignAndOrderTacosBrowserTest.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
private void assertDesignPageElements() {
  assertEquals(designPageUrl(), browser.getCurrentUrl());
  List<WebElement> ingredientGroups = browser.findElementsByClassName("ingredient-group");
  assertEquals(5, ingredientGroups.size());
  
  WebElement wrapGroup = browser.findElementByCssSelector("div.ingredient-group#wraps");
  List<WebElement> wraps = wrapGroup.findElements(By.tagName("div"));
  assertEquals(2, wraps.size());
  assertIngredient(wrapGroup, 0, "FLTO", "Flour Tortilla");
  assertIngredient(wrapGroup, 1, "COTO", "Corn Tortilla");
  
  WebElement proteinGroup = browser.findElementByCssSelector("div.ingredient-group#proteins");
  List<WebElement> proteins = proteinGroup.findElements(By.tagName("div"));
  assertEquals(2, proteins.size());
  assertIngredient(proteinGroup, 0, "GRBF", "Ground Beef");
  assertIngredient(proteinGroup, 1, "CARN", "Carnitas");

  WebElement cheeseGroup = browser.findElementByCssSelector("div.ingredient-group#cheeses");
  List<WebElement> cheeses = proteinGroup.findElements(By.tagName("div"));
  assertEquals(2, cheeses.size());
  assertIngredient(cheeseGroup, 0, "CHED", "Cheddar");
  assertIngredient(cheeseGroup, 1, "JACK", "Monterrey Jack");

  WebElement veggieGroup = browser.findElementByCssSelector("div.ingredient-group#veggies");
  List<WebElement> veggies = proteinGroup.findElements(By.tagName("div"));
  assertEquals(2, veggies.size());
  assertIngredient(veggieGroup, 0, "TMTO", "Diced Tomatoes");
  assertIngredient(veggieGroup, 1, "LETC", "Lettuce");

  WebElement sauceGroup = browser.findElementByCssSelector("div.ingredient-group#sauces");
  List<WebElement> sauces = proteinGroup.findElements(By.tagName("div"));
  assertEquals(2, sauces.size());
  assertIngredient(sauceGroup, 0, "SLSA", "Salsa");
  assertIngredient(sauceGroup, 1, "SRCR", "Sour Cream");
}
 
Example 16
Source File: InstructorFeedbackResultsPage.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
public void deselectUsersInRemindAllForm() {
    WebElement remindModal = browser.driver.findElement(By.id("remindModal"));
    List<WebElement> usersToRemind = remindModal.findElements(By.name("usersToRemind"));
    for (WebElement e : usersToRemind) {
        markCheckBoxAsUnchecked(e);
    }
}
 
Example 17
Source File: LibraryFieldsRoleLinkAft.java    From rice with Educational Community License v2.0 5 votes vote down vote up
protected void testRoleLinkFieldDefault() throws Exception {
    jGrowl("-- testRoleLinkFieldDefault");
    WebElement exampleDiv = navigateToExample(DEMO_PAGE_ID1);
    assertTextPresent(DEMO_PAGE_HEADER1);

    WebElement field = findElement(By.cssSelector(UIF_LINK_CSS_SELECTOR), exampleDiv);
    List<WebElement> links = exampleDiv.findElements(By.className(UIF_LINK_CLASSNAME));
    assertEquals("Number of expected role field links not found on page.", 2, links.size());

    for ( WebElement link : links) {
        String href =  link.getAttribute(HREF_ATTRIBUTE);
        if ( !StringUtils.contains(href, INQUIRY)) {
            fail("Inquiry not found in link.");
        }

        if ( !(StringUtils.contains(href, ROLE_INQUIRY_KEY_ID1) ||
                (StringUtils.contains(href, ROLE_INQUIRY_KEY_NAMESPACECODE2) &&
                        StringUtils.contains(href, ROLE_INQUIRY_KEY_NAME2)))) {
            fail("Role inquiry keys not found in href.");
        }

        String linkText = link.getText();
        if ( !(StringUtils.contains(linkText, ROLE_LINKTEXT1) ||
               StringUtils.contains(linkText, ROLE_LINKTEXT2))) {
            fail("Role names in linkText not found");
        }
    }

    field = findElement(By.linkText(ROLE_LINKTEXT1), exampleDiv);
    verifyLinkDataItem(field, LABEL_ROLE_NAME, ROLE_NAME1);

    field = findElement(By.linkText(ROLE_LINKTEXT2), exampleDiv);
    verifyLinkDataItem(field, LABEL_ROLE_NAME, ROLE_NAME2);
}
 
Example 18
Source File: AttachExistingElementIT.java    From flow with Apache License 2.0 4 votes vote down vote up
@Test
public void attachExistingElement() {
    open();

    // attach label
    findElement(By.id("attach-label")).click();

    Assert.assertTrue(isElementPresent(By.id("label")));
    WebElement label = findElement(By.id("label"));
    Assert.assertEquals("label",
            label.getTagName().toLowerCase(Locale.ENGLISH));

    WebElement parentDiv = findElement(By.id("root-div"));
    List<WebElement> children = parentDiv
            .findElements(By.xpath("./child::*"));
    boolean labelIsFoundAsChild = false;
    WebElement removeButton = null;
    for (int i = 0; i < children.size(); i++) {
        WebElement child = children.get(i);
        if (child.equals(label)) {
            labelIsFoundAsChild = true;
            WebElement attachButton = children.get(i + 1);
            Assert.assertEquals("The first inserted component after "
                    + "attached label has wrong index on the client side",
                    "attach-populated-label",
                    attachButton.getAttribute("id"));
            removeButton = children.get(i + 2);
            Assert.assertEquals("The second inserted component after "
                    + "attached label has wrong index on the client side",
                    "remove-self", removeButton.getAttribute("id"));
            break;
        }
    }

    Assert.assertTrue(
            "The attached label is not found as a child of its parent",
            labelIsFoundAsChild);

    removeButton.click();
    Assert.assertFalse(isElementPresent(By.id("remove-self")));

    // attach existing server-side element
    findElement(By.id("attach-populated-label")).click();
    Assert.assertEquals("already-populated", label.getAttribute("class"));

    // attach header element
    findElement(By.id("attach-header")).click();

    Assert.assertTrue(isElementPresent(By.id("header")));
    Assert.assertEquals("h1", findElement(By.id("header")).getTagName()
            .toLowerCase(Locale.ENGLISH));

    // attach a child in the shadow root of the div

    findElement(By.id("attach-label-inshadow")).click();
    LabelElement labelInShadow = $(DivElement.class)
            .id("element-with-shadow").$(LabelElement.class)
            .id("label-in-shadow");
    Assert.assertEquals("label",
            labelInShadow.getTagName().toLowerCase(Locale.ENGLISH));

    // Try to attach non-existing element
    findElement(By.id("non-existing-element")).click();
    Assert.assertTrue(isElementPresent(By.id("non-existing-element")));
}
 
Example 19
Source File: PwaTestIT.java    From flow with Apache License 2.0 4 votes vote down vote up
@Test
public void testPwaResources() throws IOException, JSONException {
    open();

    WebElement head = findElement(By.tagName("head"));

    // test mobile capable
    Assert.assertEquals(1, head
            .findElements(By.name("apple-mobile-web-app-capable")).size());

    // test theme color
    Assert.assertEquals(
            1, head
                    .findElements(By
                            .xpath("//meta[@name='theme-color'][@content='"
                                    + ParentLayout.THEME_COLOR + "']"))
                    .size());

    // test theme color for apple mobile
    Assert.assertEquals(1, head.findElements(
            By.xpath("//meta[@name='apple-mobile-web-app-status-bar-style']"
                    + "[@content='" + ParentLayout.THEME_COLOR + "']"))
            .size());
    // icons test
    checkIcons(head.findElements(By.xpath("//link[@rel='shortcut icon']")),
            1);

    checkIcons(head.findElements(
            By.xpath("//link[@rel='icon'][@sizes][@href]")), 2);

    checkIcons(head.findElements(
            By.xpath("//link[@rel='apple-touch-icon'][@sizes][@href]")), 1);

    checkIcons(head.findElements(By.xpath(
            "//link[@rel='apple-touch-startup-image'][@sizes][@href]")), 4);

    // test web manifest
    List<WebElement> elements = head
            .findElements(By.xpath("//link[@rel='manifest'][@href]"));
    Assert.assertEquals(1, elements.size());
    String href = elements.get(0).getAttribute("href");
    Assert.assertTrue(href + " didn't respond with resource", exists(href));
    // Verify user values in manifest.webmanifest
    JSONObject manifest = readJsonFromUrl(href);
    Assert.assertEquals(ParentLayout.PWA_NAME, manifest.getString("name"));
    Assert.assertEquals(ParentLayout.PWA_SHORT_NAME,
            manifest.getString("short_name"));
    Assert.assertEquals(ParentLayout.BG_COLOR,
            manifest.getString("background_color"));
    Assert.assertEquals(ParentLayout.THEME_COLOR,
            manifest.getString("theme_color"));

    // test service worker initialization
    elements = head.findElements(By.tagName("script")).stream()
            .filter(webElement -> webElement.getAttribute("innerHTML")
                    .startsWith("if ('serviceWorker' in navigator)"))
            .collect(Collectors.toList());
    Assert.assertEquals(1, elements.size());

    String serviceWorkerInit = elements.get(0).getAttribute("innerHTML");
    Pattern pattern = Pattern
            .compile("navigator.serviceWorker.register\\('([^']+)'\\)");
    Matcher matcher = pattern.matcher(serviceWorkerInit);
    Assert.assertTrue("Service worker initialization missing",
            matcher.find());

    String serviceWorkerUrl = matcher.group(1).startsWith("http")
            ? matcher.group(1)
            : getRootURL() + "/" + matcher.group(1);

    Assert.assertTrue("Service worker not served at: " + serviceWorkerUrl,
            exists(serviceWorkerUrl));

    String serviceWorkerJS = readStringFromUrl(serviceWorkerUrl);
    // find precache resources from service worker
    pattern = Pattern.compile("\\{ url: '([^']+)', revision: '[^']+' }");
    matcher = pattern.matcher(serviceWorkerJS);
    // Test that all precache resources are available
    while (matcher.find()) {
        Assert.assertTrue(
                matcher.group(1) + " didn't respond with resource",
                exists(matcher.group(1)));
    }
}
 
Example 20
Source File: WebWhatsapp.java    From Java-WhatsappChatBot with MIT License 4 votes vote down vote up
private void openWhatsapp() {
	/**
	 * wait till whatsapp is loaded after scanning the QR code then type
	 * start in console to start sending messages
	 */
	Scanner sc = new Scanner(System.in);
	String command = sc.next();
	if (!command.equalsIgnoreCase("start")) {
		browser.quit();
		System.exit(1);
	}
	sc.close();

	/**
	 * keep checking for unread count every sleepTime milli secs.
	 * If some elementFound, then click it and set isStarted to true
	 * The while will check for this variable, and then will reply on that element.
	 */
	while (true) {
		try {
			if (isStarted) {
				/**
				 *  once the new messages are found
				 *  get the last message and reply to the user according to it:	
				 */
				WebElement selectedWindow = browser.findElement(By
						.xpath("//div[contains(@class, 'message-list')]"));
				List<WebElement> msgList = selectedWindow.findElements(By
						.xpath("//div[contains(@class,'msg')]"));
				WebElement lastMsgDiv = msgList.get(msgList.size() - 1);
				WebElement lastMsgSpan = lastMsgDiv
						.findElement(By
								.xpath("//span[contains(@class, 'selectable-text')]"));
				String msg = lastMsgSpan.getText();
				reply("I was already chatting with you: " + msg);
				isStarted = false;
			}

			/**
			 *  get the user who just pinged, whose 'unread-count' will be 1 or more
			 */
			List<WebElement> nonSelectedWindows = browser.findElements(By
					.xpath("//span[contains(@class,'unread-count')]"));
			if (!Utils.isEmptyOrNull(nonSelectedWindows)) {
				isStarted = true;
				responseNonSelectedWindow(nonSelectedWindows);
			} else {
				Utils.log("no new msg yet");
				Thread.sleep(sleepTime);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
			break;
		}
	}

	browser.quit();
}