Java Code Examples for org.openqa.selenium.TakesScreenshot

The following are top voted examples for showing how to use org.openqa.selenium.TakesScreenshot. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: POM_HYBRID_FRAMEOWRK   File: ReportManager.java   Source Code and License 8 votes vote down vote up
private static String captureScreenshot(WebDriver driver, String screenshotPath, String ScreenshotName) {

		String destinationPath = null;
		try {
			File destFolder = new File(screenshotPath);
			
			destinationPath = destFolder.getCanonicalPath() + "/" + ScreenshotName + ".png";
		
			// Cast webdriver to Screenshot
			TakesScreenshot screenshot = (TakesScreenshot) driver;

			File sourceFile = screenshot.getScreenshotAs(OutputType.FILE);

			FileUtils.copyFile(sourceFile, new File(destinationPath));

		} catch (Exception e) {
			System.out.println("Error capturing screenshot...\n" + e.getMessage());
			e.printStackTrace();
		}
		return destinationPath;
	}
 
Example 2
Project: marathonv5   File: JavaDriverTest.java   Source Code and License 7 votes vote down vote up
public void screenshot() throws Throwable {
    try {
        driver = new JavaDriver();
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override public void run() {
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
        if (driver instanceof TakesScreenshot) {
            Thread.sleep(1000);
            File screenshotAs = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            System.out.println(screenshotAs.getAbsolutePath());
            Thread.sleep(20000);
        }
    } finally {
        JavaElementFactory.reset();
    }
}
 
Example 3
Project: zucchini   File: ScreenshotHook.java   Source Code and License 7 votes vote down vote up
public static void createScreenshot(String fileName) {

		if (SeleniumDriver.getInstance() instanceof TakesScreenshot) {

			File fileSrc = ((TakesScreenshot) SeleniumDriver.getInstance()).getScreenshotAs(OutputType.FILE);

			try {
				File destFile = new File(String.format(SCREENSHOTS_FORMAT, fileName));
				FileUtils.copyFile(fileSrc, destFile);
				LOG.info("[Screenshot] " + destFile.getAbsolutePath());
			} catch (IOException e) {
				;
			}
		}

	}
 
Example 4
Project: Habanero   File: ScreenShotHook.java   Source Code and License 7 votes vote down vote up
/**
 * <p>
 * Takes screen-shot if the scenario fails
 * </p>
 *
 * @param scenario will be the individual scenario's within the Feature files
 * @throws InterruptedException Exception thrown if there is an interuption within the JVM
 */
@After()
public void afterTest(Scenario scenario) throws InterruptedException {
    LOG.info("Taking screenshot IF Test Failed");
    System.out.println("Taking screenshot IF Test Failed (sysOut)");
    if (scenario.isFailed()) {
        try {
            System.out.println("Scenario FAILED... screen shot taken");
            scenario.write(getDriver().getCurrentUrl());
            byte[] screenShot = ((TakesScreenshot) getDriver()).getScreenshotAs(OutputType.BYTES);
            scenario.embed(screenShot, "image/png");
        } catch (WebDriverException e) {
            LOG.error(e.getMessage());
        }
    }
}
 
Example 5
Project: XPathBuilder   File: TestBase.java   Source Code and License 7 votes vote down vote up
@AfterMethod
public void setScreenshot(ITestResult result) {
  if (!result.isSuccess()) {
    try {
      WebDriver returned = new Augmenter().augment(webDriver);
      if (returned != null) {
        File f = ((TakesScreenshot) returned).getScreenshotAs(OutputType.FILE);
        try {
          FileUtils.copyFile(f,
              new File(SCREENSHOT_FOLDER + result.getName() + SCREENSHOT_FORMAT));
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    } catch (ScreenshotException se) {
      se.printStackTrace();
    }
  }
}
 
Example 6
Project: bdd-test-automation-for-mobile   File: SetupTeardownSteps.java   Source Code and License 7 votes vote down vote up
@After
public void tearDown(Scenario scenario) {
    if (scenario.isFailed()) {
        try {
            logger.info("Test failed, taking screenshot");
            byte[] screenshot = ((TakesScreenshot) new Augmenter().augment(getAppiumDriver()))
                    .getScreenshotAs(OutputType.BYTES);
            scenario.embed(screenshot, "image/png");
        }
        catch (WebDriverException wde) {
            System.err.println(wde.getMessage());
        }
        catch (ClassCastException cce) {
            cce.printStackTrace();
        }
    }
    application.tearDown();
}
 
Example 7
Project: cucumber-framework-java   File: StartingSteps.java   Source Code and License 6 votes vote down vote up
@After
public void afterScenario( Scenario scenario ) throws Exception
{
    try
    {
        attachLog();

        if( scenario.isFailed() )
        {
            try
            {
                scenario.write( "Current Page URL is " + getDriver().getCurrentUrl() );
                byte[] screenshot;
                try
                {
                    screenshot = ( ( TakesScreenshot ) getDriver() ).getScreenshotAs( OutputType.BYTES );
                } catch( ClassCastException weNeedToAugmentOurDriverObject )
                {
                    screenshot = ( ( TakesScreenshot ) new Augmenter().augment( getDriver() ) ).getScreenshotAs( OutputType.BYTES );
                }
                String relativeScrnShotPath = takeScreenshot().substring(takeScreenshot().indexOf("screenshots"));
                Reporter.addScreenCaptureFromPath(relativeScrnShotPath, getDriver().getCurrentUrl());
            } catch( WebDriverException somePlatformsDontSupportScreenshots )
            {
                System.err.println( somePlatformsDontSupportScreenshots.getMessage() );
            }
        }
    } finally
    {
        closeDriverObjects();
    }
}
 
Example 8
Project: Gospy   File: SeleniumDemo.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    String phantomJsPath = "D:/Program Files/PhantomJS/phantomjs-2.1.1-windows/bin/phantomjs.exe";
    String savePath = "D:/screenshot.png";
    Gospy.custom()
            .setScheduler(Schedulers.VerifiableScheduler.custom()
                    .setPendingTimeInSeconds(60).build())
            .addFetcher(Fetchers.TransparentFetcher.getDefault())
            .addProcessor(Processors.PhantomJSProcessor.custom()
                    .setPhantomJsBinaryPath(phantomJsPath)
                    .setWebDriverExecutor((page, webDriver) -> {
                        TakesScreenshot screenshot = (TakesScreenshot) webDriver;
                        File src = screenshot.getScreenshotAs(OutputType.FILE);
                        FileUtils.copyFile(src, new File(savePath));
                        System.out.println("screenshot has been saved to " + savePath);
                        return new Result<>();
                    })
                    .build())
            .build().addTask("phantomjs://http://www.zhihu.com").start();
}
 
Example 9
Project: vaadin-016-helloworld-14   File: WebDriverFunctions.java   Source Code and License 6 votes vote down vote up
static Consumer<WebDriver> takeScreenShot() {
    return (webDriver) -> {
        //take Screenshot
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            outputStream.write(((TakesScreenshot) webDriver).getScreenshotAs(OutputType.BYTES));
            //write to target/screenshot-[timestamp].jpg
            final FileOutputStream out = new FileOutputStream("target/screenshot-" + LocalDateTime.now() + ".png");
            out.write(outputStream.toByteArray());
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    };
}
 
Example 10
Project: Cognizant-Intelligent-Test-Scripter   File: SeleniumDriver.java   Source Code and License 6 votes vote down vote up
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 11
Project: willtest   File: ScreenshotRule.java   Source Code and License 6 votes vote down vote up
@Override
protected void onError(Description description, Throwable testFailure) throws Throwable {
    super.onError(description, testFailure);
    if(Objects.nonNull(screenshotProvider)) {
        WebDriver webDriver = seleniumProvider.getWebDriver();
        if (webDriver instanceof TakesScreenshot) {
            BufferedImage screenshot = screenshotProvider.takeScreenshot(webDriver);

            File destFile = TestReportFile.forTest(description).withPostix(".png").build().getFile();
            ImageIO.write(screenshot, "PNG", destFile);

            LOGGER.info("Saved screenshot as " + destFile.getAbsolutePath());
        } else {
            testFailure.addSuppressed(
                    new RuntimeException(
                            "Could not take screenshot, since webdriver is not a " +
                                    TakesScreenshot.class.getName() + " instance as expected. Actual class is " +
                                    webDriver.getClass().getName()));
        }
    } else {
        LOGGER.info("Due to SreenshotProvider is not specified, no screenshot is taken");
    }
}
 
Example 12
Project: Actitime-Framework   File: ExtentReport.java   Source Code and License 6 votes vote down vote up
/**
 * This method captures the screenshot and places it in the execution report
 **/
public static void captureAndDisplayScreenShot(WebDriver ldriver,
		ExtentTest eTest) {
	Date dtnow2 = new Date();
	String strStartDate2 = dtnow2.toString().replace(":", "_");
	String strDateStamp2 = strStartDate2.replace(" ", "_");
	File src = ((TakesScreenshot) ldriver).getScreenshotAs(OutputType.FILE);
	try {
		String screenshotPath = dirPath + "_" + strDateStamp2 + ".png";
		FileUtils.copyFile(src, new File(screenshotPath));
		eTest.addScreenCaptureFromPath(screenshotPath);
	} catch (IOException e) {
		System.out.println(e.getMessage());
	}
}
 
Example 13
Project: Actitime-Framework   File: ReportNGReport.java   Source Code and License 6 votes vote down vote up
/**
 * This method captures a screenshot
 **/
public static void captureScreenshot(WebDriver driver, String screenshotName) {
	try {
		TakesScreenshot ts = (TakesScreenshot) driver;
		File source = ts.getScreenshotAs(OutputType.FILE);
		FileUtils.copyFile(source, new File(dirPath + "/ " + screenshotName
				+ "_" + strDateStamp

				+ ".png"));
		String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";
		System.setProperty(ESCAPE_PROPERTY, "false");
		URL path = new File(dirPath + "/ " + screenshotName + "_"
				+ strDateStamp + ".png").toURI().toURL();
		String test = "<a href=" + path + "> click to open screenshot of "
				+ screenshotName + "</a>";
		Reporter.log(screenshotName + test + "<br>");
		Reporter.log("<br>");
	}

	catch (Exception e) {
		System.out.println("Exception while taking screenshot "
				+ e.getMessage());
	}
}
 
Example 14
Project: mobileAutomation   File: Driver.java   Source Code and License 6 votes vote down vote up
/**
 * Save screenshot to file.
 * 
 * @param fileName
 */
public static void saveScreenShot(String fileName){
	File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
	try {

		Path destPath = Paths.get(
				Logger.getLogger().getLogDirPath().toString() 
				+ "/" + fileName);

		FileUtils.copyFile(scrFile, new File(destPath.toString()));
		logger.log("Saved screenshot: " + destPath.toString());

	} catch (IOException e) {
		logger.logLines(e.getStackTrace().toString());
		logger.log("Failed to save screenshot!");
		System.out.println();
	}
}
 
Example 15
Project: crawler   File: WindowUtil.java   Source Code and License 6 votes vote down vote up
public static void taskScreenShot(WebDriver driver,File saveFile){
	if(saveFile.exists()){
		saveFile.delete();
	}
	byte[] src=((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);//.FILE);linux下非root用户,java创建临时文件存在问题
	log.info("截图文件字节长度"+src.length);
	try {
		FileUtils.writeByteArrayToFile(saveFile, src);
	} catch (IOException e) {
		e.printStackTrace();
		log.error("截图写入失败",e);
	}
}
 
Example 16
Project: GeoCrawler   File: HttpWebClient.java   Source Code and License 6 votes vote down vote up
private static void takeScreenshot(WebDriver driver, Configuration conf) {
  try {
    String url = driver.getCurrentUrl();
    File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    LOG.debug("In-memory screenshot taken of: {}", url);
    FileSystem fs = FileSystem.get(conf);
    Path screenshotPath = new Path(conf.get("selenium.screenshot.location") + "/" + srcFile.getName());
    if (screenshotPath != null) {
      OutputStream os = null;
      if (!fs.exists(screenshotPath)) {
        LOG.debug("No existing screenshot already exists... creating new file at {} {}.", screenshotPath, srcFile.getName());
        os = fs.create(screenshotPath);
      }
      InputStream is = new BufferedInputStream(new FileInputStream(srcFile));
      IOUtils.copyBytes(is, os, conf);
      LOG.debug("Screenshot for {} successfully saved to: {} {}", url, screenshotPath, srcFile.getName()); 
    } else {
      LOG.warn("Screenshot for {} not saved to HDFS (subsequently disgarded) as value for "
          + "'selenium.screenshot.location' is absent from nutch-site.xml.", url);
    }
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 17
Project: xlt-visual-assert   File: VisualAssertion.java   Source Code and 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 18
Project: cashion   File: Snapshot.java   Source Code and License 6 votes vote down vote up
public static void snapshot(TakesScreenshot drivername, String filename)
{
    // this method will take screen shot ,require two parameters ,one is driver name, another is file name
    
    
  File scrFile = drivername.getScreenshotAs(OutputType.FILE);
      // Now you can do whatever you need to do with it, for example copy somewhere
      try {
          System.out.println("save snapshot path is:"+filename);
          FileUtils.copyFile(scrFile, new File(filename));
      } catch (IOException e) {
          // TODO Auto-generated catch block
          System.out.println("Can't save screenshot");
          e.printStackTrace();
      } 
      finally
      {
          System.out.println("screen shot finished");
      }
}
 
Example 19
Project: SeleniumCucumber   File: GenericHelper.java   Source Code and License 6 votes vote down vote up
public String takeScreenShot(String name) throws IOException {

		if (driver instanceof HtmlUnitDriver) {
			oLog.fatal("HtmlUnitDriver Cannot take the ScreenShot");
			return "";
		}

		File destDir = new File(ResourceHelper.getResourcePath("screenshots/")
				+ DateTimeHelper.getCurrentDate());
		if (!destDir.exists())
			destDir.mkdir();

		File destPath = new File(destDir.getAbsolutePath()
				+ System.getProperty("file.separator") + name + ".jpg");
		try {
			FileUtils
					.copyFile(((TakesScreenshot) driver)
							.getScreenshotAs(OutputType.FILE), destPath);
		} catch (IOException e) {
			oLog.error(e);
			throw e;
		}
		oLog.info(destPath.getAbsolutePath());
		return destPath.getAbsolutePath();
	}
 
Example 20
Project: domui   File: DefaultScreenshotHelper.java   Source Code and License 6 votes vote down vote up
@Override public boolean createScreenshot(WebDriverConnector wd, File screenshotFile) throws Exception {
	WebDriver ad = wd.driver();

	if(ad instanceof RemoteWebDriver && wd.getDriverType() == WebDriverType.REMOTE) {
		//for remote drivers we need to do augmenter thingy, for local we must not
		ad = new Augmenter().augment(ad);
	}

	if(ad instanceof TakesScreenshot) {
		File f = ((TakesScreenshot) ad).getScreenshotAs(OutputType.FILE);
		try {
			FileTool.copyFile(screenshotFile, f);
		} finally {
			FileTool.closeAll(f);
		}
		return true;
	}
	return false;
}
 
Example 21
Project: riot-automated-tests   File: TestUtilities.java   Source Code and License 6 votes vote down vote up
public void captureImage(String imgUrl,MobileElement element) throws IOException{
	new File(imgUrl).delete();
	File screen = ((TakesScreenshot) appiumFactory.getAndroidDriver2())
			.getScreenshotAs(OutputType.FILE);
	Point point = element.getLocation();

	//get element dimension
	int width = element.getSize().getWidth();
	int height = element.getSize().getHeight();

	BufferedImage img = ImageIO.read(screen);
	BufferedImage dest = img.getSubimage(point.getX(), point.getY(), width,
			height);
	ImageIO.write(dest, "png", screen);
	File file = new File(imgUrl);
	FileUtils.copyFile(screen, file);
}
 
Example 22
Project: riot-automated-tests   File: RiotMiscTests.java   Source Code and License 6 votes vote down vote up
@Test(groups="1driver_android")
public void takeScreenShot() throws Exception{
	// Set folder name to store screenshots.
	destDir = "screenshots";
	// Capture screenshot.
	File scrFile = ((TakesScreenshot) appiumFactory.getAndroidDriver1()).getScreenshotAs(OutputType.FILE);
	// Set date format to set It as screenshot file name.
	dateFormat = new SimpleDateFormat("dd-MMM-yyyy__hh_mm_ssaa");
	// Create folder under project with name "screenshots" provided to destDir.
	new File(destDir).mkdirs();
	// Set file name using current date time.
	String destFile = dateFormat.format(new Date()) + ".png";

	try {
		FileUtils.copyFile(scrFile, new File(destDir + "/" + destFile));
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 23
Project: alimama   File: SeleniumUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 鎴浘
 * 
 * @param driver
 * @param url
 * @param filePath
 * @return
 */
public static String capture(WebDriver driver, String url, String filePath) {
	if (driver == null) {
		return null;
	}
	if (!url.startsWith("http:") && !url.startsWith("https:")) {
		return null;
	}
	if (StringUtils.isBlank(filePath)) {
		return null;
	}
	try {
		driver.get(url);
		WebDriver augmentedDriver = new Augmenter().augment(driver);
		File screenshot = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
		File file = new File(filePath);
		FileUtils.copyFile(screenshot, file);
		logger.info("capture success!");
	} catch (IOException e) {
		logger.error("browser capture is error!", e);
		filePath = null;
		throw new RuntimeException(e);
	}
	return filePath;
}
 
Example 24
Project: alimama   File: SeleniumUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 鎴浘
 * 
 * @param driver
 * @param url
 * @param filePath
 * @return
 */
public static String capture(WebDriver driver, String url, String filePath) {
	if (driver == null) {
		return null;
	}
	if (!url.startsWith("http:") && !url.startsWith("https:")) {
		return null;
	}
	if (StringUtils.isBlank(filePath)) {
		return null;
	}
	try {
		driver.get(url);
		WebDriver augmentedDriver = new Augmenter().augment(driver);
		File screenshot = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
		File file = new File(filePath);
		FileUtils.copyFile(screenshot, file);
		logger.info("capture success!");
	} catch (IOException e) {
		logger.error("browser capture is error!", e);
		filePath = null;
		throw new RuntimeException(e);
	}
	return filePath;
}
 
Example 25
Project: alimama   File: SeleniumUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 鎴浘
 * 
 * @param driver
 * @param url
 * @param filePath
 * @return
 */
public static String captureDataoke(WebDriver driver, String url, String filePath) {
	if (driver == null) {
		return null;
	}
	if (!url.startsWith("http:") && !url.startsWith("https:")) {
		return null;
	}
	if (StringUtils.isBlank(filePath)) {
		return null;
	}
	try {
		driver.get(url);
		WebDriver augmentedDriver = new Augmenter().augment(driver);
		File screenshot = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
		File file = new File(filePath);
		FileUtils.copyFile(screenshot, file);
		logger.info("capture success!");
	} catch (IOException e) {
		logger.error("browser capture is error!", e);
		filePath = null;
		throw new RuntimeException(e);
	}
	return filePath;
}
 
Example 26
Project: sentinela   File: PrintsScreen.java   Source Code and License 6 votes vote down vote up
public static File printWebElement(WebElement element, WebDriver driver) throws IOException {
	File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
	Point p = element.getLocation();
	int width = element.getSize().getWidth();
	int height = element.getSize().getHeight();
	BufferedImage img = null;
	BufferedImage dest = null;
	img = ImageIO.read(scrFile);
	if (element.isDisplayed()) {
		dest = img.getSubimage(p.getX(), p.getY(), width, height);
	} else {
		dest = img.getSubimage(0, 0, 1, 1);
	}
	ImageIO.write(dest, ManipulateFiles.getListString("imgExtension"), scrFile);
	return scrFile;
}
 
Example 27
Project: jwebrobot   File: Screenshooter.java   Source Code and License 6 votes vote down vote up
public void takeScreenshot(ScenarioExecutionContext scenarioContext, Action action){
    WebDriver driver = scenarioContext.getDriver();

    if(driver instanceof TakesScreenshot){
    	ScenarioExecutionContext scenarioRootContext = scenarioContext.getRoot();
        BufferedImage screenshot = new AShot()
         .shootingStrategy(getShootingStrategy(scenarioRootContext))
         .takeScreenshot(driver).getImage();
        String format = getScreenshotFormat(scenarioRootContext);
        String targetFileName = getFileName(scenarioRootContext, action, format);
        try {
        	ImageIO.write(screenshot, format, new File(targetFileName));
        } catch (IOException e) {
            throw new NonReadableFileException(targetFileName, e);
        }
    }
}
 
Example 28
Project: hugegherkin   File: SeleniumHelperImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Gets screen shot.
 *
 * @param driver   the driver
 * @param filename the filename
 *
 * @return the screen shot
 *
 * @throws IOException the iO exception
 */
public File getScreenShot(WebDriver driver, String filename) throws IOException {
    File imageFile = null;
    try {
        createScreenShotDir();

        File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

        String path = pathToScreenshot + relativeScreenshotPath + filename + scrFile.getName();
        imageFile = new File(path);
        FileUtils.copyFile(scrFile, imageFile);
        logger.debug("We are taking screenshots!");
    } catch (Exception ex) {
        // Any exception in Screen shot should be eaten here. It should not hamper selenium tests.
        logger.debug("Something went wrong getting a screenshots");
    }
    return imageFile;
}
 
Example 29
Project: seleniumMvnScreenshot   File: FailTestScreenshotListener.java   Source Code and License 6 votes vote down vote up
@Override
public void onTestFailure(ITestResult tr) {
    super.onTestFailure(tr);

    WebDriver webDriver = findWebDriverByReflection(tr.getInstance()    );
    if (webDriver == null) {
        System.err.println(String.format("The test class '%s' does not have any field/method of type 'org.openqa.selenium.WebDriver'. " +
                "ScreenshotTestListener can not continue.", tr.getInstance().getClass().getName()));
        return;
    }

    File f = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
    try {
        final long timestamp = new Date().getTime();
        Path screenshotPath = Paths.get(currentDir, "target", "screenshot_" + tr.getMethod().getMethodName() + "_" + timestamp + ".png");
        System.out.println("copying " + screenshotPath);
        Files.copy(f.toPath(), screenshotPath, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        System.err.println("error during the screenshot copy file operation:" + e.getMessage());
    }

}
 
Example 30
Project: kc-rice   File: WebDriverScreenshotHelper.java   Source Code and License 6 votes vote down vote up
/**
 * 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 31
Project: seleniumtestsframework   File: ScreenshotUtil.java   Source Code and License 6 votes vote down vote up
public static String captureEntirePageScreenshotToString(final WebDriver driver, final String arg0) {
    if (driver == null) {
        return "";
    }

    try {

        // Don't capture snapshot for htmlunit
        if (WebUIDriver.getWebUIDriver().getBrowser().equalsIgnoreCase(BrowserType.HtmlUnit.getBrowserType())) {
            return null;
        }

        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 32
Project: webcat-testing-platform   File: NullPageObject.java   Source Code and License 6 votes vote down vote up
@Override
protected void takeScreenshotImpl(String methodName) {
    try {
        final byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
        final IContext context = Context.getInstance();
        context.addScreenshot(screenshot);
    }
    catch(UnreachableBrowserException ex) {
        logger.log(Level.WARN, "Could not reach browser to take screenshot");
    }
    catch(WebDriverException webDriverEx) {
        if(webDriverEx.getMessage().contains("Session not found")) {
            logger.log(Level.WARN, "Could not reach browser to take screenshot");
        } else {
            throw webDriverEx;
        }
    }
}
 
Example 33
Project: FuncaoWeb   File: Nucleo.java   Source Code and License 6 votes vote down vote up
/**
 * Tira uma foto da p�gina
 * 
 * @param path
 *            - Retorna o local que a imagem foi gravada.
 * @author Rog�rio Figueiredo.
 */

public String captureScreen(String path) {
	path = path + "\\";
	try {
		WebDriver augmentedDriver = new Augmenter().augment(driver);
		File source = ((TakesScreenshot) augmentedDriver)
				.getScreenshotAs(OutputType.FILE);
		path = path + source.getName();
		FileUtils.copyFile(source, new File(path));
	} catch (IOException e) {
		path = "Failed to capture screenshot: " + e.getMessage();
	}

	System.out.println("Local que foi gravado a imagem: " + path);
	return path;
}
 
Example 34
Project: edx-app-android   File: NativeAppDriver.java   Source Code and License 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 35
Project: AppiumTestDistribution   File: Hooks.java   Source Code and License 6 votes vote down vote up
@After
public void afterClass(Scenario scenario) throws InterruptedException, IOException {
    if (scenario.isFailed()) {
        try {
            byte[] screenshot =
                    ((TakesScreenshot) AppiumDriverManager.getDriver())
                            .getScreenshotAs(OutputType.BYTES);
            scenario.embed(screenshot, "image/png");
        } catch (WebDriverException wde) {
            System.err.println(wde.getMessage());
        } catch (ClassCastException cce) {
            cce.printStackTrace();
        }
        System.out.println("Inside After" + Thread.currentThread().getId());
    }
    AppiumDriverManager.getDriver().quit();

}
 
Example 36
Project: kspl-selenium-helper   File: MiscellaneousFunctions.java   Source Code and License 6 votes vote down vote up
/**
 * 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 37
Project: netarchivesuite-svngit-migration   File: SeleniumTest.java   Source Code and License 6 votes vote down vote up
@AfterMethod
/**
 * Takes care of failure situations. This includes: <ol>
 * <li> Generate a a screen dump of the page failing the test.
 * <ol>
 * 
 * This method is called by TestNG.
 * 
 * @param result The result which TestNG will inject
 */
public void onFailure(ITestResult result) { 
    if (!result.isSuccess()) { 
        log.info("Test failure, dumping screenshot as " + "target/failurescreendumps/" + 
                result.getMethod() + ".png");
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(scrFile, new File("failurescreendumps/" + result.getMethod() + ".png"));
        } catch (IOException e) {
            log.error("Failed to save screendump on error");
        }
    }
}
 
Example 38
Project: VirtusaSeleniumWebdriverRuntime   File: ScreenshotListenerVir.java   Source Code and License 6 votes vote down vote up
/**
 * On test failure.
 * 
 * result the result
 * 
 * @param result
 *            the result
 * @see org.testng.ITestListener#onTestFailure(org.testng.ITestResult)
 */
@Override
public final void onTestFailure(final ITestResult result) {
    Reporter.setCurrentTestResult(result);

    try {

        if (outputDirectory.mkdirs()) {
            String fileloc = getProperties();
            File scrFile =
                    ((TakesScreenshot) driver)
                            .getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(scrFile, new File(fileloc + ".png"));
            Reporter.log("<a href='" + fileloc + ".png'>screenshot</a>");
        } else {
            System.err.println("Creation of directory failed "
                    + outputDirectory.getAbsolutePath());
        }
    } catch (Exception e) {
        e.printStackTrace();
        Reporter.log("Couldn't create screenshot");
        Reporter.log(e.getMessage());
    }

    Reporter.setCurrentTestResult(null);
}
 
Example 39
Project: carbon-platform-integration-utils   File: UIManagementListener.java   Source Code and License 6 votes vote down vote up
/**
 * Capture the current web browser screen and save it.
 *
 * @param fullTestName - Full name of the test case.
 */
private void doScreenCapture(String fullTestName) {
    WebDriver webDriver = BrowserManager.driver;
    try {
        log.info("Screen capturing Start : " + fullTestName);
        // Retrieve report location of the Test Framework
        String reportLocation = FrameworkPathUtil.getReportLocation();
        long currentTime = System.currentTimeMillis();
        DateFormat dateFormat = new SimpleDateFormat(ExtensionCommonConstants.DATE_FORMAT_YY_MM_DD_HH_MIN_SS);
        Calendar cal = Calendar.getInstance();
        //Image path looks like :
        // [reportlocation]/capturedscreens/failedtests/[fullTestName]_[Date]_[Current time in milliseconds].png
        String imagePath =
                reportLocation + File.separator + ExtensionCommonConstants.SCREEN_SHOT_LOCATION + File.separator +
                        fullTestName + "_" + dateFormat.format(cal.getTime()) + "_" + currentTime +
                        ExtensionCommonConstants.SCREEN_SHOT_EXTENSION;
        File scrFile = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File(imagePath));
        log.info("Screen capturing End : " + fullTestName);
    } catch (IOException e) {
        //  Even having problems in screen shot  generation, test need to be continued hence not throwing any exceptions.
        log.warn("Error in screen capturing  for test failure in " + fullTestName, e);
    }
}
 
Example 40
Project: hsac-fitnesse-fixtures   File: SeleniumHelper.java   Source Code and License 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;
}