Search in sources :

Example 6 with FailureException

use of com.github.noraui.exception.FailureException in project NoraUi by NoraUi.

the class CommonSteps method clickOnAndSwitchWindow.

/**
 * Click on html element and switch window when the scenario contain more one windows (one more application for example), if all 'expected' parameters equals 'actual' parameters in conditions.
 *
 * @param page
 *            The concerned page of toClick
 * @param toClick
 *            html element
 * @param windowKey
 *            the key of window (popup, ...) Example: 'demo.Popup1DemoPage'.
 * @param conditions
 *            list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}).
 * @throws FailureException
 *             if the scenario encounters a functional error
 * @throws TechnicalException
 *             is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi.
 */
@Conditioned
@Quand("Je clique sur '(.*)-(.*)' et passe sur '(.*)' de type fenĂȘtre[\\.|\\?]")
@When("I click on '(.*)-(.*)' and switch to '(.*)' window[\\.|\\?]")
public void clickOnAndSwitchWindow(String page, String toClick, String windowKey, List<GherkinStepCondition> conditions) throws FailureException, TechnicalException {
    final String wKey = Page.getInstance(page).getApplication() + Page.getInstance(windowKey).getPageKey();
    final String handleToSwitch = Context.getWindows().get(wKey);
    if (handleToSwitch != null) {
        Context.getDriver().switchTo().window(handleToSwitch);
        // As a workaround: NoraUi specify window size manually, e.g. window_size: 1920 x 1080 (instead of .window().maximize()).
        Context.getDriver().manage().window().setSize(new Dimension(1920, 1080));
        Context.setMainWindow(windowKey);
    } else {
        try {
            final Set<String> initialWindows = getDriver().getWindowHandles();
            clickOn(Page.getInstance(page).getPageElementByKey('-' + toClick));
            final String newWindowHandle = Context.waitUntil(WindowManager.newWindowOpens(initialWindows));
            Context.addWindow(wKey, newWindowHandle);
            getDriver().switchTo().window(newWindowHandle);
            // As a workaround: NoraUi specify window size manually, e.g. window_size: 1920 x 1080 (instead of .window().maximize()).
            Context.getDriver().manage().window().setSize(new Dimension(1920, 1080));
            Context.setMainWindow(newWindowHandle);
        } catch (final Exception e) {
            new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_SWITCH_WINDOW), windowKey), true, Page.getInstance(page).getCallBack());
        }
        if (!Page.getInstance(windowKey).checkPage()) {
            new Result.Failure<>(windowKey, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_SWITCH_WINDOW), windowKey), true, Page.getInstance(page).getCallBack());
        }
    }
}
Also used : Dimension(org.openqa.selenium.Dimension) FailureException(com.github.noraui.exception.FailureException) TechnicalException(com.github.noraui.exception.TechnicalException) Result(com.github.noraui.exception.Result) When(cucumber.api.java.en.When) Conditioned(com.github.noraui.cucumber.annotation.Conditioned) Quand(cucumber.api.java.fr.Quand)

Example 7 with FailureException

use of com.github.noraui.exception.FailureException in project NoraUi by NoraUi.

the class LogoGameSteps method saveScore.

@Alors("Je sauvegarde le score")
@Then("I save score")
public void saveScore() throws FailureException {
    try {
        WebElement message = Context.waitUntil(ExpectedConditions.presenceOfElementLocated(Utilities.getLocator(this.logoGamePage.scoreMessage)));
        try {
            Context.getCurrentScenario().write("score is:\n" + message.getText());
            Context.getDataOutputProvider().writeDataResult("score", Context.getDataInputProvider().getIndexData(Context.getCurrentScenarioData()).getIndexes().get(0), message.getText());
        } catch (TechnicalException e) {
            logger.error(Messages.getMessage(TechnicalException.TECHNICAL_ERROR_MESSAGE), e);
        }
    } catch (Exception e) {
        new Result.Failure<>(e.getMessage(), "", true, this.logoGamePage.getCallBack());
    }
}
Also used : TechnicalException(com.github.noraui.exception.TechnicalException) WebElement(org.openqa.selenium.WebElement) FailureException(com.github.noraui.exception.FailureException) TechnicalException(com.github.noraui.exception.TechnicalException) Result(com.github.noraui.exception.Result) Alors(cucumber.api.java.fr.Alors) Then(cucumber.api.java.en.Then)

Example 8 with FailureException

use of com.github.noraui.exception.FailureException in project NoraUi by NoraUi.

the class StepInterceptor method invoke.

/**
 * {@inheritDoc}
 */
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    Object result = null;
    Method m = invocation.getMethod();
    Annotation[] annotations = m.getAnnotations();
    if (annotations.length > 0) {
        Annotation stepAnnotation = annotations[annotations.length - 1];
        for (Annotation a : annotations) {
            if (a.annotationType().getName().startsWith("cucumber.api.java." + Context.getLocale().getLanguage())) {
                stepAnnotation = a;
                break;
            }
        }
        if (stepAnnotation.annotationType().isAnnotationPresent(StepDefAnnotation.class)) {
            Matcher matcher = Pattern.compile("value=(.*)\\)").matcher(stepAnnotation.toString());
            if (matcher.find()) {
                logger.info("> " + stepAnnotation.annotationType().getSimpleName() + " " + String.format(matcher.group(1).replace("(.*)", "%s").replace("[\\.|\\?]", ""), invocation.getArguments()));
            }
        }
    }
    if (m.isAnnotationPresent(RetryOnFailure.class)) {
        RetryOnFailure retryAnnotation = m.getAnnotation(RetryOnFailure.class);
        if (retryAnnotation.verbose()) {
            logger.info("NORAUI StepInterceptor invoke method " + m);
        }
        for (int i = 0; i < retryAnnotation.attempts(); i++) {
            try {
                if (retryAnnotation.verbose()) {
                    logger.info("NORAUI StepInterceptor attempt n° " + i);
                }
                return invocation.proceed();
            } catch (FailureException e) {
                if (retryAnnotation.verbose()) {
                    logger.info("NORAUI StepInterceptor Exception " + e.getMessage());
                }
                if (i == retryAnnotation.attempts() - 1) {
                    e.getFailure().fail();
                }
                Thread.sleep(retryAnnotation.unit().toMillis(retryAnnotation.delay()));
            }
        }
    } else {
        try {
            return invocation.proceed();
        } catch (FailureException e) {
            if (Modifier.isPublic(m.getModifiers())) {
                e.getFailure().fail();
            } else {
                throw e;
            }
        }
    }
    return result;
}
Also used : Matcher(java.util.regex.Matcher) Method(java.lang.reflect.Method) FailureException(com.github.noraui.exception.FailureException) StepDefAnnotation(cucumber.runtime.java.StepDefAnnotation) Annotation(java.lang.annotation.Annotation) RetryOnFailure(com.github.noraui.cucumber.annotation.RetryOnFailure)

Example 9 with FailureException

use of com.github.noraui.exception.FailureException in project NoraUi by NoraUi.

the class MailSteps method validActivationEmail.

/**
 * Valid activation email.
 *
 * @param mailHost
 *            example: imap.gmail.com
 * @param mailUser
 *            login of mail box
 * @param mailPassword
 *            password of mail box
 * @param firstCssQuery
 *            the first matching element
 * @param conditions
 *            list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}).
 * @throws TechnicalException
 *             is throws if you have a technical error (format, configuration, datas, ...) in NoraUi.
 *             Exception with message and with screenshot and with exception if functional error but no screenshot and no exception if technical error.
 * @throws FailureException
 *             if the scenario encounters a functional error
 */
@RetryOnFailure(attempts = 3, delay = 60)
@Conditioned
@Et("Je valide le mail d'activation '(.*)'[\\.|\\?]")
@And("I valid activation email '(.*)'[\\.|\\?]")
public void validActivationEmail(String mailHost, String mailUser, String mailPassword, String senderMail, String subjectMail, String firstCssQuery, List<GherkinStepCondition> conditions) throws FailureException, TechnicalException {
    RestTemplate restTemplate = createRestTemplate();
    try {
        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imap");
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");
        store.connect(mailHost, mailUser, mailPassword);
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        SearchTerm filterA = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        SearchTerm filterB = new FromTerm(new InternetAddress(senderMail));
        SearchTerm filterC = new SubjectTerm(subjectMail);
        SearchTerm[] filters = { filterA, filterB, filterC };
        SearchTerm searchTerm = new AndTerm(filters);
        Message[] messages = inbox.search(searchTerm);
        for (Message message : messages) {
            Document doc = Jsoup.parse(getTextFromMessage(message));
            Element link = doc.selectFirst(firstCssQuery);
            HttpHeaders headers = new HttpHeaders();
            HttpEntity<String> entity = new HttpEntity<>(headers);
            ResponseEntity<String> response = restTemplate.exchange(link.attr("href"), HttpMethod.GET, entity, String.class);
            if (!response.getStatusCode().equals(HttpStatus.OK)) {
                new Result.Failure<>("", Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_MAIL_ACTIVATION), subjectMail), false, Context.getCallBack(Callbacks.RESTART_WEB_DRIVER));
            }
        }
    } catch (Exception e) {
        new Result.Failure<>("", Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_MAIL_ACTIVATION), subjectMail), false, Context.getCallBack(Callbacks.RESTART_WEB_DRIVER));
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) HttpEntity(org.springframework.http.HttpEntity) Element(org.jsoup.nodes.Element) Store(javax.mail.Store) Properties(java.util.Properties) Folder(javax.mail.Folder) Document(org.jsoup.nodes.Document) Result(com.github.noraui.exception.Result) AndTerm(javax.mail.search.AndTerm) FlagTerm(javax.mail.search.FlagTerm) RetryOnFailure(com.github.noraui.cucumber.annotation.RetryOnFailure) Flags(javax.mail.Flags) SearchTerm(javax.mail.search.SearchTerm) SubjectTerm(javax.mail.search.SubjectTerm) MessagingException(javax.mail.MessagingException) FailureException(com.github.noraui.exception.FailureException) IOException(java.io.IOException) TechnicalException(com.github.noraui.exception.TechnicalException) RestTemplate(org.springframework.web.client.RestTemplate) FromTerm(javax.mail.search.FromTerm) Session(javax.mail.Session) Conditioned(com.github.noraui.cucumber.annotation.Conditioned) And(cucumber.api.java.en.And) RetryOnFailure(com.github.noraui.cucumber.annotation.RetryOnFailure) Et(cucumber.api.java.fr.Et)

Example 10 with FailureException

use of com.github.noraui.exception.FailureException in project NoraUi by NoraUi.

the class Step method checkText.

/**
 * Checks if HTML text contains expected value.
 *
 * @param pageElement
 *            Is target element
 * @param textOrKey
 *            Is the new data (text or text in context (after a save))
 * @throws TechnicalException
 *             is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi.
 *             Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_WRONG_EXPECTED_VALUE} message (with screenshot, with exception) or with
 *             {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT} message
 *             (with screenshot, with exception)
 * @throws FailureException
 *             if the scenario encounters a functional error
 */
protected void checkText(PageElement pageElement, String textOrKey) throws TechnicalException, FailureException {
    WebElement webElement = null;
    final String value = Context.getValue(textOrKey) != null ? Context.getValue(textOrKey) : textOrKey;
    try {
        webElement = Context.waitUntil(ExpectedConditions.presenceOfElementLocated(Utilities.getLocator(pageElement)));
    } catch (final Exception e) {
        new Result.Failure<>(e.getMessage(), Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT), true, pageElement.getPage().getCallBack());
    }
    final String innerText = webElement == null ? null : webElement.getText();
    logger.info("checkText() expected [{}] and found [{}].", value, innerText);
    if (!value.equals(innerText)) {
        new Result.Failure<>(innerText, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_WRONG_EXPECTED_VALUE), pageElement, value, pageElement.getPage().getApplication()), true, pageElement.getPage().getCallBack());
    }
}
Also used : WebElement(org.openqa.selenium.WebElement) ParseException(java.text.ParseException) FailureException(com.github.noraui.exception.FailureException) TechnicalException(com.github.noraui.exception.TechnicalException) Result(com.github.noraui.exception.Result)

Aggregations

FailureException (com.github.noraui.exception.FailureException)14 Result (com.github.noraui.exception.Result)13 TechnicalException (com.github.noraui.exception.TechnicalException)13 WebElement (org.openqa.selenium.WebElement)11 ParseException (java.text.ParseException)10 Conditioned (com.github.noraui.cucumber.annotation.Conditioned)2 RetryOnFailure (com.github.noraui.cucumber.annotation.RetryOnFailure)2 JavascriptExecutor (org.openqa.selenium.JavascriptExecutor)2 And (cucumber.api.java.en.And)1 Then (cucumber.api.java.en.Then)1 When (cucumber.api.java.en.When)1 Alors (cucumber.api.java.fr.Alors)1 Et (cucumber.api.java.fr.Et)1 Quand (cucumber.api.java.fr.Quand)1 StepDefAnnotation (cucumber.runtime.java.StepDefAnnotation)1 IOException (java.io.IOException)1 Annotation (java.lang.annotation.Annotation)1 Method (java.lang.reflect.Method)1 Properties (java.util.Properties)1 Matcher (java.util.regex.Matcher)1