org.openqa.selenium.UnhandledAlertException Java Examples

The following examples show how to use org.openqa.selenium.UnhandledAlertException. 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: Screenshoter.java    From teasy with MIT License 6 votes vote down vote up
public String takeScreenshot(final String errorMessage, final String testName) {
    try {
        BufferedImage image;
        if (Configuration.browser.equals("chrome")) {
            image = ImageIO.read(new ChromeScreenshoter().getFullScreenshotAs(OutputType.FILE));
        } else {
            image = ImageIO.read(((TakesScreenshot)DriverHolder.getDriver()).getScreenshotAs(OutputType.FILE));
        }

        printStrings(image, removeNL(testName, errorMessage));

        final String pathName = getFilenameFor(testName);
        final File screenShotWithProjectPath = new File(pathName);
        ImageIO.write(image, "png", screenShotWithProjectPath);
        attachScreenShotToAllure(errorMessage, testName, screenShotWithProjectPath);
        return screenShotWithProjectPath.getAbsolutePath();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    } catch (UnhandledAlertException alertException) {
        Alert alert = DriverHolder.getDriver().switchTo().alert();
        alert.dismiss();
        return takeScreenshot(errorMessage, testName);
    }
}
 
Example #2
Source File: WebPage.java    From phoenix.webui.framework with Apache License 2.0 6 votes vote down vote up
@Override
public void open()
{
	String paramUrl = paramTranslate(getUrl());
	
	engine.openUrl(paramUrl);
	
	try
	{
		engine.computeToolbarHeight();
	}
	catch(UnhandledAlertException e)
	{
		Alert alert = engine.getDriver().switchTo().alert();
		if(alert != null)
		{
			alert.dismiss();

			engine.computeToolbarHeight();
		}
	}
}
 
Example #3
Source File: BrowserTest.java    From hsac-fitnesse-fixtures with Apache License 2.0 6 votes vote down vote up
/**
 * Takes screenshot from current page
 * @param basename filename (below screenshot base directory).
 * @return location of screenshot.
 */
public String takeScreenshot(String basename) {
    try {
        String screenshotFile = createScreenshot(basename);
        if (screenshotFile == null) {
            throw new SlimFixtureException(false, "Unable to take screenshot: does the webdriver support it?");
        } else {
            screenshotFile = getScreenshotLink(screenshotFile);
        }
        return screenshotFile;
    } catch (UnhandledAlertException e) {
        // standard behavior will stop test, this breaks storyboard that will attempt to take screenshot
        // after triggering alert, but before the alert can be handled.
        // so we output a message but no exception. We rely on a next line to actually handle alert
        // (which may mean either really handle or stop test).
        return String.format(
                "<div><strong>Unable to take screenshot</strong>, alert is active. Alert text:<br/>" +
                        "'<span>%s</span>'</div>",
                StringEscapeUtils.escapeHtml4(alertText()));
    }
}
 
Example #4
Source File: ErrorHandler.java    From selenium with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private UnhandledAlertException createUnhandledAlertException(Object value) {
  Map<String, Object> rawErrorData = (Map<String, Object>) value;
  if (rawErrorData.containsKey("alert") || rawErrorData.containsKey("alertText")) {
    Object alertText = rawErrorData.get("alertText");
    if (alertText == null) {
      Map<String, Object> alert = (Map<String, Object>) rawErrorData.get("alert");
      if (alert != null) {
        alertText = alert.get("text");
      }
    }
    return createThrowable(UnhandledAlertException.class,
        new Class<?>[] {String.class, String.class},
        new Object[] {rawErrorData.get("message"), alertText});
  }
  return null;
}
 
Example #5
Source File: W3CHttpResponseCodec.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
protected Object getValueToEncode(Response response) {
  HashMap<Object, Object> toReturn = new HashMap<>();
  Object value = response.getValue();
  if (value instanceof WebDriverException) {
    HashMap<Object, Object> exception = new HashMap<>();
    exception.put(
        "error",
        response.getState() != null ?
        response.getState() :
        errorCodes.toState(response.getStatus()));
    exception.put("message", ((WebDriverException) value).getMessage());
    exception.put("stacktrace", Throwables.getStackTraceAsString((WebDriverException) value));
    if (value instanceof UnhandledAlertException) {
      HashMap<String, Object> data = new HashMap<>();
      data.put("text", ((UnhandledAlertException) value).getAlertText());
      exception.put("data", data);
    }

    value = exception;
  }
  toReturn.put("value", value);
  return toReturn;
}
 
Example #6
Source File: DriverHelper.java    From carina with Apache License 2.0 6 votes vote down vote up
/**
    * Opens full or relative URL.
    * 
    * @param url
    *            to open.
    */
public void openURL(String url) {
	String decryptedURL = cryptoTool.decryptByPattern(url, CRYPTO_PATTERN);

	decryptedURL = getEnvArgURL(decryptedURL);

	WebDriver drv = getDriver();

	Messager.OPENING_URL.info(url);

	DriverListener.setMessages(Messager.OPEN_URL.getMessage(url), Messager.NOT_OPEN_URL.getMessage(url));
       
       try {
           drv.get(decryptedURL);
       } catch (UnhandledAlertException e) {
           drv.switchTo().alert().accept();
       }
   }
 
Example #7
Source File: DebugMarkerFeatureTest.java    From webtester-core with Apache License 2.0 5 votes vote down vote up
@Test(expected = UnhandledAlertException.class)
public void demonstrateDebugMarking() {
    String username = page.usernameCredential.getText();
    String password = page.passwordCredential.getText();

    page.username.setText(username);
    page.password.setText(password);
    page.login.click();
    getBrowser().acceptAlertIfVisible();
}
 
Example #8
Source File: BrowserTest.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
protected String getExceptionScreenshotTag(String screenshotBaseName, String messageBase, Throwable t) {
    String screenshotTag = "(Screenshot not available)";
    try {
        String screenShotFile = createScreenshot(screenshotBaseName, t);
        screenshotTag = getScreenshotLink(screenShotFile);
    } catch (UnhandledAlertException e) {
        // https://code.google.com/p/selenium/issues/detail?id=4412
        System.err.println("Unable to take screenshot while alert is present for exception: " + messageBase);
    } catch (Exception sse) {
        System.err.println("Unable to take screenshot for exception: " + messageBase);
        sse.printStackTrace();
    }
    return screenshotTag;
}
 
Example #9
Source File: JsonOutputTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConvertUnhandledAlertException() {
  RuntimeException clientError = new UnhandledAlertException("unhandled alert", "cheese!");
  Map<String, Object> obj = new Json().toType(new StringReader(convert(clientError)), Map.class);
  assertThat(obj).containsKey("alert");
  assertThat(obj.get("alert")).isEqualTo(ImmutableMap.of("text", "cheese!"));
}
 
Example #10
Source File: W3CHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldPopulateTheAlertTextIfThrowingAnUnhandledAlertException() {
  Map<String, Map<String, Serializable>> data = ImmutableMap.of(
      "value", ImmutableMap.of(
          "error", "unexpected alert open",
          "message", "Modal dialog present",
          "stacktrace", "",
          "data", ImmutableMap.of("text", "cheese")));

  HttpResponse response = createValidResponse(500, data);
  Response decoded = new W3CHttpResponseCodec().decode(response);

  UnhandledAlertException ex = (UnhandledAlertException) decoded.getValue();
  assertThat(ex.getAlertText()).isEqualTo("cheese");
}
 
Example #11
Source File: WebDriverInterface.java    From candybean with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Click &quot;OK&quot; on a modal dialog box (usually referred to
 * as a &quot;javascript dialog&quot;).
 */
public void acceptDialog() {
	try {
		logger.info("Accepting dialog.");
		this.wd.switchTo().alert().accept();
		this.waitForAlertDismissal();
	} catch(UnhandledAlertException uae) {
		logger.warning("Unhandled alert exception");
	}
}
 
Example #12
Source File: WebDriverInterface.java    From candybean with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Dismisses a modal dialog box (usually referred to
 * as a &quot;javascript dialog&quot;).
 *
 */
public void dismissDialog() {
	try {
		logger.info("Dismissing dialog.");
		this.wd.switchTo().alert().dismiss();
		this.waitForAlertDismissal();
	} catch(UnhandledAlertException uae) {
		logger.warning("Unhandled alert exception");
	}
}
 
Example #13
Source File: WebDriverInterface.java    From candybean with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Returns true if a modal dialog can be switched to 
 * and switched back from; otherwise, returns false.
 * 
 * @return 	Boolean true only if a modal dialog can 
 * be switched to, then switched back from.
 */
public boolean isDialogVisible() {
	try { 
		this.wd.switchTo().alert(); 
		logger.info("Dialog present?: true.");
		return true;
	} catch(UnhandledAlertException uae) {
		logger.info("(Unhandled alert in FF?) Dialog present?: true.  May have ignored dialog...");
		return true;
	} catch(NoAlertPresentException nape) {
		logger.info("Dialog present?: false.");
		return false;
	}
}
 
Example #14
Source File: ErrorHandler.java    From selenium with Apache License 2.0 4 votes vote down vote up
private Throwable rebuildServerError(Map<String, Object> rawErrorData, int responseStatus) {

    if (rawErrorData.get(CLASS) == null && rawErrorData.get(STACK_TRACE) == null) {
      // Not enough information for us to try to rebuild an error.
      return null;
    }

    Throwable toReturn = null;
    String message = (String) rawErrorData.get(MESSAGE);
    Class<?> clazz = null;

    // First: allow Remote Driver to specify the Selenium Server internal exception
    if (rawErrorData.get(CLASS) != null) {
      String className = (String) rawErrorData.get(CLASS);
      try {
        clazz = Class.forName(className);
      } catch (ClassNotFoundException ignored) {
        // Ok, fall-through
      }
    }

    // If the above fails, map Response Status to Exception class
    if (null == clazz) {
      clazz = errorCodes.getExceptionType(responseStatus);
    }

    if (clazz.equals(UnhandledAlertException.class)) {
      toReturn = createUnhandledAlertException(rawErrorData);
    } else if (Throwable.class.isAssignableFrom(clazz)) {
      @SuppressWarnings({"unchecked"})
      Class<? extends Throwable> throwableType = (Class<? extends Throwable>) clazz;
      toReturn = createThrowable(
          throwableType,
          new Class<?>[] {String.class},
          new Object[] {message});
    }

    if (toReturn == null) {
      toReturn = new UnknownServerException(message);
    }

    // Note: if we have a class name above, we should always have a stack trace.
    // The inverse is not always true.
    StackTraceElement[] stackTrace = new StackTraceElement[0];
    if (rawErrorData.get(STACK_TRACE) != null) {
      @SuppressWarnings({"unchecked"})
      List<Map<String, Object>> stackTraceInfo =
          (List<Map<String, Object>>) rawErrorData.get(STACK_TRACE);

      stackTrace = stackTraceInfo.stream()
          .map(entry -> new FrameInfoToStackFrame().apply(entry))
          .filter(Objects::nonNull)
          .toArray(StackTraceElement[]::new);
    }

    toReturn.setStackTrace(stackTrace);
    return toReturn;
  }
 
Example #15
Source File: W3CHttpResponseCodec.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Override
public Response decode(HttpResponse encodedResponse) {
  String content = string(encodedResponse).trim();
  log.fine(String.format(
    "Decoding response. Response code was: %d and content: %s",
    encodedResponse.getStatus(),
    content));
  String contentType = nullToEmpty(encodedResponse.getHeader(CONTENT_TYPE));

  Response response = new Response();

  // Are we dealing with an error?
  // {"error":"no such alert","message":"No tab modal was open when attempting to get the dialog text"}
  if (HTTP_OK != encodedResponse.getStatus()) {
    log.fine("Processing an error");
    if (HTTP_BAD_METHOD == encodedResponse.getStatus()) {
      response.setStatus(ErrorCodes.UNKNOWN_COMMAND);
      response.setValue(content);
    } else {
      Map<String, Object> obj = json.toType(content, MAP_TYPE);

      Object w3cWrappedValue = obj.get("value");
      if (w3cWrappedValue instanceof Map && ((Map<?, ?>) w3cWrappedValue).containsKey("error")) {
        //noinspection unchecked
        obj = (Map<String, Object>) w3cWrappedValue;
      }

      String message = "An unknown error has occurred";
      if (obj.get("message") instanceof String) {
        message = (String) obj.get("message");
      }

      String error = "unknown error";
      if (obj.get("error") instanceof String) {
        error = (String) obj.get("error");
      }

      response.setState(error);
      response.setStatus(errorCodes.toStatus(error, Optional.of(encodedResponse.getStatus())));

      // For now, we'll inelegantly special case unhandled alerts.
      if ("unexpected alert open".equals(error) &&
          HTTP_INTERNAL_ERROR == encodedResponse.getStatus()) {
        String text = "";
        Object data = obj.get("data");
        if (data != null) {
          Object rawText = ((Map<?, ?>) data).get("text");
          if (rawText instanceof String) {
            text = (String) rawText;
          }
        }
        response.setValue(new UnhandledAlertException(message, text));
      } else {
        response.setValue(createException(error, message));
      }
    }
    return response;
  }

  response.setState("success");
  response.setStatus(ErrorCodes.SUCCESS);
  if (!content.isEmpty()) {
    if (contentType.startsWith("application/json") || Strings.isNullOrEmpty("")) {
      Map<String, Object> parsed = json.toType(content, MAP_TYPE);
      if (parsed.containsKey("value")) {
        Object value = parsed.get("value");
        response.setValue(value);
      } else {
        // Assume that the body of the response was the response.
        response.setValue(json.toType(content, OBJECT_TYPE));
      }
    }
  }

  if (response.getValue() instanceof String) {
    // We normalise to \n because Java will translate this to \r\n
    // if this is suitable on our platform, and if we have \r\n, java will
    // turn this into \r\r\n, which would be Bad!
    response.setValue(((String) response.getValue()).replace("\r\n", "\n"));
  }

  return response;
}
 
Example #16
Source File: ErrorHandlerTest.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Test
public void testStatusCodesRaisedBackToStatusMatches() {
  Map<Integer, Class<?>> exceptions = new HashMap<>();
  exceptions.put(ErrorCodes.NO_SUCH_SESSION, NoSuchSessionException.class);
  exceptions.put(ErrorCodes.NO_SUCH_ELEMENT, NoSuchElementException.class);
  exceptions.put(ErrorCodes.NO_SUCH_FRAME, NoSuchFrameException.class);
  exceptions.put(ErrorCodes.UNKNOWN_COMMAND, UnsupportedCommandException.class);
  exceptions.put(ErrorCodes.STALE_ELEMENT_REFERENCE, StaleElementReferenceException.class);
  exceptions.put(ErrorCodes.ELEMENT_NOT_VISIBLE, ElementNotVisibleException.class);
  exceptions.put(ErrorCodes.INVALID_ELEMENT_STATE, InvalidElementStateException.class);
  exceptions.put(ErrorCodes.UNHANDLED_ERROR, WebDriverException.class);
  exceptions.put(ErrorCodes.ELEMENT_NOT_SELECTABLE, ElementNotSelectableException.class);
  exceptions.put(ErrorCodes.JAVASCRIPT_ERROR, JavascriptException.class);
  exceptions.put(ErrorCodes.XPATH_LOOKUP_ERROR, InvalidSelectorException.class);
  exceptions.put(ErrorCodes.TIMEOUT, TimeoutException.class);
  exceptions.put(ErrorCodes.NO_SUCH_WINDOW, NoSuchWindowException.class);
  exceptions.put(ErrorCodes.INVALID_COOKIE_DOMAIN, InvalidCookieDomainException.class);
  exceptions.put(ErrorCodes.UNABLE_TO_SET_COOKIE, UnableToSetCookieException.class);
  exceptions.put(ErrorCodes.UNEXPECTED_ALERT_PRESENT, UnhandledAlertException.class);
  exceptions.put(ErrorCodes.NO_ALERT_PRESENT, NoAlertPresentException.class);
  exceptions.put(ErrorCodes.ASYNC_SCRIPT_TIMEOUT, ScriptTimeoutException.class);
  exceptions.put(ErrorCodes.INVALID_ELEMENT_COORDINATES, InvalidCoordinatesException.class);
  exceptions.put(ErrorCodes.IME_NOT_AVAILABLE, ImeNotAvailableException.class);
  exceptions.put(ErrorCodes.IME_ENGINE_ACTIVATION_FAILED, ImeActivationFailedException.class);
  exceptions.put(ErrorCodes.INVALID_SELECTOR_ERROR, InvalidSelectorException.class);
  exceptions.put(ErrorCodes.SESSION_NOT_CREATED, SessionNotCreatedException.class);
  exceptions.put(ErrorCodes.MOVE_TARGET_OUT_OF_BOUNDS, MoveTargetOutOfBoundsException.class);
  exceptions.put(ErrorCodes.INVALID_XPATH_SELECTOR, InvalidSelectorException.class);
  exceptions.put(ErrorCodes.INVALID_XPATH_SELECTOR_RETURN_TYPER, InvalidSelectorException.class);

  for (Map.Entry<Integer, Class<?>> exception : exceptions.entrySet()) {
    assertThatExceptionOfType(WebDriverException.class)
        .isThrownBy(() -> handler.throwIfResponseFailed(createResponse(exception.getKey()), 123))
        .satisfies(e -> {
          assertThat(e.getClass().getSimpleName()).isEqualTo(exception.getValue().getSimpleName());

          // all of the special invalid selector exceptions are just mapped to the generic invalid selector
          int expected = e instanceof InvalidSelectorException
                         ? ErrorCodes.INVALID_SELECTOR_ERROR : exception.getKey();
          assertThat(new ErrorCodes().toStatusCode(e)).isEqualTo(expected);
        });
  }
}