Search in sources :

Example 1 with MoveTargetOutOfBoundsException

use of org.openqa.selenium.interactions.MoveTargetOutOfBoundsException in project selenium_java by sergueik.

the class MouseEventHandler method execute.

@Override
public Void execute(Context context, String... args) {
    log.debug("Mouse event: {}", eventType.commandName);
    WebDriver driver = context.getWrappedDriver();
    List<Long> viewportSize = eval(driver, "return [document.documentElement.clientWidth, document.documentElement.clientHeight];");
    int vpWidth = viewportSize.get(0).intValue();
    int vpHeight = viewportSize.get(1).intValue();
    WebElement element = context.findElement(args[ARG_LOCATOR]);
    Dimension elemSize = element.getSize();
    Point elemLocation = element.getLocation();
    log.debug("Viewport Size: ({}, {}) / Element Location: {} / Element Size: {}", vpWidth, vpHeight, elemLocation, elemSize);
    Function<Actions, Actions> afterMovingMouse;
    Point coord;
    switch(eventType) {
        case MOUSE_OVER:
        case MOUSE_MOVE:
            coord = calcOffset(vpWidth, vpHeight, elemLocation, elemSize);
            afterMovingMouse = actions -> actions;
            break;
        case MOUSE_OUT:
            coord = calcOffsetOutsideElement(vpWidth, vpHeight, elemLocation, elemSize);
            if (coord != null) {
                log.debug("Move to: ({}, {}) on {}", coord.x, coord.y, element);
                afterMovingMouse = actions -> actions;
            } else {
                log.debug("Fire \"mouseleave\" and \"mouseout\" events by JS.");
                eval(driver, FIRE_MOUSE_OUT_EVENT, element);
                return null;
            }
            break;
        case MOUSE_MOVE_AT:
            coord = coordToPoint(args[ARG_COORD]);
            afterMovingMouse = actions -> actions;
            break;
        case MOUSE_DOWN:
            coord = calcOffset(vpWidth, vpHeight, elemLocation, elemSize);
            afterMovingMouse = actions -> actions.clickAndHold();
            break;
        case MOUSE_DOWN_AT:
            coord = coordToPoint(args[ARG_COORD]);
            afterMovingMouse = actions -> actions.clickAndHold();
            break;
        case MOUSE_UP:
            coord = calcOffset(vpWidth, vpHeight, elemLocation, elemSize);
            afterMovingMouse = actions -> actions.release();
            break;
        case MOUSE_UP_AT:
            coord = coordToPoint(args[ARG_COORD]);
            afterMovingMouse = actions -> actions.release();
            break;
        default:
            throw new UnsupportedOperationException("Unsupported command: " + eventType.commandName);
    }
    try {
        afterMovingMouse.apply(MouseUtils.moveTo(context, element, coord)).build().perform();
    } catch (MoveTargetOutOfBoundsException e) {
        log.warn("Cannot mouse pointer move to element: {}", e.getMessage());
        log.warn("Only fire \"{}\" event by JS.", eventType.eventName);
        if (eventType == MouseEventType.MOUSE_OVER) {
            eval(driver, FIRE_MOUSE_OVER_EVENT);
        } else if (eventType.hasCoord) {
            // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent
            Map<String, Object> init = new HashMap<>();
            init.put("clientX", coord.x);
            init.put("clientY", coord.y);
            eval(driver, FIRE_MOUSE_EVENT, element, eventType.eventName, init);
        } else {
            eval(driver, FIRE_MOUSE_EVENT, element, eventType.eventName);
        }
    }
    return null;
}
Also used : WebDriver(org.openqa.selenium.WebDriver) Actions(org.openqa.selenium.interactions.Actions) HashMap(java.util.HashMap) Dimension(org.openqa.selenium.Dimension) Point(org.openqa.selenium.Point) WebElement(org.openqa.selenium.WebElement) Point(org.openqa.selenium.Point) MoveTargetOutOfBoundsException(org.openqa.selenium.interactions.MoveTargetOutOfBoundsException)

Example 2 with MoveTargetOutOfBoundsException

use of org.openqa.selenium.interactions.MoveTargetOutOfBoundsException in project seleniumRobot by bhecquet.

the class DriverExceptionListener method onException.

@Override
public void onException(final Throwable ex, final WebDriver arg1) {
    if (ex.getMessage() == null || ex.getMessage().contains("Element must be user-editable in order to clear it") || ex.getMessage().contains("Element is not clickable at point") || ex instanceof UnsupportedCommandException || ex.getMessage().contains(" read-only") || ex.getMessage().contains("not implemented") || ex instanceof org.openqa.selenium.UnsupportedCommandException || // exception raised when element is non clickable
    ex instanceof MoveTargetOutOfBoundsException || // exception raised when element is non clickable
    ex instanceof InvalidElementStateException) {
    // do nothing
    // Edge driver does return a WebDriverException when doing getPageSource
    } else if (ex.getMessage().contains("No response on ECMAScript evaluation command")) {
        // customexception
        for (int i = 0; i < ex.getStackTrace().length; i++) {
            String method = ex.getStackTrace()[i].getMethodName();
            if (method.contains("getTitle") || method.contains("getWindowHandle") || method.contains("click") || method.contains("getPageSource")) {
                return;
            }
        }
        logger.error(ex);
    } else if (ex.getMessage().contains("Error communicating with the remote browser. It may have died.")) {
        // Session has lost connection, remove it then ignore quit() method.
        if (WebUIDriver.getWebUIDriver(false).getConfig().getMode() == DriverMode.GRID) {
            WebUIDriver.setWebDriver(null);
            throw new WebSessionEndedException(ex);
        }
    } else if (ex instanceof NoSuchWindowException) {
        try {
            WebDriver driver = WebUIDriver.getWebDriver(false);
            List<String> handles = new ArrayList<>(driver.getWindowHandles());
            if (!handles.isEmpty()) {
                try {
                    driver.switchTo().window(handles.get(handles.size() - 1));
                    logger.info("Current window has been closed, switching to previous window to avoid problems in future commands");
                } catch (IndexOutOfBoundsException | NoSuchWindowException e) {
                    driver.switchTo().window(handles.get(0));
                    logger.info("Current window has been closed, switching to first window to avoid problems in future commands");
                }
            }
        } catch (Exception e) {
        // ignore, do not raise exception during handling it
        }
    } else {
        String message = ex.getMessage().split("\\n")[0];
        logger.warn("Got exception:" + message);
        if (ex instanceof org.openqa.selenium.remote.UnreachableBrowserException || ex instanceof NoSuchSessionException || message.matches("Session .*? was terminated due to.*") || message.matches("Session .*? not available .*") || message.matches("cannot forward the request .*") || message.matches("Session is closed") || message.contains("Unable to get browser") || message.contains("not reachable") || message.contains("Tried to run command without establishing a connection") || message.matches("Session ID is null.*") || message.contains("java.net.ConnectException: Failed to connect") || message.contains("java.net.ConnectException: Connection refused")) {
            // can't quit anymore, save time.
            WebUIDriver.setWebDriver(null);
            // terminated.
            throw new WebSessionEndedException(ex);
        // issue #281: chrome < 73: WebDriverException is raised instead of ElementClickInterceptedException
        } else if (message.contains("Other element would receive the click")) {
            throw new ElementClickInterceptedException(message);
        }
    }
}
Also used : WebDriver(org.openqa.selenium.WebDriver) UnsupportedCommandException(org.openqa.selenium.UnsupportedCommandException) NoSuchSessionException(org.openqa.selenium.NoSuchSessionException) ElementClickInterceptedException(org.openqa.selenium.ElementClickInterceptedException) InvalidElementStateException(org.openqa.selenium.InvalidElementStateException) MoveTargetOutOfBoundsException(org.openqa.selenium.interactions.MoveTargetOutOfBoundsException) InvalidElementStateException(org.openqa.selenium.InvalidElementStateException) WebSessionEndedException(com.seleniumtests.customexception.WebSessionEndedException) ElementClickInterceptedException(org.openqa.selenium.ElementClickInterceptedException) NoSuchSessionException(org.openqa.selenium.NoSuchSessionException) MoveTargetOutOfBoundsException(org.openqa.selenium.interactions.MoveTargetOutOfBoundsException) UnsupportedCommandException(org.openqa.selenium.UnsupportedCommandException) NoSuchWindowException(org.openqa.selenium.NoSuchWindowException) WebSessionEndedException(com.seleniumtests.customexception.WebSessionEndedException) NoSuchWindowException(org.openqa.selenium.NoSuchWindowException) ArrayList(java.util.ArrayList) List(java.util.List) UnsupportedCommandException(org.openqa.selenium.UnsupportedCommandException)

Example 3 with MoveTargetOutOfBoundsException

use of org.openqa.selenium.interactions.MoveTargetOutOfBoundsException 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 4 with MoveTargetOutOfBoundsException

use of org.openqa.selenium.interactions.MoveTargetOutOfBoundsException 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 5 with MoveTargetOutOfBoundsException

use of org.openqa.selenium.interactions.MoveTargetOutOfBoundsException in project vividus by vividus-framework.

the class MouseActionsTests method testMoveToElementMoveTargetOutOfBoundsException.

@Test
void testMoveToElementMoveTargetOutOfBoundsException() {
    when(webDriverProvider.get()).thenReturn(webDriver);
    when(((HasInputDevices) webDriver).getMouse()).thenReturn(mouse);
    MoveTargetOutOfBoundsException boundsException = new MoveTargetOutOfBoundsException(COULD_NOT_MOVE_TO_ERROR_MESSAGE);
    Coordinates coordinates = mock(Coordinates.class);
    when(((Locatable) locatableWebElement).getCoordinates()).thenReturn(coordinates);
    doThrow(boundsException).when(mouse).mouseMove(coordinates);
    mouseActions.moveToElement(locatableWebElement);
    verify(softAssert).recordFailedAssertion(COULD_NOT_MOVE_TO_ERROR_MESSAGE + boundsException);
}
Also used : HasInputDevices(org.openqa.selenium.interactions.HasInputDevices) Coordinates(org.openqa.selenium.interactions.Coordinates) MoveTargetOutOfBoundsException(org.openqa.selenium.interactions.MoveTargetOutOfBoundsException) Locatable(org.openqa.selenium.interactions.Locatable) Test(org.junit.jupiter.api.Test)

Aggregations

MoveTargetOutOfBoundsException (org.openqa.selenium.interactions.MoveTargetOutOfBoundsException)8 HashMap (java.util.HashMap)4 WebElement (org.openqa.selenium.WebElement)4 Actions (org.openqa.selenium.interactions.Actions)4 ArrayList (java.util.ArrayList)3 InvalidElementStateException (org.openqa.selenium.InvalidElementStateException)3 WebDriver (org.openqa.selenium.WebDriver)3 TestAction (com.seleniumtests.reporter.logger.TestAction)2 Instant (java.time.Instant)2 Around (org.aspectj.lang.annotation.Around)2 Dimension (org.openqa.selenium.Dimension)2 Point (org.openqa.selenium.Point)2 ConfigurationException (com.seleniumtests.customexception.ConfigurationException)1 DatasetException (com.seleniumtests.customexception.DatasetException)1 ScenarioException (com.seleniumtests.customexception.ScenarioException)1 WebSessionEndedException (com.seleniumtests.customexception.WebSessionEndedException)1 GenericPictureElement (com.seleniumtests.uipage.htmlelements.GenericPictureElement)1 HtmlElement (com.seleniumtests.uipage.htmlelements.HtmlElement)1 List (java.util.List)1 ProceedingJoinPoint (org.aspectj.lang.ProceedingJoinPoint)1