Java源码示例:org.jbehave.core.annotations.When

示例1
/**
 * Joins two data sets from previously executed SQL queries;
 * @param left data set to join
 * @param right data set to join
 * @param scopes The set (comma separated list of scopes e.g.: STORY, NEXT_BATCHES) of variable's scope<br>
 * <i>Available scopes:</i>
 * <ul>
 * <li><b>STEP</b> - the variable will be available only within the step,
 * <li><b>SCENARIO</b> - the variable will be available only within the scenario,
 * <li><b>STORY</b> - the variable will be available within the whole story,
 * <li><b>NEXT_BATCHES</b> - the variable will be available starting from next batch
 * </ul>
 * @param variableName a name of variable to store a result
 */
@When("I merge `$left` and `$right` and save result to $scopes variable `$variableName`")
public void joinDataSets(List<Map<String, Object>> left, List<Map<String, Object>> right,
        Set<VariableScope> scopes, String variableName)
{
    List<Map<String, Object>> result = new ArrayList<>(left.size() + right.size());
    if (!left.isEmpty() && !right.isEmpty())
    {
        Set<String> leftHeader = left.get(0).keySet();
        Set<String> rightHeader = right.get(0).keySet();
        Validate.isTrue(leftHeader.equals(rightHeader),
                "Data sets should have same columns;\nLeft:  %s\nRight: %s", leftHeader, rightHeader);
    }
    result.addAll(left);
    result.addAll(right);
    bddVariableContext.putVariable(scopes, variableName, result);
}
 
示例2
/**
 * Drags the <b>draggable</b> element and moves it relatively to the <b>target</b> element in
 * accordance to provided <b>location</b>.
 * <br>
 * <i>Example</i>
 * <br>
 * <code>When I drag element located `By.xpath(//div[@class='draggable'])` and drop it at RIGHT_TOP of element
 * located `By.xpath(//div[@class='target'])`</code>
 * If this step doesn't work, try to use step simulating drag&amp;drop
 * @param draggable draggable element
 * @param location location relatively to the <b>target</b> element (<b>TOP</b>,<b>BOTTOM</b>,<b>LEFT</b>,
 * <b>RIGHT</b>,<b>CENTER</b>,<b>LEFT_TOP</b>,<b>RIGHT_TOP</b>,<b>LEFT_BOTTOM</b>,<b>RIGHT_BOTTOM</b>)
 * @param target target element
 */
@When("I drag element located `$draggable` and drop it at $location of element located `$target`")
@SuppressWarnings("checkstyle:MagicNumber")
public void dragAndDropToTargetAtLocation(SearchAttributes draggable, Location location, SearchAttributes target)
{
    performDragAndDrop(draggable, target, (draggableElement, targetElement) ->
    {
        Point offsetPoint = location.getPoint(draggableElement.getRect(), targetElement.getRect());
        new Actions(webDriverProvider.get())
                .clickAndHold(draggableElement)
                // Selenium bug: https://github.com/SeleniumHQ/selenium/issues/1365#issuecomment-547786925
                .moveByOffset(10, 0)
                .moveByOffset(-10, 0)
                .moveByOffset(offsetPoint.getX(), offsetPoint.getY())
                .release()
                // Wait for DOM stabilization
                .pause(Duration.ofSeconds(1))
                .perform();
    });
}
 
示例3
/**
 * This step uploads a file with the given relative path
 * <p>A <b>relative path</b> starts from some given working directory,
 * avoiding the need to provide the full absolute path
 * (i.e. <i>'about.jpeg'</i> is in the root directory
 * or <i>'/story/uploadfiles/about.png'</i>)</p>
 * @param locator The locator for the upload element
 * @param filePath relative path to the file to be uploaded
 * @see <a href="https://en.wikipedia.org/wiki/Path_(computing)#Absolute_and_relative_paths"> <i>Absolute and
 * relative paths</i></a>
 * @throws IOException If an input or output exception occurred
 */
@When("I select element located `$locator` and upload file `$filePath`")
public void uploadFile(SearchAttributes locator, String filePath) throws IOException
{
    Resource resource = resourceLoader.getResource(ResourceLoader.CLASSPATH_URL_PREFIX + filePath);
    if (!resource.exists())
    {
        resource = resourceLoader.getResource(ResourceUtils.FILE_URL_PREFIX + filePath);
    }
    File fileForUpload = ResourceUtils.isFileURL(resource.getURL()) ? resource.getFile()
            : unpackFile(resource, filePath);
    if (highlightingSoftAssert.assertTrue("File " + filePath + " exists", fileForUpload.exists()))
    {
        String fullFilePath = fileForUpload.getAbsolutePath();
        if (isRemoteExecution())
        {
            webDriverProvider.getUnwrapped(RemoteWebDriver.class).setFileDetector(new LocalFileDetector());
        }
        locator.getSearchParameters().setVisibility(Visibility.ALL);
        WebElement browse = baseValidations.assertIfElementExists(AN_ELEMENT, locator);
        if (browse != null)
        {
            browse.sendKeys(fullFilePath);
        }
    }
}
 
示例4
/**
 * Step intended to execute UPDATE, INSERT, DELETE queries.
 * In case of SELECT query exception will be thrown.
 * For SELECT queries please use step:
 * <br><b>When I execute SQL query `$sqlQuery` against `$dbKey`
 * and save result to $scopes variable `$variableName`</b>
 * Actions performed in the step:
 * <ul>
 *     <li>executes provided SQL query against database by the provided key</li>
 *     <li>logs affected lines</li>
 * </ul>
 *
 * @param sqlQuery SQL query to execute
 * @param dbKey Key identifying the database connection
 */
@When("I execute SQL query `$sqlQuery` against `$dbKey`")
public void executeSql(String sqlQuery, String dbKey)
{
    try
    {
        LOGGER.info("Executed query: {}\nAffected rows:{}", sqlQuery, getJdbcTemplate(dbKey).update(sqlQuery));
    }
    catch (DataIntegrityViolationException e)
    {
        throw new IllegalStateException("Exception occured during query execution.\n"
            + "If you are trying execute SELECT query consider using step:"
            + "When I execute SQL query '$sqlQuery' and save the result to the $scopes variable '$variableName'",
            e);
    }
}
 
示例5
/**
 * Saves cookie to scope variable.
 * If present several cookies with the same name will be stored cookie with the root path value (path is '/'),
 * @param cookieName   name of cookie to save
 * @param scopes       The set (comma separated list of scopes e.g.: STORY, NEXT_BATCHES) of variable's scope<br>
 *                     <i>Available scopes:</i>
 *                     <ul>
 *                     <li><b>STEP</b> - the variable will be available only within the step,
 *                     <li><b>SCENARIO</b> - the variable will be available only within the scenario,
 *                     <li><b>STORY</b> - the variable will be available within the whole story,
 *                     <li><b>NEXT_BATCHES</b> - the variable will be available starting from next batch
 *                     </ul>
 * @param variableName name of variable
 */
@When("I save value of HTTP cookie with name `$cookieName` to $scopes variable `$variableName`")
public void saveHttpCookieIntoVariable(String cookieName, Set<VariableScope> scopes, String variableName)
{
    List<Cookie> cookies = findCookiesBy(FILTER_BY_NAME, cookieName);
    int cookiesNumber = cookies.size();
    if (assertCookiesPresent(cookieName, cookiesNumber))
    {
        if (cookiesNumber == 1)
        {
            bddVariableContext.putVariable(scopes, variableName, cookies.get(0).getValue());
        }
        else
        {
            String rootPath = "/";
            BiPredicate<Cookie, String> filterByPath = (cookie, cookiePath) -> cookie.getPath().equals(cookiePath);
            LOGGER.info("Filtering cookies by path attribute '{}'", rootPath);
            cookies = findCookiesBy(filterByPath, rootPath);
            if (softAssert.assertEquals(String.format("Number of cookies with name '%s' and path attribute '%s'",
                    cookieName, rootPath), 1, cookies.size()))
            {
                bddVariableContext.putVariable(scopes, variableName, cookies.get(0).getValue());
            }
        }
    }
}
 
示例6
/**
 * Step sets value of slider (input element with type = "range")
 * using javascript script.
 * @param value A value to set
 * @param xpath Xpath to slider
 * @see <a href="https://www.w3schools.com/jsref/dom_obj_range.asp"> <i>more about sliders</i></a>
 */
@When("I select the value '$value' in a slider by the xpath '$xpath'")
public void setSliderValue(String value, String xpath)
{
    WebElement slider = baseValidations.assertIfElementExists("Slider to select value in",
            new SearchAttributes(ActionAttributeType.XPATH, LocatorUtil.getXPath(xpath)));
    if (null != slider)
    {
        javascriptActions.executeScript("arguments[0].value=arguments[1]", slider, value);
    }
}
 
示例7
/**
 * Step implemented to reuse browser cookies for HTTP client executed requests.
 * Steps performed:
 *   - Set's browser cookies into API context
 */
@When("I set browser cookies to the API context")
public void executeRequestUsingBrowserCookies()
{
    CookieStore cookieStore = cookieManager.getCookiesAsHttpCookieStore();
    attachmentPublisher.publishAttachment("org/vividus/bdd/steps/integration/browser-cookies.ftl",
            Map.of("cookies", cookieStore.getCookies()), "Browser cookies");
    httpTestContext.putCookieStore(cookieStore);
}
 
示例8
/**
 * Executes the sequence of web actions
 * <div>Example:</div>
 * <code>
 *   <br>When I execute the sequence of actions:
 *   <br>|type           |searchAttributes                        |offset   |
 *   <br>|MOVE_BY_OFFSET |                                        |(-300, 0)|
 *   <br>|MOVE_BY_OFFSET |                                        |(0, 40)  |
 *   <br>|CLICK_AND_HOLD |By.xpath(//signature-pad-control/canvas)|         |
 *   <br>|MOVE_BY_OFFSET |                                        |(0, 100) |
 *   <br>|RELEASE        |By.xpath(//signature-pad-control/canvas)|         |
 * </code>
 * <br>
 * <br>
 * where
 * <ul>
 * <li><code>type</code> is one of web actions: move by offset, click and hold, release</li>
 * <li><code>searchAttributes</code> is search attribute to find element for interaction
 *  (could be empty if not applicable)</li>
 * <li><code>offset</code> the offset to move by (ex.: (10, 10))</li>
 * </ul>
 * @param actions table of actions to execute
 * @deprecated Use <i>When I execute sequence of actions: actions</i>
 */
@Deprecated(since = "0.2.0", forRemoval = true)
@When("I execute the sequence of actions: $actions")
public void executeActionsSequence(List<Action> actions)
{
    performActions(actions, (builder, action) ->
    {
        ActionType actionType = action.getType();
        if (actionType.isCoordinatesRequired())
        {
            Optional<Point> offset = action.getOffset();
            if (!softAssert.assertTrue("Action offset is present", offset.isPresent()))
            {
                return false;
            }
            actionType.addAction(builder, offset.get());
        }
        else
        {
            Optional<SearchAttributes> searchAttributes = action.getSearchAttributes();
            Optional<WebElement> element;
            if (searchAttributes.isPresent())
            {
                element = findElement(searchAttributes.get());
                if (element.isEmpty())
                {
                    return false;
                }
            }
            else
            {
                element = Optional.empty();
            }
            actionType.addAction(builder, element);
        }
        return true;
    });
}
 
示例9
/**
 * Step waits until data received from SQL request is equal to data from examples table for some duration.
 * Actions performed in the step:
 * <ul>
 *     <li>executes provided SQL query against database</li>
 *     <li>compares data received from SQL request against examples table</li>
 *     <li>sleeps during calculated part of specified duration</li>
 *     <li>repeats previous actions if data was not equal and seconds timeout not expired</li>
 * </ul>
 * @param duration Time duration to wait
 * @param retryTimes How many times request will be retried; duration/retryTimes=timeout between requests
 * @param sqlQuery SQL query to execute
 * @param dbKey Key identifying the database connection
 * @param table Rows to compare data against
 */
@When("I wait for '$duration' duration retrying $retryTimes times while data from `$sqlQuery`"
        + " executed against `$dbKey` is equal to data from:$table")
public void waitForDataAppearance(Duration duration, int retryTimes, String sqlQuery, String dbKey,
        ExamplesTable table)
{
    JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey);
    QueriesStatistic statistics = new QueriesStatistic(jdbcTemplate, jdbcTemplate);
    Map<Object, Map<String, Object>> sourceData = hashMap(Set.of(), table.getRows());
    statistics.getTarget().setRowsQuantity(sourceData.size());

    Waiter waiter = new Waiter(new WaitMode(duration, retryTimes));
    List<List<EntryComparisonResult>> comparisonResult = waiter.wait(
        () -> {
            List<Map<String, Object>> data = jdbcTemplate.queryForList(sqlQuery);
            statistics.getSource().setRowsQuantity(data.size());
            Map<Object, Map<String, Object>> targetData = hashMap(Set.of(),
                    data.stream().map(
                        m -> m.entrySet()
                           .stream()
                           .collect(Collectors.toMap(Map.Entry::getKey, e -> String.valueOf(e.getValue())))
                    )
            );
            return compareData(statistics, sourceData, targetData);
        },
        result -> {
            boolean empty = result.isEmpty();
            if (!empty)
            {
                LOGGER.atInfo().addArgument(result::size).log(
                        "SQL result data is not equal to expected data in {} records");
            }
            return empty;
        }
    );
    verifyComparisonResult(statistics, filterPassedChecks(comparisonResult));
}
 
示例10
/**
 * Scroll the element into view by calling API:
 * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView">Scroll into view</a>
 * @param locator to locate an element
 */
@When("I scroll element located `$locator` into view")
public void scrollIntoView(SearchAttributes locator)
{
    WebElement toScroll = baseValidaitons.assertIfAtLeastOneElementExists("Element to scroll into view", locator);
    if (null != toScroll)
    {
        javascriptActions.scrollIntoView(toScroll, true);
    }
}
 
示例11
/**
 * Sets a cursor on the <b>element</b> specified by locator
 * @param locator to locate the element
 */
@When("I hover mouse over element located `$locator`")
public void hoverMouseOverElement(SearchAttributes locator)
{
    WebElement element = baseValidations.assertIfElementExists(
            String.format(AN_ELEMENT_WITH_ATTRIBUTES, locator), locator);
    mouseActions.moveToElement(element);
}
 
示例12
/**
 * Set the context for further localization of elements to an <b>element</b> specified by <b>locator</b>
 * @param locator Locator used to find an element
 */
@When("I change context to element located `$locator`")
public void changeContextToElement(SearchAttributes locator)
{
    changeContextToPage();
    WebElement element = baseValidations.assertIfElementExists("Element to set context", locator);
    webUiContext.putSearchContext(element, () -> changeContextToElement(locator));
}
 
示例13
/**
 * Waits for element disappearance with timeout
 * @param locator The locating mechanism to use
 * @return true if element disappeared, false otherwise
 */
@When("I wait until element located `$locator` disappears")
public boolean waitForElementDisappearance(SearchAttributes locator)
{
    return waitActions.wait(getSearchContext(), expectedSearchActionsConditions.invisibilityOfElement(locator))
            .isWaitPassed();
}
 
示例14
/**
* Wait for a window and switches the focus of future browser commands to the new
* <b>window object</b> with the specified <b>title</b>.
* <p>
* Each browser <b>window</b> or <b>tab</b> is considered to be a separate <b>window object</b>. This object holds
* corresponding <b>Document</b> object, which itself is a HTML page.
* </p>
* <b>Title</b> references to the page title, which is set by {@code <title>} tag.
* <p>
* Actions performed at this step:
* <ul>
* <li>Searches among currently opened windows (and tabs) for a window with the specified <b>windowName</b>.</li>
* <li>If such window is found switches focus to it. If window is not found current focus stays unchanged;</li>
* </ul>
* @param comparisonRule is equal to, contains, does not contain
* @param title Value of the {@code <title>} tag of a desired window
* @param duration in format <a href="https://en.wikipedia.org/wiki/ISO_8601">Duration Format</a>
* @see <a href="https://html.spec.whatwg.org/#browsing-context"><i>Browsing context (Window &amp; Document)</i></a>
* @see <a href="https://www.w3schools.com/tags/default.asp"><i>HTML Element Reference</i></a>
*/
@When("I wait `$duration` until window with title that $comparisonRule `$title` appears and switch to it")
public void waitForWindowAndSwitch(Duration duration, StringComparisonRule comparisonRule, String title)
{
    Matcher<String> expected = comparisonRule.createMatcher(title);
    WaitResult<Boolean> result = waitActions.wait(webDriverProvider.get(), duration, new ExpectedCondition<>()
    {
        @Override
        public Boolean apply(WebDriver driver)
        {
            try
            {
                return expected.matches(windowsActions.switchToWindowWithMatchingTitle(expected));
            }
            catch (WebDriverException webDriverException)
            {
                return false;
            }
        }

        @Override
        public String toString()
        {
            return String.format("switch to a window where title %s \"%s\"", comparisonRule, title);
        }
    });
    resetContextIf(result::isWaitPassed);
}
 
示例15
/**
 * Step for interaction with page via keyboard. Interacts with the context element in focus.
 * @param keys List of keys to be pressed. (Separator: ",")
 * @see <a href="https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/Keys.html">
 * <i>Keys</i></a>
 */
@When("I press $keys on keyboard")
public void pressKeys(List<String> keys)
{
    WebElement element = webUiContext.getSearchContext() instanceof WebDriver
            ? webDriverProvider.get().findElement(By.xpath("//body"))
            : webUiContext.getSearchContext(WebElement.class);
    if (focusValidations.isElementInFocusState(element, FocusState.IN_FOCUS))
    {
        element.sendKeys(KeysUtils.keysToCharSequenceArray(keys));
    }
}
 
示例16
/** If the variable with name is not set into context executes steps.
 * <b>Example:</b>
 * <br> When variable 'token' is not set perform:
 * <br> |When I login|
 * @param name variable name to check
 * @param stepsToExecute steps to execute
 */
@When("variable '$name' is not set I do:$stepsToExecute")
public void ifVariableNotSetPerformSteps(String name, SubSteps stepsToExecute)
{
    if (bddVariableContext.getVariable(name) == null)
    {
        stepsToExecute.execute(Optional.empty());
    }
}
 
示例17
/**
 * Step establishes baseline or compares against existing one.
 * @param actionType ESTABLISH, COMPARE_AGAINST
 * @param name of baseline
 */
@When("I $actionType baseline with `$name`")
public void runVisualTests(VisualActionType actionType, String name)
{
    performVisualAction(() -> visualCheckFactory.create(name, actionType));
}
 
示例18
/**
 * This step pauses the video in the video player. The target element must be &lt;video&gt; tag.
 * @param videoPlayerName any attribute value of the element
 */
@When("I pause video in the video player with the name '$videoPlayerName'")
public void pauseVideoInVideoPlayer(String videoPlayerName)
{
    findVideoPlayerAndExecuteAction(videoPlayerName, videoPlayerActions::pause);
}
 
示例19
/**
 * Extracts an <b>URL</b> of a video with the specified <b>name</b> in the context
 * and saves it into the <b>variable</b>
 * <p>
 * The <i>URL</i> of a video lies into the value of the attribute 'src'
 * <p>
 * Actions performed at this step:
 * <ul>
 * <li>Finds a frame with video by its name
 * <li>Extracts the URL value of the video
 * <li>Saves the value into the <i>variable</i>
 * </ul>
 * @param name The text in the top left corner
 * @param scopes The set (comma separated list of scopes e.g.: STORY, NEXT_BATCHES) of variable's scope<br>
 * <i>Available scopes:</i>
 * <ul>
 * <li><b>STEP</b> - the variable will be available only within the step,
 * <li><b>SCENARIO</b> - the variable will be available only within the scenario,
 * <li><b>STORY</b> - the variable will be available within the whole story,
 * <li><b>NEXT_BATCHES</b> - the variable will be available starting from next batch
 * </ul>
 * @param variable A name under which the value should be saved
 */
@When("I get the URL value of a video with the name '$name' and set it to the '$scopes' variable '$variable'")
public void getUrlValueOfVideoWithName(String name, Set<VariableScope> scopes, String variable)
{
    List<WebElement> frames = getVideoIFrames(1);
    if (!frames.isEmpty())
    {
        SearchAttributes attributes = new SearchAttributes(ActionAttributeType.LINK_TEXT, name);
        for (WebElement frame : frames)
        {
            getWebDriver().switchTo().frame(frame);
            List<WebElement> links = searchActions.findElements(getWebDriver(), attributes);
            if (!links.isEmpty())
            {
                getWebDriver().switchTo().defaultContent();
                saveSrcAttributeValueToVariable(frame, scopes, variable);
                return;
            }
        }
        getWebDriver().switchTo().defaultContent();
        softAssert.recordFailedAssertion(String.format("A video with the name '%s' was not found", name));
    }
}
 
示例20
@When(I_DO_ACTION)
void anotherWhenStep()
{
    // nothing to do
}
 
示例21
/**
 * Loads the previous URL in the browser history list
 */
@When("I navigate back")
public void navigateBack()
{
    webDriverProvider.get().navigate().back();
}
 
示例22
@When(I_DO_ACTION)
void innerWhenStep()
{
    // nothing to do
}
 
示例23
@TakeScreenshotOnFailure
@When(I_DO_ACTION)
void whenStep()
{
    // nothing to do
}
 
示例24
/**
 * Waits for the scroll finish; Could be useful for the cases when you have very slow scroll
 * and need to synchronize the tests with the scroll
 */
@When("I wait until scroll is finished")
public void waitForScroll()
{
    javascriptActions.waitUntilScrollFinished();
}
 
示例25
/**
 * Step designed to perform steps against all elements found by JSON path in current json context or response
 * <b>if</b> they are matching comparison rule.
 * Actions performed by step:
 * <ul>
 * <li>Searches for elements using JSON path</li>
 * <li>Checks that elements quantity matches comparison rule and elements number</li>
 * <li>For each element switches JSON context and performs all steps. No steps will be performed
 * in case of comparison rule mismatch</li>
 * <li>Restores previously set context</li>
 * </ul>
 * <br> Usage example:
 * <code>
 * <br>When I find equal to '1' JSON elements by '$.[?(@.parent_target_id=="")]' and for each element do
 * <br>|step|
 * <br>|Then the number of JSON elements by the JSON path '$..name' is = 3|
 * </code>
 * @param comparisonRule use to check elements quantity
 * @param elementsNumber The expected number of elements
 * @param jsonPath A JSON path
 * @param stepsToExecute examples table with steps to execute for each found elements
 */
@SuppressWarnings("MagicNumber")
@When(value = "I find $comparisonRule '$elementsNumber' JSON elements by '$jsonPath' and for each element do"
        + "$stepsToExecute", priority = 6)
public void performAllStepsForJsonIfFound(ComparisonRule comparisonRule, int elementsNumber, String jsonPath,
        SubSteps stepsToExecute)
{
    performAllStepsForProvidedJsonIfFound(comparisonRule, elementsNumber, getActualJson(), jsonPath,
            stepsToExecute);
}
 
示例26
/**
 * Saves the value of response body into the variable with given scope and name.
 * @param scopes The set (comma separated list of scopes e.g.: STORY, NEXT_BATCHES) of variable's scope<br>
 * <i>Available scopes:</i>
 * <ul>
 * <li><b>STEP</b> - the variable will be available only within the step,
 * <li><b>SCENARIO</b> - the variable will be available only within the scenario,
 * <li><b>STORY</b> - the variable will be available within the whole story,
 * <li><b>NEXT_BATCHES</b> - the variable will be available starting from next batch
 * </ul>
 * @param variableName A variable name
 */
@When("I save response body to the $scopes variable '$variableName'")
public void saveResponseBody(Set<VariableScope> scopes, String variableName)
{
    performIfHttpResponseIsPresent(
        response -> bddVariableContext.putVariable(scopes, variableName, response.getResponseBodyAsString()));
}
 
示例27
/**
 * Gets an expected <b>value</b> from the <b>URL</b>
 * and saves it into the <b>variable</b>
 * <p>
 * A <b>value</b> is everything after the last <b>/</b>. <br>
 * An 'URL' is a 'href' attribute value of the <b>link</b> (<i>{@literal <a>}</i> tag) <br>
 * Possible values:
 * <ul>
 * <li>An absolute URL - points to another web site (like href="http://www.example.com/absolute")
 * <li>A relative URL - points to a file within a web site (like href="/relative")
 * </ul>
 * @param scopes The set (comma separated list of scopes e.g.: STORY, NEXT_BATCHES) of variable's scope<br>
 * <i>Available scopes:</i>
 * <ul>
 * <li><b>STEP</b> - the variable will be available only within the step,
 * <li><b>SCENARIO</b> - the variable will be available only within the scenario,
 * <li><b>STORY</b> - the variable will be available within the whole story,
 * <li><b>NEXT_BATCHES</b> - the variable will be available starting from next batch
 * </ul>
 * @param variable A name under which the value should be saved
 */
@When("I get the value from the URL and set it to the '$scopes' variable '$variable'")
public void gettingValueFromUrl(Set<VariableScope> scopes, String variable)
{
    String url = getWebDriver().getCurrentUrl();
    int valueIndex = url.lastIndexOf('/') + 1;
    if (valueIndex != 0 && valueIndex != url.length())
    {
        saveVariable(scopes, variable, url.substring(valueIndex));
    }
    else
    {
        softAssert.recordFailedAssertion("Any appropriate value wasn't found in the URL: " + url);
    }
}
 
示例28
/**
 * Waits until GET request to resource retrieves response body that contains specific JSON path
 * for a specified amount of time.
 * <p>
 * <b>Actions performed at this step:</b>
 * </p>
 * <ul>
 * <li>Executes HTTP GET request to the specified resource</li>
 * <li>Checks if response body contains an element by JSON path</li>
 * <li>Sleeps during calculated part of specified duration</li>
 * <li>Repeats previous actions if element was not found and seconds timeout not expired</li>
 * </ul>
 * @param jsonPath A JSON path
 * @param resourceUrl Resource URL
 * @param duration Time duration to wait
 * @param retryTimes How many times request will be retried; duration/retryTimes=timeout between requests
 * @throws IOException If an input or output exception occurred
 * @deprecated Use <i>When I wait for presence of element by `$jsonPath` for `$duration` duration
 * retrying $retryTimes times$stepsToExecute</i>
 */
@Deprecated(since = "0.2.0", forRemoval = true)
@When("I wait for presence of element by '$jsonPath' in HTTP GET response from '$resourceUrl'"
        + " for '$duration' duration retrying $retryTimes times")
public void waitForJsonFieldAppearance(String jsonPath, String resourceUrl, Duration duration,
        int retryTimes) throws IOException
{
    httpRequestExecutor.executeHttpRequest(HttpMethod.GET, resourceUrl, Optional.empty(),
        response -> isJsonElementSearchCompleted(response, jsonPath), new WaitMode(duration, retryTimes));
    assertJsonElementExists(jsonPath);
}
 
示例29
/**
 * Gets an expected <b>value</b> from the <b>number of open windows</b>
 * and saves it into the <b>variable</b>
 * <p>
 * A <b>value</b> is everything after the last <b>/</b>. <br>
 * @param scopes The set (comma separated list of scopes e.g.: STORY, NEXT_BATCHES) of variable's scope<br>
 * <i>Available scopes:</i>
 * <ul>
 * <li><b>STEP</b> - the variable will be available only within the step,
 * <li><b>SCENARIO</b> - the variable will be available only within the scenario,
 * <li><b>STORY</b> - the variable will be available within the whole story,
 * <li><b>NEXT_BATCHES</b> - the variable will be available starting from next batch
 * </ul>
 * @param variable A name under which the value should be saved
 */
@When("I get the number of open windows and set it to the $scopes variable '$variable'")
public void saveNumberOfOpenWindow(Set<VariableScope> scopes, String variable)
{
    int value = webDriverProvider.get().getWindowHandles().size();
    bddVariableContext.putVariable(scopes, variable, value);
}
 
示例30
/**
 * Extracts an <b>URL</b> of a video with the specified <b>sequence number</b> in the context
 * and saves it into the <b>variable</b>
 * <p>
 * The <i>URL</i> of a video lies into the value of the attribute 'src'
 * <p>
 * Actions performed at this step:
 * <ul>
 * <li>Finds a frame with video by its sequence number
 * <li>Extracts the URL value of the video
 * <li>Saves the value into the <i>variable</i>
 * </ul>
 * @param number A sequence number of video how it appears on the page <i>(numbering starts with '1')</i>
 * @param scopes The set (comma separated list of scopes e.g.: STORY, NEXT_BATCHES) of variable's scope<br>
 * <i>Available scopes:</i>
 * <ul>
 * <li><b>STEP</b> - the variable will be available only within the step,
 * <li><b>SCENARIO</b> - the variable will be available only within the scenario,
 * <li><b>STORY</b> - the variable will be available within the whole story,
 * <li><b>NEXT_BATCHES</b> - the variable will be available starting from next batch
 * </ul>
 * @param variable A name under which the value should be saved
 */
@When("I get the URL value of a video with sequence number '$number' and set it to the '$scopes'"
        + " variable '$variable'")
public void getUrlValueOfVideoWithNumber(int number, Set<VariableScope> scopes, String variable)
{
    List<WebElement> frames = getVideoIFrames(number);
    if (!frames.isEmpty())
    {
        WebElement frame = frames.get(number - 1);
        saveSrcAttributeValueToVariable(frame, scopes, variable);
    }
}