Java Code Examples for org.openqa.selenium.OutputType

The following examples show how to use org.openqa.selenium.OutputType. These examples are extracted from open source projects. 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
/**
 * This function is used to capture screenshot and store it in directory
 * @param driver -Pass your WebDriver instance.
 * @param screenshotdir - Pass your screenshot directory
 * @return - Returns location where screenshot is stored.
 * @throws IOException -Exception is thrown during communcation errors.
    */
public static String captureScreenshot(WebDriver driver,
		String screenshotdir) throws IOException {
	String randomUUID = UUID.randomUUID().toString();
	String storeFileName = screenshotdir + File.separator
			+ getFileNameFromURL(driver.getCurrentUrl()) + "_"
			+ randomUUID + ".png";
	String[] screenshotdirsplit = screenshotdir.split(File.separator);
	String fileName = screenshotdirsplit[screenshotdirsplit.length - 1] + File.separator
			+ getFileNameFromURL(driver.getCurrentUrl()) + "_"
			+ randomUUID + ".png";
	File scrFile = ((TakesScreenshot) driver)
			.getScreenshotAs(OutputType.FILE);
	FileUtils.copyFile(scrFile, new File(storeFileName));
	return fileName;
}
 
Example 2
@Test
public void timeScreenshotsWithMjpegScreenshotBehavior() throws IOException, URISyntaxException, InterruptedException, ExecutionException, TimeoutException {

    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability("platformName", "iOS");
    caps.setCapability("platformVersion", "12.4");
    caps.setCapability("deviceName", "iPhone Xs");
    caps.setCapability("automationName", "XCUITest");
    caps.setCapability("app", IOS_APP);

    driver = new IOSDriver(new URL("http://0.0.0.0:4723/wd/hub"), caps);

    driver.startRecordingScreen(); // this is unnecessary for this test run, but included here to make this test identical to the next test

    long startTime = System.nanoTime();
    for (int i = 0; i < 100; i++) {
        driver.getScreenshotAs(OutputType.FILE);
    }
    long endTime = System.nanoTime();

    long msElapsed = (endTime - startTime) / 1000000;
    System.out.println("100 screenshots using mjpeg: " + msElapsed + "ms. On average " + msElapsed/100 + "ms per screenshot");
    // about 436ms per screenshot on my machine
}
 
Example 3
Source Project: appiumpro   Source File: Edition088_Debugging_Aids.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void failed(Throwable e, Description desc) {
    // print appium logs
    LogEntries entries = driver.manage().logs().get("server");
    System.out.println("======== APPIUM SERVER LOGS ========");
    for (LogEntry entry : entries) {
        System.out.println(new Date(entry.getTimestamp()) + " " + entry.getMessage());
    }
    System.out.println("================");

    // print source
    System.out.println("======== APP SOURCE ========");
    System.out.println(driver.getPageSource());
    System.out.println("================");

    // save screenshot
    String testName = desc.getMethodName().replaceAll("[^a-zA-Z0-9-_\\.]", "_");
    File screenData = driver.getScreenshotAs(OutputType.FILE);
    try {
        File screenFile = new File(SCREEN_DIR + "/" + testName + ".png");
        FileUtils.copyFile(screenData, screenFile);
        System.out.println("======== SCREENSHOT ========");
        System.out.println(screenFile.getAbsolutePath());
        System.out.println("================");
    } catch (IOException ign) {}
}
 
Example 4
/**
 * �����Խ�����н�ͼ
 * @param driver ����
 * @param imgname ͼƬ����
 */
public static void webScreenShot(WebDriver driver, String imgname) {
	String relativelyPath = System.getProperty("user.dir");
	String pngpath=relativelyPath +File.separator+ "log"+File.separator+"ScreenShot" +File.separator+ imgname + ".png";

	// ��Զ��ϵͳ���н�ͼ
	driver = new Augmenter().augment(driver);
	File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
	try {
		FileUtils.copyFile(scrFile, new File(pngpath));
	} catch (IOException e) {
		LogUtil.APP.error("��ͼ����ʧ�ܣ��׳��쳣��鿴��־...", e);
	}
	scrFile.deleteOnExit();
	LogUtil.APP
			.info("�ѶԵ�ǰ������н�ͼ��������ͨ������ִ�н������־��ϸ�鿴��Ҳ����ǰ���ͻ����ϲ鿴...��{}��",pngpath);
}
 
Example 5
Source Project: NetDiscovery   Source File: SeleniumUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 截取某个区域的截图
 * @param driver
 * @param x
 * @param y
 * @param width
 * @param height
 * @param pathName
 */
public static void taskScreenShot(WebDriver driver,int x,int y,int width,int height,String pathName) {

    //指定了OutputType.FILE做为参数传递给getScreenshotAs()方法,其含义是将截取的屏幕以文件形式返回。
    File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    //利用IOUtils工具类的copyFile()方法保存getScreenshotAs()返回的文件对象。

    try {
        //矩形图像对象
        Rectangle rect = new Rectangle(width, height);
        BufferedImage img = ImageIO.read(srcFile);
        BufferedImage dest = img.getSubimage(x, y, rect.width, rect.height);
        ImageIO.write(dest, "png", srcFile);
        IOUtils.copyFile(srcFile, new File(pathName));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 6
Source Project: seleniumtestsframework   Source File: ScreenshotUtil.java    License: 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 7
Source Project: test-samples   Source File: BaseTest.java    License: Apache License 2.0 6 votes vote down vote up
protected File takeScreenshot(String screenshotName) {
    String fullFileName = System.getProperty("user.dir") + "/screenshots/" + screenshotName + ".png";
    logger.debug("Taking screenshot...");
    File scrFile = ((TakesScreenshot) wd).getScreenshotAs(OutputType.FILE);

    try {
        File testScreenshot = new File(fullFileName);
        FileUtils.copyFile(scrFile, testScreenshot);
        logger.debug("Screenshot stored to " + testScreenshot.getAbsolutePath());

        return testScreenshot;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 8
/**
 * Screenshots will be saved using either the value of (#REMOTE_DRIVER_SCREENSHOT_FILENAME or if none, testName.testNameMethod)
 * appended with a date time stamp and the png file extension.
 *
 * @see WebDriverUtils#getDateTimeStampFormatted
 *
 * @param driver to use, if not of type TakesScreenshot no screenshot will be taken
 * @param testName to save test as, unless #REMOTE_DRIVER_SCREENSHOT_FILENAME is set
 * @param testMethodName to save test as, unless #REMOTE_DRIVER_SCREENSHOT_FILENAME is set
 * @throws IOException
 */
public void screenshot(WebDriver driver, String testName, String testMethodName, String screenName) throws IOException {
    if (driver instanceof TakesScreenshot) {

        if (!"".equals(screenName)) {
            screenName = "-" + screenName;
        }

        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        // It would be nice to make the screenshot file name much more configurable.
        String screenshotFileName = WebDriverUtils.getDateTimeStampFormatted() + "-"
                + System.getProperty(REMOTE_DRIVER_SCREENSHOT_FILENAME, testName + "." + testMethodName)
                + screenName + ".png";
        FileUtils.copyFile(scrFile, new File(System.getProperty(REMOTE_DRIVER_SCREENSHOT_DIR, ".")
                + File.separator, screenshotFileName));
        String archiveUrl = System.getProperty(REMOTE_DRIVER_SCREENSHOT_ARCHIVE_URL, "");
        WebDriverUtils.jGrowl(driver, "Screenshot", false, archiveUrl + screenshotFileName);
    }
}
 
Example 9
Source Project: sahagin-java   Source File: FluentLeniumAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public byte[] captureScreen() {
    if (fluent == null) {
        return null;
    }
    WebDriver driver = fluent.getDriver();
    if (driver == null) {
        return null;
    }
    if (!(driver instanceof TakesScreenshot)) {
        return null;
    }
    try {
        return ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.BYTES);
    } catch (NoSuchSessionException e) {
        // just do nothing if WebDriver instance is in invalid state
        return null;
    }
}
 
Example 10
Source Project: twse-captcha-solver-dl4j   Source File: Downloader.java    License: MIT License 6 votes vote down vote up
private void downloadCaptcha(WebElement element) {
	// take all webpage as screenshot
	File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
	try {
		// read the full screenshot
		BufferedImage fimg = ImageIO.read(screenshot);
		// get element location
		org.openqa.selenium.Point p = element.getLocation();
		// find element size
		org.openqa.selenium.Dimension size = element.getSize();
		// corp the captcha image
		BufferedImage croppedImage = fimg.getSubimage(p.getX(), p.getY(), size.getWidth(),
				size.getHeight());
		// save the capthca image
		File f = new File(this.saveDir + File.separator + randomImgName());
		ImageIO.write(croppedImage, "PNG", f);
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		// delete tmp file
		screenshot.delete();
	}
}
 
Example 11
public File createScreenShot() {
    try {
        if (driver == null) {
            System.err.println("Report Driver[" + runContext.BrowserName + "]  is not initialized");
        } else if (isAlive()) {
            if (alertPresent()) {
                System.err.println("Couldn't take ScreenShot Alert Present in the page");
                return ((TakesScreenshot) (new EmptyDriver())).getScreenshotAs(OutputType.FILE);
            } else if (driver instanceof MobileDriver || driver instanceof ExtendedHtmlUnitDriver
                    || driver instanceof EmptyDriver) {
                return ((TakesScreenshot) (driver)).getScreenshotAs(OutputType.FILE);
            } else {
                return createNewScreenshot();
            }
        }
    } catch (DriverClosedException ex) {
        System.err.println("Couldn't take ScreenShot Driver is closed or connection is lost with driver");
    }
    return null;
}
 
Example 12
Source Project: Selenium-Foundation   Source File: ScreenshotUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Produce a screenshot from the specified driver.
 * 
 * @param optDriver optional web driver object
 * @param reason impetus for capture request; may be 'null'
 * @param logger SLF4J logger object; may be 'null'
 * @return screenshot artifact; if capture fails, an empty byte array is returned
 */
public static byte[] getArtifact(
                final Optional<WebDriver> optDriver, final Throwable reason, final Logger logger) { //NOSONAR
    
    if (canGetArtifact(optDriver, logger)) {
        try {
            WebDriver driver = optDriver.get();
            return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
        } catch (WebDriverException e) {
            if (e.getCause() instanceof ClassCastException) {
                return proxyArtifact();
            } else if (logger != null) {
                logger.warn("The driver is capable of taking a screenshot, but it failed.", e);
            }
        }
    }
    return new byte[0];
}
 
Example 13
Source Project: edx-app-android   Source File: NativeAppDriver.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Captures the screenshot
 */
public void captureScreenshot() {
	String outputPath = PropertyLoader.loadProperty("output.path").get();

	String screenShotPath = outputPath + "/ScreenShots/";
	String fileName = generateFileName() + ".jpg";
	// Take the screenshot
	File scrFile = ((TakesScreenshot) (this.appiumDriver))
			.getScreenshotAs(OutputType.FILE);
	try {
		FileUtils.copyFile(scrFile, new File(screenShotPath + fileName));
		Reporter.log("<br> Module name: " + getCurrentTestClassName()
				+ "<br>");
		Reporter.log(" Refer to <a href=\"ScreenShots/" + fileName
				+ "\" target = \"_blank\"><img src=\"ScreenShots/"
				+ fileName + "\" width=\"50\" height=\"50\"></a><br>");
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 14
@Override
public void takeScreenShot() throws IOException {

	File scrFile = null;
	try {
		scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
	} catch (Exception e) {
		WEBDRIVER_LOG.error("Failed to generate screenshot, problem with driver: {} ", e.getMessage());
	}

	if (scrFile != null) {
		File file = createScreenshotFile();
		FileUtils.copyFile(scrFile, file);

		reportLogScreenshot(file);
	}
}
 
Example 15
Source Project: neodymium-library   Source File: VisualAssertion.java    License: MIT License 6 votes vote down vote up
/**
 * Takes a screenshot if the underlying web driver instance is capable of doing it. Fails with a message only in
 * case the webdriver cannot take screenshots. Avoids issue when certain drivers are used.
 * 
 * @param webDriver
 *            the web driver to use
 * @return {@link BufferedImage} if the webdriver supports taking screenshots, null otherwise
 * @throws RuntimeException
 *             In case the files cannot be written
 */
private BufferedImage takeScreenshot(final WebDriver webDriver)
{
    if (webDriver instanceof TakesScreenshot)
    {
        final byte[] bytes = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.BYTES);
        try
        {
            return ImageIO.read(new ByteArrayInputStream(bytes));
        }
        catch (final IOException e)
        {
            throw new RuntimeException(e);
        }
    }
    else
    {
        return null;
    }
}
 
Example 16
Source Project: java-client   Source File: ImagesComparisonTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void verifyOccurrencesLookup() {
    byte[] screenshot = Base64.encodeBase64(driver.getScreenshotAs(OutputType.BYTES));
    OccurrenceMatchingResult result = driver
            .findImageOccurrence(screenshot, screenshot, new OccurrenceMatchingOptions()
                    .withEnabledVisualization());
    assertThat(result.getVisualization().length, is(greaterThan(0)));
    assertNotNull(result.getRect());
}
 
Example 17
Source Project: webdsl   Source File: Test.java    License: Apache License 2.0 5 votes vote down vote up
public static void takeScreenshot(WebDriver driver){
  	File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
  	try {
  		File f = new File("screenshot-"+(screenshotCounter++)+"-"+new Date()+".png");
	FileUtils.copyFile(scrFile, f);
	org.webdsl.logging.Logger.info("screenshot saved "+f.getAbsolutePath());
} catch (IOException e) {
	e.printStackTrace();
}
  }
 
Example 18
Source Project: vividus   Source File: DelegatingWebElementTests.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
void testGetScreenshotAs()
{
    OutputType<String> target = Mockito.mock(OutputType.class);
    String output = "output";
    when(webElement.getScreenshotAs(target)).thenReturn(output);
    assertEquals(output, delegatingWebElement.getScreenshotAs(target));
}
 
Example 19
Source Project: vividus   Source File: DelegatingWebDriverTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testGetScreenshotAs()
{
    WebDriver takesScreenshotDriver = Mockito.mock(WebDriver.class,
            withSettings().extraInterfaces(TakesScreenshot.class));
    File file = Mockito.mock(File.class);
    when(((TakesScreenshot) takesScreenshotDriver).getScreenshotAs(OutputType.FILE)).thenReturn(file);
    assertEquals(file, new DelegatingWebDriver(takesScreenshotDriver).getScreenshotAs(OutputType.FILE));
}
 
Example 20
Source Project: vividus   Source File: DelegatingWebDriverTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testGetScreenshotAsUnsupportedOperationException()
{
    UnsupportedOperationException exception = assertThrows(UnsupportedOperationException.class,
        () -> delegatingWebDriver.getScreenshotAs(OutputType.FILE));
    assertEquals("Underlying driver instance does not support taking screenshots", exception.getMessage());
}
 
Example 21
Source Project: appiumpro   Source File: Edition098_Visual_Testing_1.java    License: Apache License 2.0 5 votes vote down vote up
private void doVisualCheck(String checkName) throws Exception {
    String baselineFilename = VALIDATION_PATH + "/" + BASELINE + checkName + ".png";
    File baselineImg = new File(baselineFilename);

    // If no baseline image exists for this check, we should create a baseline image
    if (!baselineImg.exists()) {
        System.out.println(String.format("No baseline found for '%s' check; capturing baseline instead of checking", checkName));
        File newBaseline = driver.getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(newBaseline, new File(baselineFilename));
        return;
    }

    // Otherwise, if we found a baseline, get the image similarity from Appium. In getting the similarity,
    // we also turn on visualization so we can see what went wrong if something did.
    SimilarityMatchingOptions opts = new SimilarityMatchingOptions();
    opts.withEnabledVisualization();
    SimilarityMatchingResult res = driver.getImagesSimilarity(baselineImg, driver.getScreenshotAs(OutputType.FILE), opts);

    // If the similarity is not high enough, consider the check to have failed
    if (res.getScore() < MATCH_THRESHOLD) {
        File failViz = new File(VALIDATION_PATH + "/FAIL_" + checkName + ".png");
        res.storeVisualization(failViz);
        throw new Exception(
            String.format("Visual check of '%s' failed; similarity match was only %f, and below the threshold of %f. Visualization written to %s.",
                checkName, res.getScore(), MATCH_THRESHOLD, failViz.getAbsolutePath()));
    }

    // Otherwise, it passed!
    System.out.println(String.format("Visual check of '%s' passed; similarity match was %f",
        checkName, res.getScore()));
}
 
Example 22
@Test
public void testScreenshots() throws Exception {
    Thread.sleep(2000);
    String desktop = System.getenv("HOME") + "/Desktop";
    driver.rotate(ScreenOrientation.LANDSCAPE);
    File regularScreenshot = driver.getScreenshotAs(OutputType.FILE);
    driver.setSetting("screenshotOrientation", "landscapeRight");
    File adjustedScreenshot = driver.getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(regularScreenshot, new File(desktop + "/screen1.png"));
    FileUtils.copyFile(adjustedScreenshot, new File(desktop + "/screen2.png"));
}
 
Example 23
Source Project: movieapp-dialog   Source File: TestWatcherRule.java    License: 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 24
Source Project: java-client   Source File: ImagesComparisonTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void verifyOccurrencesSearch() {
    byte[] screenshot = Base64.encodeBase64(driver.getScreenshotAs(OutputType.BYTES));
    OccurrenceMatchingResult result = driver
            .findImageOccurrence(screenshot, screenshot, new OccurrenceMatchingOptions()
                    .withEnabledVisualization());
    assertThat(result.getVisualization().length, is(greaterThan(0)));
    assertNotNull(result.getRect());
}
 
Example 25
Source Project: test-samples   Source File: AndroidSample.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void failed(Throwable e, Description description) {
    String fullFileName = System.getProperty("user.dir") + "/" + System.getProperty("SCREENSHOT_FOLDER") + description.getMethodName() + "_failure.png";
    try {
        File scrFile = driver.getScreenshotAs(OutputType.FILE);
        File testScreenshot = new File(fullFileName);
        FileUtils.copyFile(scrFile, testScreenshot);
        logger.info("Screenshot stored to {}", testScreenshot.getAbsolutePath());
        logger.info("PAGE SOURCE:");
        logger.info(driver.getPageSource());
    } catch (IOException e2) {
        e2.printStackTrace();
    }
}
 
Example 26
private void writeScreenshotToFile(WebDriver driver, File screenshot) {
    try {
        FileOutputStream screenshotStream = new FileOutputStream(screenshot);
        screenshotStream.write(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES));
        screenshotStream.close();
    } catch (IOException unableToWriteScreenshot) {
        System.err.println("Unable to write " + screenshot.getAbsolutePath());
        unableToWriteScreenshot.printStackTrace();
    }
}
 
Example 27
private void writeScreenshotToFile(WebDriver driver, File screenshot) {
    try {
        FileOutputStream screenshotStream = new FileOutputStream(screenshot);
        screenshotStream.write(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES));
        screenshotStream.close();
    } catch (IOException unableToWriteScreenshot) {
        System.err.println("Unable to write " + screenshot.getAbsolutePath());
        unableToWriteScreenshot.printStackTrace();
    }
}
 
Example 28
private void writeScreenshotToFile(WebDriver driver, File screenshot) {
    try {
        FileOutputStream screenshotStream = new FileOutputStream(screenshot);
        screenshotStream.write(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES));
        screenshotStream.close();
    } catch (IOException unableToWriteScreenshot) {
        System.err.println("Unable to write " + screenshot.getAbsolutePath());
        unableToWriteScreenshot.printStackTrace();
    }
}
 
Example 29
Source Project: JGiven   Source File: Html5AppTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Issue( "#274" )
public void a_thumbnail_is_shown_for_image_attachments() throws IOException {

    String screenshot = ( (TakesScreenshot) webDriver ).getScreenshotAs( OutputType.BASE64 );

    given().a_report_model()
        .and().step_$_of_scenario_$_has_an_image_attachment_$( 1, 1, screenshot );
    jsonReports
        .and().the_report_exist_as_JSON_file();
    whenReport.when().the_HTML_Report_Generator_is_executed();
    when().the_page_of_scenario_$_is_opened( 1 );
    then().an_element_with_a_$_class_exists( "jgiven-html-thumbnail" )
        .and().the_image_is_loaded();
}
 
Example 30
Source Project: hifive-pitalium   Source File: PtlWebDriver.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * スクリーンショットを撮影し、{@link BufferedImage}として取得します。
 *
 * @return 撮影したスクリーンショット
 */
protected BufferedImage getScreenshotAsBufferedImage() {
	try {
		LOG.debug("[getScreenshot start]");
		byte[] data = getScreenshotAs(OutputType.BYTES);
		LOG.debug("[getScreenshot finished]");
		LOG.debug("[ImageIO.read start]");
		BufferedImage image = ImageIO.read(new ByteArrayInputStream(data));
		LOG.debug("[ImageIO.read finished]");
		return image;
	} catch (IOException e) {
		throw new TestRuntimeException("Screenshot capture error", e);
	}
}