Search in sources :

Example 26 with TestAction

use of com.seleniumtests.reporter.logger.TestAction in project seleniumRobot by bhecquet.

the class LogAction method logAction.

/**
 * Log an action inside a TestStep
 * @param joinPoint		the joinPoint
 * @param targetName	target on which action is done (page or element)
 * @return
 * @throws Throwable
 */
private Object logAction(ProceedingJoinPoint joinPoint, String targetName) throws Throwable {
    List<String> pwdToReplace = new ArrayList<>();
    String actionName = String.format("%s on %s %s", joinPoint.getSignature().getName(), targetName, buildArgString(joinPoint, pwdToReplace, new HashMap<>()));
    Object reply = null;
    boolean actionFailed = false;
    TestAction currentAction = new TestAction(actionName, false, pwdToReplace);
    Throwable currentException = null;
    // order of steps is the right one (first called is first displayed)
    if (TestStepManager.getParentTestStep() != null) {
        TestStepManager.getParentTestStep().addAction(currentAction);
    }
    try {
        reply = joinPoint.proceed(joinPoint.getArgs());
    } catch (Throwable e) {
        actionFailed = true;
        currentException = e;
        throw e;
    } finally {
        if (TestStepManager.getParentTestStep() != null) {
            currentAction.setFailed(actionFailed);
            scenarioLogger.logActionError(currentException);
        }
    }
    return reply;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) PageObject(com.seleniumtests.uipage.PageObject) TestAction(com.seleniumtests.reporter.logger.TestAction)

Example 27 with TestAction

use of com.seleniumtests.reporter.logger.TestAction in project seleniumRobot by bhecquet.

the class LogAction method commonLogTestStep.

/**
 * Log a TestStep, inside a parent TestStep or not
 * Common method used for all test step logging
 * @return
 * @throws Throwable
 */
private Object commonLogTestStep(ProceedingJoinPoint joinPoint, String stepNamePrefix, boolean configStep) throws Throwable {
    Object reply = null;
    boolean rootStep = false;
    TestStep previousParent = null;
    // step name will contain method arguments only if it's not a configuration method (as they are generic)
    TestStep currentStep = buildRootStep(joinPoint, stepNamePrefix, !configStep);
    if ("openPage".equals(joinPoint.getSignature().getName()) && joinPoint.getTarget() instanceof PageObject) {
        PageObject page = (PageObject) joinPoint.getTarget();
        currentStep.addAction(new TestAction(String.format("Opening page %s", page.getClass().getSimpleName()), false, new ArrayList<>()));
    }
    BrowserMobProxy mobProxy = WebUIDriver.getBrowserMobProxy();
    NLWebDriver neoloadDriver = WebUIDriver.getNeoloadDriver();
    VideoRecorder videoRecorder = WebUIDriver.getThreadVideoRecorder();
    // if rootStep is null, parent step is also null
    if (TestStepManager.getCurrentRootTestStep() == null) {
        // will also set parent step
        TestStepManager.setCurrentRootTestStep(currentStep);
        rootStep = true;
        if (mobProxy != null) {
            mobProxy.newPage(currentStep.getName());
        }
        if (videoRecorder != null) {
            CustomEventFiringWebDriver.displayStepOnScreen(currentStep.getName(), SeleniumTestsContextManager.getThreadContext().getRunMode(), SeleniumTestsContextManager.getThreadContext().getSeleniumGridConnector(), videoRecorder);
        }
        if (neoloadDriver != null) {
            neoloadDriver.startTransaction(currentStep.getName());
        }
    } else {
        TestStepManager.getParentTestStep().addStep(currentStep);
        previousParent = TestStepManager.getParentTestStep();
        TestStepManager.setParentTestStep(currentStep);
    }
    // set the start date once step is initialized so that when we get the video frame associated to step, step name displayed on screen is the same as the running step name
    currentStep.setStartDate();
    try {
        reply = joinPoint.proceed(joinPoint.getArgs());
    } catch (Throwable e) {
        currentStep.setFailed(true);
        currentStep.setActionException(e);
        // issue #287 (https://github.com/cbeust/testng/issues/2148): is method an @AfterMethod. Then do not rethrow exception
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        if (methodSignature.getMethod().getAnnotation(AfterMethod.class) != null) {
            scenarioLogger.error(String.format("Error in @AfterMethod %s: %s", methodSignature, e.getMessage()));
        } else {
            throw e;
        }
    } finally {
        if (rootStep) {
            TestStepManager.getCurrentRootTestStep().updateDuration();
            TestStepManager.logTestStep(TestStepManager.getCurrentRootTestStep());
            if (neoloadDriver != null) {
                neoloadDriver.stopTransaction();
            }
        } else {
            TestStepManager.setParentTestStep(previousParent);
        }
    }
    return reply;
}
Also used : TestStep(com.seleniumtests.reporter.logger.TestStep) MethodSignature(org.aspectj.lang.reflect.MethodSignature) NLWebDriver(com.neotys.selenium.proxies.NLWebDriver) ArrayList(java.util.ArrayList) BrowserMobProxy(net.lightbody.bmp.BrowserMobProxy) PageObject(com.seleniumtests.uipage.PageObject) VideoRecorder(com.seleniumtests.util.video.VideoRecorder) PageObject(com.seleniumtests.uipage.PageObject) TestAction(com.seleniumtests.reporter.logger.TestAction)

Example 28 with TestAction

use of com.seleniumtests.reporter.logger.TestAction in project seleniumRobot by bhecquet.

the class ReplayAction method replayHtmlElement.

/**
 * Replay all HtmlElement actions annotated by ReplayOnError.
 * Classes which are not subclass of HtmlElement won't go there
 * See javadoc of the annotation for details
 * @param joinPoint
 * @throws Throwable
 */
@Around("execution(public * com.seleniumtests.uipage.htmlelements.HtmlElement+.* (..))" + "&& execution(@com.seleniumtests.uipage.ReplayOnError public * * (..)) && @annotation(replay)")
public Object replayHtmlElement(ProceedingJoinPoint joinPoint, ReplayOnError replay) throws Throwable {
    Object reply = null;
    // update driver reference of the element
    // corrects bug of waitElementPresent which threw a SessionNotFoundError because driver reference were not
    // updated before searching element (it used the driver reference of an old test session)
    HtmlElement element = (HtmlElement) joinPoint.getTarget();
    element.setDriver(WebUIDriver.getWebDriver(false));
    String targetName = joinPoint.getTarget().toString();
    Instant end = systemClock.instant().plusSeconds(element.getReplayTimeout());
    TestAction currentAction = null;
    String methodName = joinPoint.getSignature().getName();
    if (!methodName.equals("getCoordinates")) {
        List<String> pwdToReplace = new ArrayList<>();
        String actionName = String.format("%s on %s %s", methodName, targetName, LogAction.buildArgString(joinPoint, pwdToReplace, new HashMap<>()));
        currentAction = new TestAction(actionName, false, pwdToReplace);
    }
    // order of steps is the right one (first called is first displayed)
    if (currentAction != null && TestStepManager.getParentTestStep() != null) {
        TestStepManager.getParentTestStep().addAction(currentAction);
    }
    boolean actionFailed = false;
    boolean ignoreFailure = false;
    Throwable currentException = null;
    try {
        while (end.isAfter(systemClock.instant())) {
            // in case we have switched to an iframe for using previous webElement, go to default content
            if (element.getDriver() != null && SeleniumTestsContextManager.isWebTest()) {
                // TODO: error when clic is done, closing current window
                element.getDriver().switchTo().defaultContent();
            }
            try {
                reply = joinPoint.proceed(joinPoint.getArgs());
                // wait will be done only if action annotation request it
                if (replay.waitAfterAction()) {
                    WaitHelper.waitForMilliSeconds(getActionDelay());
                }
                break;
            } catch (UnhandledAlertException e) {
                throw e;
            } catch (MoveTargetOutOfBoundsException | InvalidElementStateException e) {
                if (element.isScrollToElementBeforeAction()) {
                    element.setScrollToElementBeforeAction(false);
                } else {
                    element.setScrollToElementBeforeAction(true);
                }
            } catch (WebDriverException e) {
                // only check that cause is the not found element and not an other error (NoSucheSessionError for example)
                if ((e instanceof TimeoutException && joinPoint.getSignature().getName().equals("waitForPresent") && // issue #104: do not log error when waitForPresent raises TimeoutException
                e.getCause() instanceof NoSuchElementException) || (e instanceof NotFoundException && // issue #194: return immediately if the action has been performed from ExpectedConditions class
                isFromExpectedConditions(Thread.currentThread().getStackTrace()))) // This way, we let the FluentWait process to retry or re-raise the exception
                {
                    ignoreFailure = true;
                    throw e;
                }
                if (end.minusMillis(replay.replayDelayMs() + 100L).isAfter(systemClock.instant())) {
                    WaitHelper.waitForMilliSeconds(replay.replayDelayMs());
                } else {
                    if (e instanceof NoSuchElementException) {
                        throw new NoSuchElementException(String.format("Searched element [%s] from page '%s' could not be found", element, element.getOrigin()));
                    } else if (e instanceof UnreachableBrowserException) {
                        throw new WebDriverException("Browser did not reply, it may have frozen");
                    }
                    throw e;
                }
            }
        }
        return reply;
    } catch (Throwable e) {
        if (e instanceof NoSuchElementException && joinPoint.getTarget() instanceof HtmlElement && (joinPoint.getSignature().getName().equals("findElements") || joinPoint.getSignature().getName().equals("findHtmlElements"))) {
            return new ArrayList<WebElement>();
        } else {
            if (!ignoreFailure) {
                actionFailed = true;
                currentException = e;
            }
            throw e;
        }
    } finally {
        if (currentAction != null && TestStepManager.getParentTestStep() != null) {
            currentAction.setFailed(actionFailed);
            scenarioLogger.logActionError(currentException);
        }
        // restore element scrolling flag for further uses
        element.setScrollToElementBeforeAction(false);
    }
}
Also used : HashMap(java.util.HashMap) HtmlElement(com.seleniumtests.uipage.htmlelements.HtmlElement) UnhandledAlertException(org.openqa.selenium.UnhandledAlertException) Instant(java.time.Instant) ArrayList(java.util.ArrayList) NotFoundException(org.openqa.selenium.NotFoundException) WebElement(org.openqa.selenium.WebElement) RemoteWebElement(org.openqa.selenium.remote.RemoteWebElement) InvalidElementStateException(org.openqa.selenium.InvalidElementStateException) MoveTargetOutOfBoundsException(org.openqa.selenium.interactions.MoveTargetOutOfBoundsException) TestAction(com.seleniumtests.reporter.logger.TestAction) UnreachableBrowserException(org.openqa.selenium.remote.UnreachableBrowserException) NoSuchElementException(org.openqa.selenium.NoSuchElementException) WebDriverException(org.openqa.selenium.WebDriverException) TimeoutException(org.openqa.selenium.TimeoutException) Around(org.aspectj.lang.annotation.Around)

Example 29 with TestAction

use of com.seleniumtests.reporter.logger.TestAction in project seleniumRobot by bhecquet.

the class ReplayAction method replay.

/**
 * Replay all actions annotated by ReplayOnError if the class is not a subclass of
 * HtmlElement
 * @param joinPoint
 * @throws Throwable
 */
@Around("!execution(public * com.seleniumtests.uipage.htmlelements.HtmlElement+.* (..))" + "&& execution(@com.seleniumtests.uipage.ReplayOnError public * * (..)) && @annotation(replay)")
public Object replay(ProceedingJoinPoint joinPoint, ReplayOnError replay) throws Throwable {
    int replayDelayMs = replay != null ? replay.replayDelayMs() : 100;
    Instant end = systemClock.instant().plusSeconds(SeleniumTestsContextManager.getThreadContext().getReplayTimeout());
    Object reply = null;
    String targetName = joinPoint.getTarget().toString();
    TestAction currentAction = null;
    if (joinPoint.getTarget() instanceof GenericPictureElement) {
        String methodName = joinPoint.getSignature().getName();
        List<String> pwdToReplace = new ArrayList<>();
        String actionName = String.format("%s on %s %s", methodName, targetName, LogAction.buildArgString(joinPoint, pwdToReplace, new HashMap<>()));
        currentAction = new TestAction(actionName, false, pwdToReplace);
        // order of steps is the right one (first called is first displayed)
        if (TestStepManager.getParentTestStep() != null) {
            TestStepManager.getParentTestStep().addAction(currentAction);
        }
    }
    boolean actionFailed = false;
    Throwable currentException = null;
    try {
        while (end.isAfter(systemClock.instant())) {
            // raised if action cannot be performed
            if (((CustomEventFiringWebDriver) WebUIDriver.getWebDriver(false)).getBrowserInfo().getBrowser() == BrowserType.CHROME || ((CustomEventFiringWebDriver) WebUIDriver.getWebDriver(false)).getBrowserInfo().getBrowser() == BrowserType.EDGE) {
                updateScrollFlagForElement(joinPoint, true, null);
            }
            try {
                reply = joinPoint.proceed(joinPoint.getArgs());
                WaitHelper.waitForMilliSeconds(200);
                break;
            // do not replay if error comes from scenario
            } catch (ScenarioException | ConfigurationException | DatasetException e) {
                throw e;
            } catch (MoveTargetOutOfBoundsException | InvalidElementStateException e) {
                updateScrollFlagForElement(joinPoint, null, e);
            } catch (Throwable e) {
                if (end.minusMillis(200).isAfter(systemClock.instant())) {
                    WaitHelper.waitForMilliSeconds(replayDelayMs);
                    continue;
                } else {
                    throw e;
                }
            }
        }
        return reply;
    } catch (Throwable e) {
        actionFailed = true;
        currentException = e;
        throw e;
    } finally {
        if (currentAction != null && TestStepManager.getParentTestStep() != null) {
            currentAction.setFailed(actionFailed);
            scenarioLogger.logActionError(currentException);
            if (joinPoint.getTarget() instanceof GenericPictureElement) {
                currentAction.setDurationToExclude(((GenericPictureElement) joinPoint.getTarget()).getActionDuration());
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) Instant(java.time.Instant) ArrayList(java.util.ArrayList) InvalidElementStateException(org.openqa.selenium.InvalidElementStateException) ProceedingJoinPoint(org.aspectj.lang.ProceedingJoinPoint) MoveTargetOutOfBoundsException(org.openqa.selenium.interactions.MoveTargetOutOfBoundsException) TestAction(com.seleniumtests.reporter.logger.TestAction) GenericPictureElement(com.seleniumtests.uipage.htmlelements.GenericPictureElement) DatasetException(com.seleniumtests.customexception.DatasetException) ConfigurationException(com.seleniumtests.customexception.ConfigurationException) ScenarioException(com.seleniumtests.customexception.ScenarioException) Around(org.aspectj.lang.annotation.Around)

Example 30 with TestAction

use of com.seleniumtests.reporter.logger.TestAction in project seleniumRobot by bhecquet.

the class TestJiraConnector method init.

@BeforeMethod(groups = { "no-ti" })
public void init() throws IOException {
    File tmpImg = File.createTempFile("img", ".png");
    File tmpHtml = File.createTempFile("html", ".html");
    screenshot = new ScreenShot();
    screenshot.setImagePath("screenshot/" + tmpImg.getName());
    screenshot.setHtmlSourcePath("htmls/" + tmpHtml.getName());
    FileUtils.copyFile(tmpImg, new File(screenshot.getFullImagePath()));
    FileUtils.copyFile(tmpHtml, new File(screenshot.getFullHtmlPath()));
    step1 = new TestStep("step 1", null, new ArrayList<>(), false);
    step1.addSnapshot(new Snapshot(screenshot, "main", SnapshotCheckType.FULL), 1, null);
    step2 = new TestStep("step 2", null, new ArrayList<>(), false);
    step2.setFailed(true);
    step2.addAction(new TestAction("action1", false, new ArrayList<>()));
    step2.addAction(new TestAction("action2", false, new ArrayList<>()));
    step2.addSnapshot(new Snapshot(screenshot, "main", SnapshotCheckType.FULL), 1, null);
    stepEnd = new TestStep("Test end", null, new ArrayList<>(), false);
    stepEnd.addSnapshot(new Snapshot(screenshot, "end", SnapshotCheckType.FULL), 1, null);
    stepEnd.addSnapshot(new Snapshot(screenshot, "end2", SnapshotCheckType.FULL), 1, null);
}
Also used : TestStep(com.seleniumtests.reporter.logger.TestStep) Snapshot(com.seleniumtests.reporter.logger.Snapshot) ScreenShot(com.seleniumtests.driver.screenshots.ScreenShot) ArrayList(java.util.ArrayList) File(java.io.File) TestAction(com.seleniumtests.reporter.logger.TestAction) BeforeMethod(org.testng.annotations.BeforeMethod)

Aggregations

TestAction (com.seleniumtests.reporter.logger.TestAction)56 TestStep (com.seleniumtests.reporter.logger.TestStep)47 Test (org.testng.annotations.Test)44 ArrayList (java.util.ArrayList)38 GenericTest (com.seleniumtests.GenericTest)24 TestMessage (com.seleniumtests.reporter.logger.TestMessage)12 DriverExceptions (com.seleniumtests.customexception.DriverExceptions)8 ScreenShot (com.seleniumtests.driver.screenshots.ScreenShot)5 Snapshot (com.seleniumtests.reporter.logger.Snapshot)5 File (java.io.File)5 HashMap (java.util.HashMap)5 GenericFile (com.seleniumtests.reporter.logger.GenericFile)3 Element (org.jdom2.Element)3 WebDriverException (org.openqa.selenium.WebDriverException)3 HarCapture (com.seleniumtests.reporter.logger.HarCapture)2 PageObject (com.seleniumtests.uipage.PageObject)2 Instant (java.time.Instant)2 Har (net.lightbody.bmp.core.har.Har)2 HarLog (net.lightbody.bmp.core.har.HarLog)2 HarPage (net.lightbody.bmp.core.har.HarPage)2