Java Code Examples for org.openqa.selenium.TakesScreenshot#getScreenshotAs()

The following examples show how to use org.openqa.selenium.TakesScreenshot#getScreenshotAs() . 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: ScreenshotUtil.java    From seleniumtestsframework with Apache License 2.0 6 votes vote down vote up
public static String captureEntirePageScreenshotToString(final WebDriver driver) {
    if (driver == null) {
        return "";
    }

    try {
        if (WebUIDriver.getWebUIDriver().getBrowser().equalsIgnoreCase(BrowserType.Android.getBrowserType())) {
            return null;
        }

        TakesScreenshot screenShot = (TakesScreenshot) driver;
        return screenShot.getScreenshotAs(OutputType.BASE64);
    } catch (Exception ex) {

        // Ignore all exceptions
        ex.printStackTrace();
    }

    return "";
}
 
Example 2
Source File: SeleniumHelper.java    From hsac-fitnesse-fixtures with Apache License 2.0 6 votes vote down vote up
/**
 * Takes screenshot of current page (as .png).
 * @param baseName name for file created (without extension),
 *                 if a file already exists with the supplied name an
 *                 '_index' will be added.
 * @return absolute path of file created.
 */
public String takeScreenshot(String baseName) {
    String result = null;

    WebDriver d = driver();

    if (!(d instanceof TakesScreenshot)) {
        d = new Augmenter().augment(d);
    }
    if (d instanceof TakesScreenshot) {
        TakesScreenshot ts = (TakesScreenshot) d;
        byte[] png = ts.getScreenshotAs(OutputType.BYTES);
        result = writeScreenshot(baseName, png);
    }
    return result;
}
 
Example 3
Source File: CucumberReportingExtension.java    From senbot with MIT License 6 votes vote down vote up
/**
 * Capture a selenium screenshot when a test fails and add it to the Cucumber generated report
 * if the scenario has accessed selenium in its lifetime
 * @throws InterruptedException 
 */
@After
public void afterScenario(Scenario scenario) throws InterruptedException {
    log.debug("Scenarion finished");
    ScenarioGlobals scenarioGlobals = getCucumberManager().getCurrentScenarioGlobals();
	TestEnvironment testNev = getSeleniumManager().getAssociatedTestEnvironment();
	if (testNev != null && scenarioGlobals != null) {
		boolean scenarioUsedSelenium = testNev.isWebDriverAccessedSince(scenarioGlobals.getScenarioStart());
		if (scenarioUsedSelenium) {
			if (scenario.isFailed()) {
				log.debug("Scenarion failed while using selenium, so capture screenshot");
				TakesScreenshot seleniumDriver = (TakesScreenshot) SenBotContext.getSeleniumDriver();
	byte[] screenshotAs = seleniumDriver.getScreenshotAs(OutputType.BYTES);
	scenario.embed(screenshotAs, "image/png");
			}
		}
	}
    getCucumberManager().stopNewScenario();
}
 
Example 4
Source File: TestWatcherRule.java    From movieapp-dialog with Apache License 2.0 5 votes vote down vote up
@Override
protected void failed(Throwable e, Description description) {
    TakesScreenshot takesScreenshot = (TakesScreenshot) browser;

    File scrFile = takesScreenshot.getScreenshotAs(OutputType.FILE);
    File destFile = getDestinationFile(description.getMethodName());
    try {
        FileUtils.copyFile(scrFile, destFile);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}
 
Example 5
Source File: CaptureScreenshotToString.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
protected String handleSeleneseCommand(WebDriver driver, String locator, String value) {
  if (driver instanceof TakesScreenshot) {
    TakesScreenshot tsDriver = (TakesScreenshot) driver;
    return tsDriver.getScreenshotAs(OutputType.BASE64);
  }
  throw new UnsupportedOperationException("WebDriver does not implement TakeScreenshot");
}
 
Example 6
Source File: Image4SearchLog.java    From phoenix.webui.framework with Apache License 2.0 4 votes vote down vote up
/**
 * 截图捕捉
 * @param ele
 * @throws IOException
 */
private void capture(Object ele, Throwable e) throws IOException
{
	if(ele == null)
	{
		return;
	}
	
	WebDriver driver = engine.getDriver();
	if(ele instanceof WebElement && driver instanceof TakesScreenshot)
	{
		TakesScreenshot shot = (TakesScreenshot) driver;
		
		File file = shot.getScreenshotAs(OutputType.FILE);
		BufferedImage bufImg = ImageIO.read(file);
		
		try
		{
			elementMark.mark((WebElement) ele, file);
		}
		catch(IOException ioEx)
		{
			ioEx.printStackTrace();
		}
		
		long currentTime =  System.currentTimeMillis();
		String fileName = null;
		if(e == null)
		{
			fileName = currentTime + ".png";
		}
		else
		{
			fileName = "ex_" + currentTime + ".png";
		}
		
		File elementSearchImageFile = new File(outputDir, fileName);
		try(OutputStream output = new FileOutputStream(elementSearchImageFile))
		{
			ImageIO.write(bufImg, "gif", output);
			elementSearchImageFileList.add(elementSearchImageFile);
			animatedGifEncoder.addFrame(bufImg);
		}
	}
}
 
Example 7
Source File: WebDriverScreenDiffer.java    From nomulus with Apache License 2.0 4 votes vote down vote up
private byte[] takeScreenshot() {
  checkArgument(webDriver instanceof TakesScreenshot);
  TakesScreenshot takesScreenshot = (TakesScreenshot) webDriver;
  return takesScreenshot.getScreenshotAs(OutputType.BYTES);
}
 
Example 8
Source File: RequiredActionsTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private void testBarcodeOtp() throws Exception {
    assumeFalse(driver instanceof HtmlUnitDriver); // HtmlUnit browser cannot take screenshots
    TakesScreenshot screenshotDriver = (TakesScreenshot) driver;
    QRCodeReader qrCodeReader = new QRCodeReader();

    initiateRequiredAction(otpSetupPage);

    otpSetupPage.localeDropdown().selectAndAssert(CUSTOM_LOCALE_NAME);

    otpSetupPage.clickManualMode();
    otpSetupPage.clickBarcodeMode();

    assertTrue(otpSetupPage.isBarcodePresent());
    assertFalse(otpSetupPage.isSecretKeyPresent());
    assertTrue(otpSetupPage.feedbackMessage().isWarning());
    assertEquals("You need to set up Mobile Authenticator to activate your account.", otpSetupPage.feedbackMessage().getText());

    // empty input
    otpSetupPage.submit();
    assertTrue(otpSetupPage.feedbackMessage().isError());
    assertEquals("Please specify authenticator code.", otpSetupPage.feedbackMessage().getText());

    // take a screenshot of the QR code
    byte[] screenshot = screenshotDriver.getScreenshotAs(OutputType.BYTES);
    BufferedImage screenshotImg = ImageIO.read(new ByteArrayInputStream(screenshot));
    BinaryBitmap screenshotBinaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(screenshotImg)));
    Result qrCode = qrCodeReader.decode(screenshotBinaryBitmap);

    // parse the QR code string
    Pattern qrUriPattern = Pattern.compile("^otpauth:\\/\\/(?<type>.+)\\/(?<realm>.+):(?<user>.+)\\?secret=(?<secret>.+)&digits=(?<digits>.+)&algorithm=(?<algorithm>.+)&issuer=(?<issuer>.+)&(?:period=(?<period>.+)|counter=(?<counter>.+))$");
    Matcher qrUriMatcher = qrUriPattern.matcher(qrCode.getText());
    assertTrue(qrUriMatcher.find());

    // extract data
    String type = qrUriMatcher.group("type");
    String realm = qrUriMatcher.group("realm");
    String user = qrUriMatcher.group("user");
    String secret = qrUriMatcher.group("secret");
    int digits = Integer.parseInt(qrUriMatcher.group("digits"));
    String algorithm = qrUriMatcher.group("algorithm");
    String issuer = qrUriMatcher.group("issuer");
    Integer period = type.equals(TOTP) ? Integer.parseInt(qrUriMatcher.group("period")) : null;
    Integer counter = type.equals(HOTP) ? Integer.parseInt(qrUriMatcher.group("counter")) : null;

    RealmRepresentation realmRep = testRealmResource().toRepresentation();
    String expectedRealmName = realmRep.getDisplayName() != null && !realmRep.getDisplayName().isEmpty() ? realmRep.getDisplayName() : realmRep.getRealm();

    // basic assertations
    assertEquals(QR_CODE, qrCode.getBarcodeFormat());
    assertEquals(expectedRealmName, realm);
    assertEquals(expectedRealmName, issuer);
    assertEquals(testUser.getUsername(), user);

    // the actual test
    testOtp(type, algorithm, digits, period, counter, secret);
}
 
Example 9
Source File: ScreenshotTaker.java    From webtester2-core with Apache License 2.0 3 votes vote down vote up
private File doTakeAndStoreScreenshot(File targetFolder, String fileNameWithoutSuffix) throws IOException {

        TakesScreenshot takesScreenshot = ( TakesScreenshot ) webDriver();
        File tempScreenshot = takesScreenshot.getScreenshotAs(OutputType.FILE);

        String fileName = fileNameWithoutSuffix + ".png";
        File screenshot = new File(targetFolder, fileName);

        FileUtils.moveFile(tempScreenshot, screenshot);

        log.debug("saved screenshot to file: {}", screenshot);
        fireEventIfEnabled(screenshot);
        return screenshot;

    }