org.jbehave.core.annotations.When Java Examples

The following examples show how to use org.jbehave.core.annotations.When. 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: HttpCookieSteps.java    From vividus with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
            }
        }
    }
}
 
Example #2
Source File: DatabaseSteps.java    From vividus with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #3
Source File: DatabaseSteps.java    From vividus with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #4
Source File: DragAndDropSteps.java    From vividus with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
    });
}
 
Example #5
Source File: ElementSteps.java    From vividus with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example #6
Source File: SliderSteps.java    From vividus with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #7
Source File: HttpRequestSteps.java    From vividus with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #8
Source File: ExecutableSteps.java    From vividus with Apache License 2.0 5 votes vote down vote up
/** 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());
    }
}
 
Example #9
Source File: ActionSteps.java    From vividus with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
    });
}
 
Example #10
Source File: DatabaseSteps.java    From vividus with Apache License 2.0 5 votes vote down vote up
/**
 * 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));
}
 
Example #11
Source File: ScrollSteps.java    From vividus with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #12
Source File: SetContextSteps.java    From vividus with Apache License 2.0 5 votes vote down vote up
/**
 * 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));
}
 
Example #13
Source File: WaitSteps.java    From vividus with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #14
Source File: SetContextSteps.java    From vividus with Apache License 2.0 5 votes vote down vote up
/**
* 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);
}
 
Example #15
Source File: KeyboardSteps.java    From vividus with Apache License 2.0 5 votes vote down vote up
/**
 * 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));
    }
}
 
Example #16
Source File: ElementSteps.java    From vividus with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #17
Source File: VideoPlayerSteps.java    From vividus with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
}
 
Example #18
Source File: ScreenshotOnFailureMonitorTests.java    From vividus with Apache License 2.0 4 votes vote down vote up
@When(I_DO_ACTION)
void anotherWhenStep()
{
    // nothing to do
}
 
Example #19
Source File: PageSteps.java    From vividus with Apache License 2.0 4 votes vote down vote up
/**
 * Loads the previous URL in the browser history list
 */
@When("I navigate back")
public void navigateBack()
{
    webDriverProvider.get().navigate().back();
}
 
Example #20
Source File: ScreenshotOnFailureMonitorTests.java    From vividus with Apache License 2.0 4 votes vote down vote up
@When(I_DO_ACTION)
void innerWhenStep()
{
    // nothing to do
}
 
Example #21
Source File: ScreenshotOnFailureMonitorTests.java    From vividus with Apache License 2.0 4 votes vote down vote up
@TakeScreenshotOnFailure
@When(I_DO_ACTION)
void whenStep()
{
    // nothing to do
}
 
Example #22
Source File: WaitSteps.java    From vividus with Apache License 2.0 4 votes vote down vote up
/**
 * 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();
}
 
Example #23
Source File: VisualSteps.java    From vividus with Apache License 2.0 4 votes vote down vote up
/**
 * 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));
}
 
Example #24
Source File: SetVariableSteps.java    From vividus with Apache License 2.0 4 votes vote down vote up
/**
 * 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));
    }
}
 
Example #25
Source File: SetContextSteps.java    From vividus with Apache License 2.0 3 votes vote down vote up
/**
* Switch the focus of future browser commands to the new <b>window object</b> with the specified <b>windowName</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>WindowName</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 windowName Value of the {@code <title>} tag of a desired window
* @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 switch to window with title that $stringComparisonRule `$windowName`")
public void switchingToWindow(StringComparisonRule comparisonRule, String windowName)
{
    Matcher<String> matcher = comparisonRule.createMatcher(windowName);
    String titleAfterSwitch = windowsActions.switchToWindowWithMatchingTitle(matcher);
    resetContextIf(() ->
        highlightingSoftAssert.assertThat("New window or browser tab name is ", "Window or tab name is ",
            titleAfterSwitch, matcher));
}
 
Example #26
Source File: SetContextSteps.java    From vividus with Apache License 2.0 3 votes vote down vote up
/**
 * Switching to the frame using one of supported locators
 * <p>
 * A <b>frame</b> is used for splitting browser page into several segments, each of which can show a different
 * document (content). This enables updates of parts of a website while the user browses without making them reload
 * the whole page (this is now largely replaced by AJAX).
 * <p>
 * <b>Frames</b> are located inside {@code <iframe>} tag.
 * <p>
 * Actions performed at this step:
 * <ul>
 * <li>Finds the frame with desired parameters;
 * <li>If frame is found, switches focus to it.
 * </ul>
 * @see <a href="https://en.wikipedia.org/wiki/HTML_element#Frames"><i>Frames</i></a>
 * @see <a href="https://www.w3schools.com/tags/default.asp"><i>HTML Element Reference</i></a>
 * @param locator to locate frame element
 * <p>
 * <b>Example:</b>
 * <pre>
 * {@code <iframe attributeType=}<b>'attributeValue'</b>{@code > some iframe content</iframe>}
 * </pre>
 */
@When("I switch to frame located `$locator`")
public void switchingToFrame(SearchAttributes locator)
{
    changeContextToPage();
    WebElement element = baseValidations.assertIfElementExists("A frame", locator);
    switchToFrame(element);
}
 
Example #27
Source File: SetContextSteps.java    From vividus with Apache License 2.0 3 votes vote down vote up
/**
 * Switch the focus of future browser commands to the new <b>window object</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>
 * Actions performed at this step:
 * <ul>
 * <li>Gets identifier of the currently active window (tab);
 * <li>Switches focus to the first available window with another identifier. So if currently there are 3 opened
 * windows #1, #2, #3 and window #2 is active one, using this method will switch focus to the window #3;
 * </ul>
 * @see <a href="https://html.spec.whatwg.org/#browsing-context"><i>Browsing context (Window &amp; Document)
 * reference</i></a>
 */
@When("I switch to a new window")
public void switchingToWindow()
{
    String currentWindow = getWebDriver().getWindowHandle();
    String newWindow = windowsActions.switchToNewWindow(currentWindow);
    if (highlightingSoftAssert.assertThat(String.format("New window '%s' is found", newWindow),
            "New window is found", newWindow, not(equalTo(currentWindow))))
    {
        changeContextToPage();
    }
}
 
Example #28
Source File: SetVariableSteps.java    From vividus with Apache License 2.0 3 votes vote down vote up
/**
 * Extracts the value of <b>attribute</b> of element found by <b>locator</b> and saves it
 * to the <b>variable</b> with the specified <b>variable name</b>
 * Actions performed at this step:
 * <ul>
 * <li>Saves the value of attribute with name <i>attributeName</i> to the <i>variableName</i>
 * </ul>
 * @param attributeName the name of the attribute (for ex. 'name', 'id')
 * @param locator to search for elements
 * @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 under which the value should be saved
 */
@When("I set '$attributeName' attribute value of the element by $locator to the $scopes variable '$variableName'")
public void setAttributeValueBySelectorToVariable(String attributeName, SearchAttributes locator,
        Set<VariableScope> scopes, String variableName)
{
    locator.getSearchParameters().setVisibility(Visibility.ALL);
    Optional.ofNullable(baseValidations
            .assertIfElementExists("The element to extract the attribute", locator))
            .map(element -> getAssertedAttributeValue(element, attributeName))
            .ifPresent(attributeValue -> bddVariableContext.putVariable(scopes, variableName, attributeValue));
}
 
Example #29
Source File: CheckboxSteps.java    From vividus with Apache License 2.0 3 votes vote down vote up
/**
 * Checks checkbox within the context
 * <p>Actions performed at this step:</p>
 * <ul>
 * <li>Finds a checkbox within the context;</li>
 * <li>Checks its state, if it's <b><i>not selected</i></b> then changes its state
 * <li>Waits for page to load;</li>
 * </ul>
 */
@When("I check a checkbox")
public void checkCheckBox()
{
    WebElement checkBox = baseValidations.assertIfElementExists(CHECKBOX, new SearchAttributes(
            ActionAttributeType.XPATH, CHECKBOX_LOCATOR));
    changeCheckboxState(new Checkbox(checkBox), true);
}
 
Example #30
Source File: CheckboxSteps.java    From vividus with Apache License 2.0 3 votes vote down vote up
/**
 * Checks all enabled checkboxes within the set context
 * <p>Actions performed at this step:</p>
 * <ul>
 * <li> Verifies that at least 1 checkbox is found within the search context;</li>
 * <li> Checks the state of each checkbox found on the page, if it's <b><i>not selected</i></b>
 * then change it to <b><i>selected</i></b>;</li>
 * <li>Waits for page to load;</li>
 * </ul>
 */
@When("I check all the checkboxes")
public void checkAllCheckboxes()
{
    List<WebElement> checkBoxes = baseValidations.assertIfElementsExist("Checkboxes number",
            new SearchAttributes(ActionAttributeType.XPATH, CHECKBOX_LOCATOR));
    checkBoxes.stream().map(Checkbox::new).forEach(checkbox -> changeCheckboxState(checkbox, true));
}