简体   繁体   English

如何使用 selenium 4 和 java 编写通用的 base64 截图方法并将其附加到测试失败的范围报告中?

[英]How to write a generic base64 screenshot method using selenium 4 with java and attach it to extent report on test failure?

method used currently目前使用的方法

public static String getScreenshot(String screenshotName) throws IOException {
        String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
        TakesScreenshot ts = (TakesScreenshot) Base.getDriver();
        File source = ts.getScreenshotAs(OutputType.FILE);
        String destination = System.getProperty("user.dir") + "/FailedTestsScreenshots/" + screenshotName + dateName
                + ".png";
        File finalDestination = new File(destination);
        FileUtils.copyFile(source, finalDestination);
        return destination;
    }

TestListener.java TestListener.java

@Override
    public synchronized void onTestFailure(ITestResult result) {
        System.out.println((result.getMethod().getMethodName() + " failed!"));
        test.get().fail(result.getThrowable());
        if (result.getStatus() == ITestResult.FAILURE) {
            try {

                String imgPath = Utilities.getScreenshot(result.getName());
                test.get().addScreenCaptureFromPath(imgPath);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

I want to get the screenshot in base 64 format so that it cab be shared to anyone easily.我想获取 base 64 格式的屏幕截图,以便轻松与任何人共享。 I am using selenium version 4.0.0 and extent report version 3.1.5我正在使用 selenium 版本 4.0.0 和范围报告版本 3.1.5

I had a similar requirement to store screenshots in base64 as reports will be shared with multiple stakeholders across my team.我有类似的要求将屏幕截图存储在 base64 中,因为报告将与我团队中的多个利益相关者共享。 The following solution worked well for me.以下解决方案对我来说效果很好。

Screenshot.java截图.java

public static String getScreenshot(WebDriver driver) {
        String screenshotBase64 = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64);
        return screenshotBase64;
    }

TestListener.java TestListener.java

@Override
    public void onTestFailure(ITestResult result) {
        test.fail("Test case Failed");
        test.fail("Failed step: ",MediaEntityBuilder.createScreenCaptureFromBase64String("data:image/png;base64,"+Screenshot.getScreenshot(driver)).build());
        test.fail(result.getThrowable());
    }

Here's some methods I use for this (Base64 encoding from Joe Walnes: https://github.com/jenkinsci/xstream/blob/master/xstream/src/java/com/thoughtworks/xstream/core/util/Base64Encoder.java ):这是我为此使用的一些方法(来自 Joe Walnes 的 Base64 编码: https://github.com/jenkinsci/xstream/blob/master/xstream/src/java/com/thoughtworks/xstream/core/util/Base64Encoder.Z93F725A07423FE1C889F448B33D21F ) :

 File full_scrn = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
     full_scrn.deleteOnExit();

Later on I use these methods...后来我用这些方法...

private static final char[] SIXTY_FOUR_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();

 public String FileToBase64(String ThisScreenshotPath)
     {
        String Base64String = "";
        Path screen_path = Paths.get(ThisScreenshotPath);
        byte[] screenshot_in_bytes = null;
         try
          {
          screenshot_in_bytes = Files.readAllBytes(screen_path);
          }
          catch (Exception ex)
          {
         System.out.println("Exception reading screenshot file: " + ex.toString()); 
          }
     Base64String = encode(screenshot_in_bytes);   
     return Base64String;
     }

public String encode(byte[] input) {
    StringBuffer result = new StringBuffer();
    int outputCharCount = 0;
    for (int i = 0; i < input.length; i += 3) {
        int remaining = Math.min(3, input.length - i);
        int oneBigNumber = (input[i] & 0xff) << 16 | (remaining <= 1 ? 0 : input[i + 1] & 0xff) << 8 | (remaining <= 2 ? 0 : input[i + 2] & 0xff);
        for (int j = 0; j < 4; j++) result.append(remaining + 1 > j ? SIXTY_FOUR_CHARS[0x3f & oneBigNumber >> 6 * (3 - j)] : '=');
        if ((outputCharCount += 4) % 76 == 0) result.append('\n');
    }
    return result.toString();
}

For HTML output:对于 HTML output:

"<img src=\"data:image/png;base64," + ThisScreenshotBase64String + "\"...

I do not use Extent reports, so can't help on that end.我不使用范围报告,因此对此无能为力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将屏幕截图附加到 java selenium 中的范围报告 - How to attach screenshot to Extent Report in java selenium 如何将屏幕截图附加到 cucumber java 中的范围报告 - How to attach screenshot to extent report in cucumber java 范围报告中的 Base64 图像屏幕截图显示单击报告中的屏幕截图时的垃圾值 - Base64 image screenshot in extent report is showing garbage value on clicking the screenshot in the report 如何将屏幕截图附加到 azure 报告 selenium java Z1441F19754330CA4638BFDFAZEA - How to attach screenshot to azure report for selenium java cucumber 在base64 java中编码文件失败 - Failure encoding files in base64 java 如何在Selenium Java中编写通用方法findTableRowBy()? - How to write a generic method findTableRowBy() in Selenium Java? 如何在Java中使用正则表达式从base64字符串中删除data:; base64? - how to remove data:;base64, from base64 String using regex in java? Cucumber 范围报告 - 如何将失败案例的屏幕截图添加到范围报告 - Cucumber extent report - how to add screenshot of failed case to the extent report 如何使用 java ZC31B32364CE19CA8FCD150A417ECCE8 调整 base64 ImageView 的大小? - How resize base64 ImageView using java android? 如何使用 Java 中的 Base64 对 hash 进行加密和解密 - How to encrypt and decrypt with hash using Base64 in Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM