@After public void embedScreenshot(Scenario scenario) { try { if (!scenario.isFailed()) { // Take a screenshot only in the failure case return; } String webDriverType = System.getProperty("WebDriverType"); if (!webDriverType.equals("HtmlUnit")) { // HtmlUnit does not support screenshots byte[] screenshot = getScreenshotAs(OutputType.BYTES); scenario.embed(screenshot, "image/png"); } } catch (WebDriverException somePlatformsDontSupportScreenshots) { scenario.write(somePlatformsDontSupportScreenshots.getMessage()); } }
@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(); }
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(); } }
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(); }
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) { ; } } }
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(); } }; }
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; }
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; }
@SuppressWarnings("unchecked") @Override protected void prepareDriver() throws Exception { System.clearProperty("test.selenium.remote"); localDriverClass = WebDriverMock.class.getName(); remoteDriverClass = WebDriverMock.class.getName(); scenario = "sc"; super.prepareDriver(); mockDriver = Mockito.mock(WebDriverMock.class); Mockito.when(mockDriver.getScreenshotAs(ArgumentMatchers.any(OutputType.class))) .thenReturn(new File(Thread.currentThread().getContextClassLoader().getResource("log4j2.json").toURI())); final Options options = Mockito.mock(Options.class); Mockito.when(options.window()).thenReturn(Mockito.mock(Window.class)); Mockito.when(mockDriver.manage()).thenReturn(options); final WebElement webElement = Mockito.mock(WebElement.class); Mockito.when(mockDriver.findElement(ArgumentMatchers.any(By.class))).thenReturn(webElement); Mockito.when(webElement.isDisplayed()).thenReturn(true); this.driver = mockDriver; }
@SuppressWarnings("unchecked") @Override protected void prepareDriver() throws Exception { testName = Mockito.mock(TestName.class); Mockito.when(testName.getMethodName()).thenReturn("mockTest"); System.clearProperty("test.selenium.remote"); localDriverClass = WebDriverMock.class.getName(); remoteDriverClass = WebDriverMock.class.getName(); scenario = "sc"; super.prepareDriver(); mockDriver = Mockito.mock(WebDriverMock.class); Mockito.when(((WebDriverMock) mockDriver).getScreenshotAs(ArgumentMatchers.any(OutputType.class))).thenReturn( new File(Thread.currentThread().getContextClassLoader().getResource("log4j2.json").toURI())); final Options options = Mockito.mock(Options.class); Mockito.when(options.window()).thenReturn(Mockito.mock(Window.class)); Mockito.when(mockDriver.manage()).thenReturn(options); final WebElement webElement = Mockito.mock(WebElement.class); Mockito.when(mockDriver.findElement(ArgumentMatchers.any(By.class))).thenReturn(webElement); Mockito.when(webElement.isDisplayed()).thenReturn(true); this.driver = mockDriver; }
@SuppressWarnings("unchecked") @Override protected void prepareDriver() throws Exception { System.clearProperty("test.selenium.remote"); localDriverClass = WebDriverMock.class.getName(); remoteDriverClass = WebDriverMock.class.getName(); scenario = "sc"; super.prepareDriver(); mockDriver = Mockito.mock(WebDriverMock.class); Mockito.when(mockDriver.getScreenshotAs(ArgumentMatchers.any(OutputType.class))).thenReturn( new File(Thread.currentThread().getContextClassLoader().getResource("log4j2.json").toURI())); final Options options = Mockito.mock(Options.class); Mockito.when(options.window()).thenReturn(Mockito.mock(Window.class)); Mockito.when(mockDriver.manage()).thenReturn(options); final WebElement webElement = Mockito.mock(WebElement.class); Mockito.when(mockDriver.findElement(ArgumentMatchers.any(By.class))).thenReturn(webElement); Mockito.when(webElement.isDisplayed()).thenReturn(true); this.driver = mockDriver; }
/** * 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()); } }
/** * <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()); } } }
/** * 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(); } }
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); } }
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); } }
/** * Download the report. type - pdf, html, csv, xml Example: * downloadReport(driver, "pdf", "C:\\test\\report"); */ public static void downloadReport(String type, String fileName) throws IOException { try { String command = "mobile:report:download"; Map<String, Object> params = new HashMap<String, Object>(); params.put("type", type); String report = (String) new WebDriverTestBase().getDriver() .executeScript(command, params); File reportFile = new File(fileName + "." + type); BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(reportFile)); byte[] reportBytes = OutputType.BYTES.convertFromBase64Png(report); output.write(reportBytes); output.close(); } catch (Exception ex) { System.out.println("Got exception " + ex); } }
/** * 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; } }
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"); } }
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(); }
@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(); } } }
@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; }
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); }
@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(); } }
/** * 鎴浘 * * @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; }
/** * 鎴浘 * * @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; }
@Test public void seleniumDemo() throws Exception { // Hard coded to firefox DesiredCapabilities caps = DesiredCapabilities.firefox(); // Hard coded selenium host RemoteWebDriver driver = new RemoteWebDriver(new URL("http://192.168.99.100:4444/wd/hub"), caps); driver.get("http://google.com"); String source = driver.getPageSource(); File file = driver.getScreenshotAs(OutputType.FILE); //TODO log the screenshot and source to a report // don't forget to close the WebDriver connection driver.quit(); }
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; }
/** * 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; }
@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()); } }
/** * 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); } }
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 ""; }
@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; } } }
/** * 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; }
/** * 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(); } }
public String captureScreenShot(int status, String className, String methodName, String deviceModel) throws IOException, InterruptedException { String getDeviceModel = null; if (AppiumDriverManager.getDriver().getSessionId() != null) { System.out.println("Current Running Thread Status" + AppiumDriverManager.getDriver().getSessionId()); File scrFile = AppiumDriverManager.getDriver() .getScreenshotAs(OutputType.FILE); screenShotNameWithTimeStamp = currentDateAndTime(); if (AppiumDeviceManager.getMobilePlatform().equals(MobilePlatform.ANDROID)) { getDeviceModel = screenShotNameWithTimeStamp + deviceModel; screenShotAndFrame(status, scrFile, methodName, className, getDeviceModel, "android", deviceModel); } else if (AppiumDeviceManager.getMobilePlatform().equals(MobilePlatform.IOS)) { getDeviceModel = screenShotNameWithTimeStamp + deviceModel; screenShotAndFrame(status, scrFile, methodName, className, getDeviceModel, "iOS", deviceModel); } } return getDeviceModel; }
@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(); }
/** * 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; }