下面列出了org.openqa.selenium.By#xpath ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public By pickFrom(String method, String selector) {
if ("class name".equals(method)) {
return By.className(selector);
} else if ("css selector".equals(method)) {
return By.cssSelector(selector);
} else if ("id".equals(method)) {
return By.id(selector);
} else if ("link text".equals(method)) {
return By.linkText(selector);
} else if ("partial link text".equals(method)) {
return By.partialLinkText(selector);
} else if ("name".equals(method)) {
return By.name(selector);
} else if ("tag name".equals(method)) {
return By.tagName(selector);
} else if ("xpath".equals(method)) {
return By.xpath(selector);
} else {
throw new WebDriverException("Cannot find matching element locator to: " + method);
}
}
@Test
void testDoesElementExistsForTimePeriod()
{
when(webUiContext.getSearchContext()).thenReturn(webElement);
By xpath = By.xpath(XPATH);
IExpectedSearchContextCondition<List<WebElement>> condition = mock(IExpectedSearchContextCondition.class);
when(expectedSearchContextConditions.presenceOfAllElementsLocatedBy(xpath)).thenReturn(condition);
IExpectedSearchContextCondition<Boolean> notCondition = mock(IExpectedSearchContextCondition.class);
when(expectedSearchContextConditions.not(condition)).thenReturn(notCondition);
WaitResult<Boolean> waitResult = new WaitResult<>();
waitResult.setWaitPassed(true);
when(waitActions.wait(webElement, TIMEOUT, notCondition, false)).thenReturn(waitResult);
waitSteps.doesElementExistsForTimePeriod(XPATH, TIMEOUT.getSeconds());
verify(softAssert).assertFalse(String.format("Element with xpath '%s' has existed during '%d' seconds",
XPATH, TIMEOUT.getSeconds()), true);
}
@Test()
public void testMobileTextLocatorWithDoubleQuotesAndContains() {
String xpath = "//android.widget.Button[contains(@text, \"Text text\")]";
By expectedRes = By.xpath("//android.widget.Button[contains(translate(@text, \"TEXT TEXT\", \"text text\"),translate(\"Text text\", \"TEXT TEXT\", \"text text\"))]");
By result = ExtendedElementLocator.toCaseInsensitive(xpath);
Assert.assertEquals(result, expectedRes, "Incorrect converting to caseinsensitive xpath!");
}
@Test
void testFindLinksByTextByLinkText()
{
By innerTextLocator = By.xpath(String.format(".//*[contains(normalize-space(.), \"%1$s\") and "
+ "not(.//*[contains(normalize-space(.), \"%1$s\")])]", TEXT));
SearchContext searchContext = mock(SearchContext.class);
CaseSensitiveTextSearch spy = Mockito.spy(caseSensitiveTextSearch);
List<WebElement> webElements = List.of(mock(WebElement.class));
doReturn(List.of()).when(spy).findElementsByText(searchContext, FULL_INNER_TEXT_LOCATOR, parameters, ANY);
doReturn(webElements).when(spy).findElementsByText(searchContext, innerTextLocator, parameters, ANY);
List<WebElement> foundElements = spy.search(searchContext, parameters);
assertEquals(webElements, foundElements);
}
@Test
void testGetXpathPatternWithoutNormalization()
{
By expectedLocator = By.xpath(".//*[@*='text %' or text()='text %']");
By actualLocator = LocatorUtil.getXPathLocator(false, ELEMENT_WITH_ANY_ATTRIBUTE_NAME_PATTERN,
TEXT_WITH_PERCENT);
assertEquals(expectedLocator, actualLocator);
}
@ParameterizedTest
@CsvSource({XPATH_PARAM, "xpath(.//a)"})
void convertStringToLocatorTest(String locatorAsString)
{
By expected = By.xpath(XPATH);
assertEquals(expected, LocatorFactory.convertStringToLocator(locatorAsString));
}
@Test
void testGetXPathLocatorThroughParentNode3()
{
By expectedLocator = By.xpath("//*[normalize-space(.//@id)='main-content a-b.C_de2']//h1[text()]");
By actualLocator = LocatorUtil.getXPathLocator("//*[.//@id='main-content a-b.C_de2']//h1[text()]");
assertEquals(expectedLocator, actualLocator);
}
@Test()
public void testWebTextLocatorWithSingleQuoteAndContains() {
String xpath = "//div[contains(text(), 'Text text')]";
By expectedRes = By.xpath("//div[contains(translate(text(), 'TEXT TEXT', 'text text'),translate('Text text', 'TEXT TEXT', 'text text'))]");
By result = ExtendedElementLocator.toCaseInsensitive(xpath);
Assert.assertEquals(result, expectedRes, "Incorrect converting to caseinsensitive xpath!");
}
@Test
void testWaitForElementDisappearanceByWithDuration()
{
By by = By.xpath(XPATH);
IExpectedSearchContextCondition<Boolean> condition = mock(IExpectedSearchContextCondition.class);
when(expectedSearchContextConditions.invisibilityOfElement(by)).thenReturn(condition);
WaitResult<Boolean> waitResult = new WaitResult<>();
when(waitActions.wait(webElement, TIMEOUT, condition)).thenReturn(waitResult);
waitResult.setWaitPassed(true);
assertTrue(waitSteps.waitForElementDisappearance(webElement, by, TIMEOUT));
}
@Test
void testGetXpathPatternWithNormalization9()
{
By expectedLocator = By.xpath(".//[text()[normalize-space(translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',"
+ " 'abcdefghijklmnopqrstuvwxyz'))='text %'] or *[normalize-space(translate(.,"
+ " 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'))='text %']]");
By actualLocator = LocatorUtil.getXPathLocator(true, ELEMENT_WITH_ANY_ATTRIBUTE_OR_TEXT_CASE_INSENSITIVE,
TEXT_WITH_PERCENT);
assertEquals(expectedLocator, actualLocator);
}
public static By locateByXPath(final String xPath) {
return By.xpath(xPath);
}
protected void runParagraph(int paragraphNo) {
By by = By.xpath(getParagraphXPath(paragraphNo) + "//span[@class='icon-control-play']");
pollingWait(by, 5);
driver.findElement(by).click();
}
protected boolean waitForParagraph(final int paragraphNo, final String state) {
By locator = By.xpath(getParagraphXPath(paragraphNo)
+ "//div[contains(@class, 'control')]//span[2][contains(.,'" + state + "')]");
WebElement element = pollingWait(locator, MAX_PARAGRAPH_TIMEOUT_SEC);
return element.isDisplayed();
}
public static By getXPathLocatorByInnerTextWithTagName(String tagName, String text)
{
return By.xpath(getXPathByInnerTextWithTagName(tagName, text));
}
public static By getXPathLocatorByFullInnerText(String text)
{
return By.xpath(getXPathByFullInnerTextWithTagName(ANY, text));
}
@Test
public void testExceptionalCases() throws Exception {
______TS("Case where more than 1 question with same question number");
// results page should be able to load incorrect data and still display it gracefully
FeedbackQuestionAttributes firstQuestion = testData.feedbackQuestions.get("qn1InSession4");
assertEquals(1, firstQuestion.questionNumber);
FeedbackQuestionAttributes firstQuestionFromDatastore =
BackDoor.getFeedbackQuestion(firstQuestion.courseId,
firstQuestion.feedbackSessionName,
firstQuestion.questionNumber);
FeedbackQuestionAttributes secondQuestion = testData.feedbackQuestions.get("qn2InSession4");
assertEquals(2, secondQuestion.questionNumber);
// need to retrieve question from datastore to get its questionId
FeedbackQuestionAttributes secondQuestionFromDatastore =
BackDoor.getFeedbackQuestion(secondQuestion.courseId,
secondQuestion.feedbackSessionName,
secondQuestion.questionNumber);
assertEquals(secondQuestion, secondQuestionFromDatastore);
// make both questions have the same question number
secondQuestionFromDatastore.questionNumber = 1;
BackDoor.editFeedbackQuestion(secondQuestionFromDatastore);
resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.instr", "Session with errors");
resultsPage.loadResultQuestionPanel(1);
resultsPage.loadResultQuestionPanel(2);
// compare html for each question panel
// to verify that the right responses are showing for each question
By firstQuestionPanelResponses = By.xpath("//div[contains(@class,'panel')][.//input[@name='questionid'][@value='"
+ firstQuestionFromDatastore.getId() + "']]"
+ "//div[contains(@class, 'table-responsive')]");
resultsPage.verifyHtmlPart(firstQuestionPanelResponses,
"/instructorFeedbackResultsDuplicateQuestionNumberPanel1.html");
By secondQuestionPanelResponses = By.xpath("//div[contains(@class,'panel')][.//input[@name='questionid'][@value='"
+ secondQuestionFromDatastore.getId() + "']]"
+ "//div[contains(@class, 'table-responsive')]");
resultsPage.verifyHtmlPart(secondQuestionPanelResponses,
"/instructorFeedbackResultsDuplicateQuestionNumberPanel2.html");
______TS("Results with sanitized data");
resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.SanitizedTeam.instr",
"Session with sanitized data");
resultsPage.loadResultQuestionPanel(1);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsPageWithSanitizedData.html");
______TS("Results with sanitized data with comments : giver > recipient > question");
resultsPage.displayByGiverRecipientQuestion();
resultsPage.loadResultSectionPanel(0, 1);
resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsPageGQRWithSanitizedData.html");
}
@Test
void testConverter()
{
By expected = By.xpath("//xpath");
assertEquals(expected, converter.convert("By.xpath(//xpath)"));
}
public EByXpath(String locator) {
super(locator, By.xpath(locator));
}
private By getXPathForLookupCardWithName(String credentialName) {
return By.xpath("//div[contains(@class, 'card-pf-view-single-select')]//h2[normalize-space() = '"+ credentialName +"']");
}
/**
* Returns locator for all elements.
*
* @return
*/
public By getMainContainerItemsLocator() {
return By.xpath("//" + this.getMainContainerLocatorName() + "//" + this.getMainContainerItemsName());
}