Java源码示例:org.jbehave.core.annotations.Then
示例1
/**
* Steps checks the <a href="https://en.wikipedia.org/wiki/Favicon">favicon</a> of the tab
* of the browser. It is displayed in DOM in the <head> tag.
* <b> Example</b>
* <pre>
* <head profile="http://www.w3.org/1999/xhtml/vocab">
* <link type="image/png" href="http://promo1dev/sites/promo1/files/<b>srcpart</b>" rel="shortcut icon" />
* </head>
* </pre>
* @param srcpart Part of URL with favicon
*/
@Then("favicon with src containing `$srcpart` exists")
public void ifFaviconWithSrcExists(String srcpart)
{
WebElement faviconElement = baseValidations.assertIfElementExists("Favicon",
new SearchAttributes(ActionAttributeType.XPATH,
new SearchParameters(LocatorUtil.getXPath("//head/link[@rel='shortcut icon' or @rel='icon']"),
Visibility.ALL)));
if (faviconElement != null)
{
String href = faviconElement.getAttribute("href");
if (softAssert.assertNotNull("Favicon contains 'href' attribute", href))
{
softAssert.assertThat("The favicon with the src containing " + srcpart + " exists", href,
containsString(srcpart));
}
}
}
示例2
/**
* Step designed to compare data received from SQL request against examples table;
* Examples table could be build for example via GENERATE_FROM_CSV table transformer.
* Consider complete example:
* <br>When I execute SQL query `${source}` against `$dbKey` and save result to STORY variable `data`
* <br>Then `${data}` matching rows using `` from `$dbKey` is equal to data from:
* <br>{transformer=GENERATE_FROM_CSV, csvPath=${path}/source.csv}
* @param data saved by step:
* When I execute SQL query `$sqlQuery` against `$dbKey` and save result to $scopes variable `$data`"
* @param keys comma-separated list of column's names to map resulting tables rows
* (could be empty - all columns will be used)
* @param dbKey key identifying the database connection used to get data
* @param table rows to compare data against
*/
@Then("`$data` matching rows using `$keys` from `$dbKey` is equal to data from:$table")
public void compareData(List<Map<String, Object>> data, Set<String> keys, String dbKey, ExamplesTable table)
{
JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey);
QueriesStatistic statistics = new QueriesStatistic(jdbcTemplate, jdbcTemplate);
statistics.getTarget().setRowsQuantity(data.size());
Map<Object, Map<String, Object>> targetData = hashMap(keys, data.stream()
.map(m -> m.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> String.valueOf(e.getValue())))));
Map<Object, Map<String, Object>> sourceData = hashMap(keys, table.getRows());
statistics.getSource().setRowsQuantity(sourceData.size());
List<List<EntryComparisonResult>> result = compareData(statistics, sourceData, targetData);
verifyComparisonResult(statistics, filterPassedChecks(result));
}
示例3
/**
* Step is intended to verify SQL state of JDBC connection
* @see <a href="https://en.wikipedia.org/wiki/SQLSTATE">SQL States</a>
* @param dbKey Key identifying the database connection
* @param username Database username
* @param password Database password
* @param comparisonRule The rule to compare values<br>
* (<i>Possible values:<b> is equal to, contains, does not contain</b></i>)
* @param sqlState State of SQL connection
*/
@SuppressWarnings({"try", "EmptyBlock"})
@Then("SQL state for connection to `$dbKey` with username `$username` and password `$password` $comparisonRule "
+ "`$sqlState`")
public void verifySqlState(String dbKey, String username, String password, StringComparisonRule comparisonRule,
String sqlState)
{
String actualSqlState = "00000";
try (Connection connection = dataSources.get(dbKey).getConnection(username, password))
{
// empty statement
}
catch (SQLException e)
{
actualSqlState = e.getSQLState();
}
softAssert.assertThat("SQL state for connection", actualSqlState, comparisonRule.createMatcher(sqlState));
}
示例4
/**
* Checks if XML is equal to expected XML
* @param xml XML
* @param expectedXml Expected XML
*/
@Then("XML `$xml` is equal to `$expectedXml`")
public void compareXmls(String xml, String expectedXml)
{
Diff diff = DiffBuilder.compare(expectedXml).withTest(xml)
.withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndAllAttributes))
.ignoreWhitespace()
.checkForSimilar()
.build();
Iterable<?> allDifferences = diff.getDifferences();
if (allDifferences.iterator().hasNext())
{
StringBuilder stringBuilder = new StringBuilder();
for (Object difference : allDifferences)
{
stringBuilder.append(difference).append(System.lineSeparator());
}
softAssert.recordFailedAssertion(stringBuilder.toString());
}
}
示例5
/**
* Compares two dates according to the given comparison rule. Dates should be in ISO-8601 format.
* @param date1 The first date text string
* @param comparisonRule The rule to compare values
* (<i>Possible values:<b> less than, less than or equal to, greater than, greater than or equal to,
* equal to</b></i>)
* @param date2 The second date text string
*/
@Then("the date '$date1' is $comparisonRule the date '$date2'")
public void compareDates(String date1, ComparisonRule comparisonRule, String date2)
{
try
{
ZonedDateTime zonedDateTime1 = dateUtils.parseDateTime(date1, DateTimeFormatter.ISO_DATE_TIME);
ZonedDateTime zonedDateTime2 = dateUtils.parseDateTime(date2, DateTimeFormatter.ISO_DATE_TIME);
softAssert
.assertThat("Compare dates", zonedDateTime1, comparisonRule.getComparisonRule(zonedDateTime2));
}
catch (DateTimeParseException e)
{
softAssert.recordFailedAssertion(e);
}
}
示例6
/**
* Validates that response <b>header</b> contains expected <b>attributes</b>.
* <p>
* <b>Actions performed at this step:</b>
* </p>
* <ul>
* <li>Checks that HTTP response header contains expected attributes.</li>
* </ul>
* @param httpHeaderName HTTP header name. For example, <b>Content-Type</b>
* @param attributes expected HTTP header attributes. For example, <b>charset=utf-8</b>
*/
@Then("response header '$httpHeaderName' contains attribute: $attributes")
public void assertHeaderContainsAttributes(String httpHeaderName, ExamplesTable attributes)
{
performIfHttpResponseIsPresent(response ->
{
getHeaderByName(response, httpHeaderName).ifPresent(header ->
{
List<String> actualAttributes = Stream.of(header.getElements()).map(HeaderElement::getName)
.collect(Collectors.toList());
for (Parameters row : attributes.getRowsAsParameters(true))
{
String expectedAttribute = row.valueAs("attribute", String.class);
softAssert.assertThat(httpHeaderName + " header contains " + expectedAttribute + " attribute",
actualAttributes, contains(expectedAttribute));
}
});
});
}
示例7
/**
* Step checks value of slider (input element with type = "range")
* @param value A value to check
* @param xpath Xpath to slider
* @see <a href="https://www.w3schools.com/jsref/dom_obj_range.asp"> <i>more about sliders</i></a>
*/
@Then("the value '$value' is selected in a slider by the xpath '$xpath'")
public void verifySliderValue(String value, String xpath)
{
WebElement slider = baseValidations.assertIfElementExists("Slider to verify value in",
new SearchAttributes(ActionAttributeType.XPATH, LocatorUtil.getXPath(xpath)));
if (null != slider)
{
softAssert.assertThat("Slider value", slider.getAttribute("value"), equalTo(value));
}
}
示例8
/**
* Checks, that the current page has a correct relative URL <br>
* A <b>relative URL</b> - points to a file within a web site (like <i>'about.html'</i> or <i>'/products'</i>)<br>
* <p>
* Actions performed at this step:
* <ul>
* <li>Gets the absolute URL of the current page;
* <li>Gets relative URL from it;
* <li>Compares it with the specified relative URL.
* </ul>
* <p>
* @param relativeURL A string value of the relative URL
*/
@Then("the page has the relative URL '$relativeURL'")
public void checkPageRelativeURL(String relativeURL)
{
URI url = UriUtils.createUri(getWebDriver().getCurrentUrl());
// If web application under test is unavailable (no page is opened), an empty URL will be returned
if (url.getPath() != null)
{
String expectedRelativeUrl = relativeURL.isEmpty() ? FORWARD_SLASH : relativeURL;
highlightingSoftAssert.assertEquals("Page has correct relative URL",
UriUtils.buildNewUrl(getWebDriver().getCurrentUrl(), expectedRelativeUrl), url);
return;
}
highlightingSoftAssert.recordFailedAssertion("URL path component is null");
}
示例9
/**
* Checks, that the <b><i>page</i></b> with certain <b>URL</b> is loaded <br>
* <b>URL</b> is the internet address of the current page which is located in the address bar
* <p>
* @param url String value of URL
*/
@Then("the page with the URL '$URL' is loaded")
public void checkUriIsLoaded(String url)
{
String actualUrl = getWebDriver().getCurrentUrl();
highlightingSoftAssert.assertEquals("Page has correct URL", decodeUrl(url), decodeUrl(actualUrl));
}
示例10
/**
* Checks if the text in context matches <b>regex</b>
* @param regex Expected regular expression
*/
@Then("the text matches '$regex'")
public void ifTextMatchesRegex(String regex)
{
String actualText = "";
boolean assertCondition = false;
boolean isWebElement = getSearchContext() instanceof WebElement;
if (isWebElement)
{
actualText = webElementActions.getElementText((WebElement) getSearchContext());
}
if (getSearchContext() instanceof WebDriver)
{
actualText = webElementActions.getPageText();
}
if (!actualText.isEmpty())
{
Pattern pattern = Pattern.compile(regex);
assertCondition = pattern.matcher(actualText).find();
if (!assertCondition && isWebElement)
{
String pseudoElementContent = webElementActions
.getPseudoElementContent((WebElement) getSearchContext());
if (!pseudoElementContent.isEmpty())
{
assertCondition = pattern.matcher(pseudoElementContent).find();
}
}
}
highlightingSoftAssert.assertTrue("The text in search context matches regular expression " + regex,
assertCondition);
}
示例11
/**
* Checks if xml contains element by XPath
* @param xml XML
* @param xpath XPath
*/
@Then("XML `$xml` contains element by xpath `$xpath`")
public void doesElementExistByXpath(String xml, String xpath)
{
Document doc = XmlUtils.convertToDocument(xml);
softAssert.assertThat("XML has element with XPath: " + xpath, doc, hasXPath(xpath));
}
示例12
/**
* Checks, if there is a frame with desired attribute on the context
* @param attributeType Type of tag attribute (for ex. 'name', 'id')
* @param attributeValue Value of the attribute
* @return Frame web element if it is found on the page
*/
@Then("a frame with the attribute '$attributeType'='$attributeValue' exists")
public WebElement isFrameWithCertainAttributeFound(String attributeType, String attributeValue)
{
return baseValidations.assertIfElementExists(
String.format("A frame with the attribute '%1$s'='%2$s'", attributeType, attributeValue),
new SearchAttributes(ActionAttributeType.XPATH,
LocatorUtil.getXPathByTagNameAndAttribute("iframe", attributeType, attributeValue)));
}
示例13
/**
* Checks if cookie with name <code>cookieName</code> is set
* @param cookieName Cookie name
* @return Optional containing cookie
*/
@Then("a cookie with the name '$cookieName' is set")
public Optional<Cookie> thenCookieWithNameIsSet(String cookieName)
{
Cookie cookie = cookieManager.getCookie(cookieName);
softAssert.assertThat(String.format("Cookie with the name '%s' is set", cookieName), cookie, notNullValue());
return Optional.ofNullable(cookie);
}
示例14
/**
* Checks if cookie with name <code>cookieName</code> is not set
* @param cookieName Cookie name
*/
@Then("a cookie with the name '$cookieName' is not set")
public void thenCookieWithNameIsNotSet(String cookieName)
{
Cookie cookie = cookieManager.getCookie(cookieName);
softAssert.assertThat(String.format("Cookie with the name '%s' is not set", cookieName), cookie, nullValue());
}
示例15
/**
* Checks that opened page contains JavaScript browser console logs that matches regex.
* <p>Note that log buffers are reset after step invocation, meaning that available log entries correspond to those
* entries not yet returned for a given log type. In practice, this means that this step invocation will return the
* available log entries since the last step invocation (or from the last page navigation if corresponding listener
* is enabled).</p>
* <p>Step passes if console logs were found, otherwise it fails. All found logs are available in
* report step's attachment</p>
* @param logEntries Log entries to check: "errors", "warnings", "errors, warnings" or "warnings, errors"
* @param regex Regular expression to filter log entries
*/
@Then(value = "there are browser console $logEntries by regex `$regex`")
public void checkThereAreLogEntriesOnOpenedPageFiltredByRegExp(List<BrowserLogLevel> logEntries, String regex)
{
WebDriver webDriver = webDriverProvider.get();
Set<LogEntry> filteredLogEntries = BrowserLogManager.getFilteredLog(webDriver, logEntries).stream()
.filter(logEntry -> logEntry.getMessage().matches(regex))
.collect(Collectors.toSet());
publishAttachment(Map.of(webDriver.getCurrentUrl(), filteredLogEntries));
softAssert.assertFalse(String.format("Current page contains JavaScript %s by regex '%s'",
toString(logEntries), regex), filteredLogEntries.isEmpty());
}
示例16
/**
* Checks that the <b>each element</b> specified by <b>XPath</b> contains an exact number
* of visible <b>child elements</b> specified by <b>XPath</b>
* <p>Actions performed at this step:</p>
* <ul>
* <li>Finds all parent elements matching the 'elementXpath'
* <li>Finds in each patent element all child element matching the 'childXpath' an verifies their amount
* </ul>
* @param elementLocator locator for the parent element
* @param number An amount of child elements (Every positive integer from 0)
* @param childLocator locator for the child element
*/
@Then("each element with locator `$elementLocator` has `$number` child elements with locator `$childLocator`")
public void doesEachElementByLocatorHaveChildWithLocator(SearchAttributes elementLocator, int number,
SearchAttributes childLocator)
{
List<WebElement> elements = baseValidations.assertIfElementsExist("The number of parent elements",
elementLocator);
for (WebElement element : elements)
{
baseValidations.assertIfExactNumberOfElementsFound("Parent element has number of child elements which",
element, childLocator, number);
}
}
示例17
/**
* Checks that the context <b>element</b> has an expected <b>CSS property</b>
* @param cssName A name of the <b>CSS property</b>
* @param cssValue An expected value of <b>CSS property</b>
*/
@Then("the context element has the CSS property '$cssName'='$cssValue'")
public void doesElementHaveRightCss(String cssName, String cssValue)
{
WebElement element = webUiContext.getSearchContext(WebElement.class);
String actualCssValue = webElementActions.getCssValue(element, cssName);
highlightingSoftAssert.assertEquals("Element has correct css property value", cssValue,
actualCssValue);
}
示例18
/**
* Checks that the context <b>element</b>
* has an expected <b>width in a percentage</b> (from style attribute)
* @param widthInPerc An expected width of the element in a percentage
*/
@Then("the context has a width of '$widthInPerc'%")
public void isElementHasRightWidth(int widthInPerc)
{
WebElement webElement = webUiContext.getSearchContext(WebElement.class);
WebElement bodyElement = baseValidations.assertIfElementExists("'Body' element", webDriverProvider.get(),
new SearchAttributes(ActionAttributeType.XPATH,
new SearchParameters(LocatorUtil.getXPath("//body"), Visibility.ALL)));
elementValidations.assertIfElementHasWidthInPerc(bodyElement, webElement, widthInPerc);
}
示例19
/**
* Checks, if the context element has specified width in percentage
* @param width Expected element with in percentage
*/
@Then("the context element has a width of '$widthInPerc'% relative to the parent element")
public void isElementHasWidthRelativeToTheParentElement(int width)
{
WebElement elementChild = webUiContext.getSearchContext(WebElement.class);
WebElement elementParent = baseValidations.assertIfElementExists("Parent element",
new SearchAttributes(ActionAttributeType.XPATH, "./.."));
elementValidations.assertIfElementHasWidthInPerc(elementParent, elementChild, width);
}
示例20
/**
* Checks if a checkbox with the specified <b>name</b> exists in context
* @param checkboxName Checkbox text (the text in the (<i><code><label></code></i>) tag
* @return <b>WebElement</b> An element (checkbox) matching the requirements,
* <b> null</b> - if there are no desired elements
*/
@Then("a checkbox with the name '$checkboxName' exists")
public Checkbox ifCheckboxExists(String checkboxName)
{
return (Checkbox) baseValidations.assertIfElementExists(String.format(CHECKBOX_WITH_NAME, checkboxName),
new SearchAttributes(ActionAttributeType.CHECKBOX_NAME, checkboxName));
}
示例21
/**
* Checks if a checkbox with the specified <b>name</b> does not exist in context
* @param checkboxName Checkbox text (the text in the (<i><code><label></code></i>) tag
*/
@Then("a checkbox with the name '$checkBox' does not exist")
public void doesNotCheckboxExist(String checkboxName)
{
SearchParameters parameters = new SearchParameters(checkboxName).setWaitForElement(false);
baseValidations.assertIfElementDoesNotExist(String.format(CHECKBOX_WITH_NAME, checkboxName),
new SearchAttributes(ActionAttributeType.CHECKBOX_NAME, parameters));
}
示例22
/**
* Asserts that local storage item with key does not exist
* @param key of local storage item
*/
@Then("local storage item with `$key` does not exist")
public void checkLocalStorageItemDoesNotExist(String key)
{
softAssert.assertThat("Local storage item with key: " + key,
localStorageManager.getItem(key), Matchers.nullValue());
}
示例23
/**
* Waits for <b><i>an element</i></b> with the specified <b>id</b> disappearance
* in the specified search context
* @param id Value of the 'id' attribute of the element
*/
@Then("an element with the id '$id' disappears")
public void elementByIdDisappears(String id)
{
By locator = By.xpath(LocatorUtil.getXPathByAttribute("id", id));
waitActions.wait(getSearchContext(),
State.NOT_VISIBLE.getExpectedCondition(expectedSearchContextConditions, locator));
}
示例24
/**
* Checks that element exists during the timeout
* @param seconds timeout in seconds
* @param xpath XPath value of the element
*/
@Then("the element with the xpath '$xpath' exists for '$seconds' seconds")
public void doesElementExistsForTimePeriod(String xpath, long seconds)
{
By elementXpath = LocatorUtil.getXPathLocator(xpath);
WaitResult<Boolean> result = waitActions.wait(getSearchContext(), Duration.ofSeconds(seconds),
expectedSearchContextConditions.not(
expectedSearchContextConditions.presenceOfAllElementsLocatedBy(elementXpath)), false);
softAssert.assertFalse(String.format("Element with xpath '%s' has existed during '%d' seconds",
xpath, seconds), result.isWaitPassed());
}
示例25
/**
* Waits for element disappearance with desired timeout in seconds
* @param locator The locating mechanism to use
* @param timeout Desired timeout
* @return true if element disappeared, false otherwise
*/
@Then("element located '$locator' disappears in '$timeout'")
public boolean waitForElementDisappearance(SearchAttributes locator, Duration timeout)
{
return waitActions.wait(getSearchContext(), timeout,
expectedSearchActionsConditions.invisibilityOfElement(locator)).isWaitPassed();
}
示例26
/**
* Checks if a drop down with the specified <b>name</b> does not exist in context
* @param dropDownName Any attribute value of the <i><select></i> tag
*/
@Then("a drop down with the name '$dropDownName' does not exist")
public void doesNotDropDownExist(String dropDownName)
{
SearchAttributes searchAttributes = createSearchAttributes(dropDownName);
searchAttributes.getSearchParameters().setVisibility(Visibility.ALL);
baseValidations.assertIfElementDoesNotExist(String.format(DROP_DOWN_WITH_NAME, dropDownName), searchAttributes);
}
示例27
/**
* Step purpose is checking of resources availability;
* Steps follows next logic for each page URL:
* 1. Gathers all the elements by CSS selector
* 2. For each element executes HEAD request;
* a. If status code acceptable than check considered as passed;
* b. If status code not acceptable but one of (404, 405, 501, 503) then GET request will be sendt;
* c. If GET status code acceptable than check considered as passed otherwise failed;
* <b>Example</b>
* Then all resources by selector a are valid on:
* |pages|
* |https://vividus.org|
* |/test-automation-made-awesome|
* @param cssSelector to locate resources
* @param pages where resources will be validated
* @throws InterruptedException when a thread is interrupted
* @throws ExecutionException when exception thrown before result get
*/
@Then("all resources by selector `$cssSelector` are valid on:$pages")
public void checkResources(String cssSelector, ExamplesTable pages) throws InterruptedException, ExecutionException
{
execute(() -> {
Stream<ResourceValidation> resourcesToValidate =
pages.getRows()
.parallelStream()
.map(m -> m.get("pages"))
.map(this::createUri)
.map(URI::toString)
.flatMap(pageURL ->
{
try
{
httpRequestExecutor.executeHttpRequest(HttpMethod.GET, pageURL, Optional.empty());
return Optional.ofNullable(httpTestContext.getResponse())
.map(HttpResponse::getResponseBodyAsString)
.map(b -> createResourceValidations(getElements(cssSelector, b),
p -> new ResourceValidation(p.getLeft(), p.getRight(), pageURL)))
.orElseGet(() ->
Stream.of(brokenResourceValidation(pageURL, Optional.empty())));
}
catch (IOException toReport)
{
return Stream.of(brokenResourceValidation(pageURL, Optional.of(toReport)));
}
});
validateResources(resourcesToValidate);
});
}
示例28
/**
* Compare the value from the first <b>variable</b> with the value from the second <b>variable</b>
* in accordance with the <b>condition</b>
* Could compare Maps and Lists of maps using EQUAL_TO comparison rule.
* Other rules will fallback to strings comparison
* <p>
* The values of the variables should be logically comparable.
* @param variable1 The <b>name</b> of the variable in witch the value was set
* @param condition The rule to compare values<br>
* (<i>Possible values:<b> less than, less than or equal to, greater than, greater than or equal to,
* equal to</b></i>)
* @param variable2 The <b>name</b> of the different variable in witch the value was set
* @return true if assertion is passed, otherwise false
*/
@Then("`$variable1` is $comparisonRule `$variable2`")
public boolean compareVariables(Object variable1, ComparisonRule condition, Object variable2)
{
if (variable1 instanceof String && variable2 instanceof String)
{
String variable1AsString = (String) variable1;
String variable2AsString = (String) variable2;
if (NumberUtils.isCreatable(variable1AsString) && NumberUtils.isCreatable(variable2AsString))
{
BigDecimal number1 = NumberUtils.createBigDecimal(variable1AsString);
BigDecimal number2 = NumberUtils.createBigDecimal(variable2AsString);
return compare(number1, condition, number2);
}
}
else if (ComparisonRule.EQUAL_TO.equals(condition))
{
if (isEmptyOrListOfMaps(variable1) && isEmptyOrListOfMaps(variable2))
{
return compareListsOfMaps(variable1, variable2);
}
else if (instanceOfMap(variable1) && instanceOfMap(variable2))
{
return compareListsOfMaps(List.of(variable1), List.of(variable2));
}
}
return compare(variable1.toString(), condition, variable2.toString());
}
示例29
/**
* Compare the map from <b>variable</b> with the provided table in <b>table</b>
* ignoring any extra entries in <b>variable</b>
* @param variable The <b>name</b> of the variable with map to check
* @param table ExamplesTable with parameters to compare with
*/
@Then("`$variable` is equal to table ignoring extra columns:$table")
public void tablesAreEqualIgnoringExtraColumns(Object variable, ExamplesTable table)
{
if (!instanceOfMap(variable))
{
throw new IllegalArgumentException("'variable' should be instance of map");
}
Map<String, String> expectedMap = MapUtils.convertSingleRowExamplesTableToMap(table);
List<EntryComparisonResult> results = ComparisonUtils.checkMapContainsSubMap((Map<?, ?>) variable, expectedMap);
publishMapComparisonResults(List.of(results));
softAssert.assertTrue(TABLES_ARE_EQUAL, results.stream().allMatch(EntryComparisonResult::isPassed));
}
示例30
/**
* Matches given value against specified pattern
* @param value The value to be matched
* @param pattern pattern
*/
@Then("`$value` matches `$pattern`")
public void valueMatchesPattern(String value, Pattern pattern)
{
softAssert.assertThat(String.format("Value '%s' matches pattern '%s'", value, pattern.pattern()), value,
matchesPattern(pattern));
}