com.aventstack.extentreports.ExtentTest

Here are the examples of the java api com.aventstack.extentreports.ExtentTest taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

60 Examples 7

19 Source : ExtentTestReport.java
with Apache License 2.0
from sergiomartins8

public static synchronized void createTest(String testName, String desc) {
    ExtentTest test = ExtentManager.getInstance().createTest(testName, desc);
    EXTENT_TEST_MAP.put(Thread.currentThread().getId(), test);
}

19 Source : ExtentReportsBuilder.java
with MIT License
from prashant-ramcharan

private void addError(ExtentTest node, String error) {
    log(node, error);
}

19 Source : ExtentReportsBuilder.java
with MIT License
from prashant-ramcharan

private void addImageEmbeddings(ExtentTest node, List<Embedding> embeddings) {
    embeddings.forEach(embedding -> {
        if (embedding.getMimeType().startsWith("image")) {
            addBase64ScreenCapture(node, embedding.getData());
        }
    });
}

19 Source : MyReporter.java
with MIT License
from Jsir07

/**
 * @Auther: jx
 * @Date: 2018/6/27 17:18
 * @Description:
 */
public clreplaced MyReporter {

    public static ExtentTest report;

    private static String testName;

    public static String getTestName() {
        return testName;
    }

    public static void setTestName(String testName) {
        MyReporter.testName = testName;
    }
}

19 Source : MyExtentTestNgFormatter.java
with MIT License
from Jsir07

/**
 * Adds a screen shot image file to the report. This method should be used only in the configuration method
 * and the {@link ITestResult} is the mandatory parameter
 *
 * @param iTestResult The {@link ITestResult} object
 * @param filePath    The image file path
 * @throws IOException {@link IOException}
 */
public void addScreenCaptureFromPath(ITestResult iTestResult, String filePath) throws IOException {
    ExtentTest test = (ExtentTest) iTestResult.getAttribute("test");
    test.addScreenCaptureFromPath(filePath);
}

19 Source : ExtentTestManager.java
with Apache License 2.0
from extent-framework

public static synchronized ExtentTest getTest() {
    ExtentTest t = dataProviderTest.get() == null ? methodTest.get() : dataProviderTest.get();
    return t;
}

18 Source : ExtentReportsBuilder.java
with MIT License
from prashant-ramcharan

private void replacedignCategoryToScenario(ExtentTest scenarioNode, List<Tag> tags) {
    tags.forEach(tag -> scenarioNode.replacedignCategory(tag.getName()));
}

18 Source : ExtentReportsBuilder.java
with MIT License
from prashant-ramcharan

private void addOutputs(ExtentTest node, List<String> outputs) {
    outputs.forEach(output -> log(node, output));
}

18 Source : ExtentReportsBuilder.java
with MIT License
from prashant-ramcharan

private ExtentTest createGherkinNode(ExtentTest parent, String keyword, String name, boolean appendKeyword) {
    try {
        String nodeName = appendKeyword ? (keyword + " " + name) : name;
        return parent.createNode(new GherkinKeyword(keyword), nodeName);
    } catch (ClreplacedNotFoundException e) {
        throw new CourgetteException(e);
    }
}

18 Source : MyExtentTestNgFormatter.java
with MIT License
from Jsir07

/**
 * Marks the given node as failed
 *
 * @param nodeName The name of the node
 * @param t        The {@link Throwable} object
 */
public void failTheNode(String nodeName, Throwable t) {
    ITestResult result = Reporter.getCurrentTestResult();
    Preconditions.checkState(result != null);
    ExtentTest test = (ExtentTest) result.getAttribute(nodeName);
    test.fail(t);
}

18 Source : MyExtentTestNgFormatter.java
with MIT License
from Jsir07

public void beforeInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {
    if (iInvokedMethod.isTestMethod()) {
        ITestContext iTestContext = iTestResult.getTestContext();
        ExtentTest testContext = (ExtentTest) iTestContext.getAttribute("testContext");
        ExtentTest test = testContext.createNode(iTestResult.getName(), iInvokedMethod.getTestMethod().getDescription());
        iTestResult.setAttribute("test", test);
    }
}

18 Source : MyExtentTestNgFormatter.java
with MIT License
from Jsir07

/**
 * Adds a screen shot image file to the report. This method should be used only in the
 * {@link org.testng.annotations.Test} annotated method
 *
 * @param filePath The image file path
 * @throws IOException {@link IOException}
 */
public void addScreenCaptureFromPath(String filePath) throws IOException {
    ITestResult iTestResult = Reporter.getCurrentTestResult();
    Preconditions.checkState(iTestResult != null);
    ExtentTest test = (ExtentTest) iTestResult.getAttribute("test");
    test.addScreenCaptureFromPath(filePath);
}

18 Source : MyExtentTestNgFormatter.java
with MIT License
from Jsir07

/**
 * Marks the given node as failed
 *
 * @param nodeName   The name of the node
 * @param logMessage The message to be logged
 */
public void failTheNode(String nodeName, String logMessage) {
    ITestResult result = Reporter.getCurrentTestResult();
    Preconditions.checkState(result != null);
    ExtentTest test = (ExtentTest) result.getAttribute(nodeName);
    test.fail(logMessage);
}

18 Source : MyExtentTestNgFormatter.java
with MIT License
from Jsir07

public void onStart(ITestContext iTestContext) {
    ISuite iSuite = iTestContext.getSuite();
    ExtentTest suite = (ExtentTest) iSuite.getAttribute(SUITE_ATTR);
    ExtentTest testContext = suite.createNode(iTestContext.getName());
    // 自定义报告
    MyReporter.report = testContext;
    iTestContext.setAttribute("testContext", testContext);
}

18 Source : ExtentTestManager.java
with Apache License 2.0
from extent-framework

public static synchronized ExtentTest getTest(ITestResult result) {
    ExtentTest t = result.getParameters() != null && result.getParameters().length > 0 ? dataProviderTest.get() : methodTest.get();
    return t;
}

18 Source : ExtentTestManager.java
with Apache License 2.0
from extent-framework

private static synchronized ExtentTest createTest(ITestResult result, ExtentTest clreplacedTest) {
    String methodName = result.getMethod().getMethodName();
    String desc = result.getMethod().getDescription();
    ExtentTest test;
    if (clreplacedTest != null)
        test = clreplacedTest.createNode(methodName, desc);
    else
        test = ExtentService.getInstance().createTest(methodName, desc);
    methodTest.set(test);
    String[] groups = result.getMethod().getGroups();
    ExtentTestCommons.replacedignGroups(test, groups);
    return test;
}

18 Source : ExtentCucumberAdapter.java
with Apache License 2.0
from extent-framework

private synchronized void handleTestStepStarted(TestStepStarted event) {
    isHookThreadLocal.set(false);
    if (event.testStep instanceof HookTestStep) {
        ExtentTest t = scenarioThreadLocal.get().createNode(Asterisk.clreplaced, event.testStep.getCodeLocation());
        stepTestThreadLocal.set(t);
        isHookThreadLocal.set(true);
    }
    if (event.testStep instanceof PickleStepTestStep) {
        PickleStepTestStep testStep = (PickleStepTestStep) event.testStep;
        createTestStep(testStep);
    }
}

18 Source : ExtentTestManager.java
with MIT License
from dipjyotimetia

public static synchronized ExtentTest startTest(String testName, String desc) {
    ExtentTest test = extent.createTest(testName, desc);
    extentTestMap.put((int) (long) (Thread.currentThread().getId()), test);
    return test;
}

17 Source : ExtentReportsBuilder.java
with MIT License
from prashant-ramcharan

private void log(ExtentTest node, String message) {
    if (message != null) {
        node.log(Status.INFO, message);
    }
}

17 Source : ExtentReportsBuilder.java
with MIT License
from prashant-ramcharan

private void addBeforeOrAfterDetails(ExtentTest scenarioNode, List<Hook> hooks) {
    hooks.forEach(hook -> {
        String error = hook.getResult().getErrorMessage();
        List<String> output = hook.getOutput();
        List<Embedding> embeddings = hook.getEmbeddings();
        final ExtentTest hookNode = scenarioNode.createNode(com.aventstack.extentreports.gherkin.model.Asterisk.clreplaced, hook.getLocation());
        addOutputs(hookNode, output);
        addError(hookNode, error);
        addImageEmbeddings(hookNode, embeddings);
    });
}

17 Source : ExtentReportsBuilder.java
with MIT License
from prashant-ramcharan

private void addStartAndEndTime(ExtentTest node, Date startTime, Date endTime) {
    node.getModel().setStartTime(startTime);
    node.getModel().setEndTime(endTime);
}

17 Source : ReportManagerHelper.java
with MIT License
from MohabMohie

public clreplaced ReportManagerHelper {

    private static final String TIMESTAMP_FORMAT = "dd-MM-yyyy HH:mm:ss.SSSS aaa";

    private static final Logger slf4jLogger = LoggerFactory.getLogger(ReportManagerHelper.clreplaced);

    private static final String SHAFT_ENGINE_VERSION_PROPERTY_NAME = "shaftEngineVersion";

    private static final String TARGET_OS_PROPERTY_NAME = "targetOperatingSystem";

    private static final String ALLURE_VERSION_PROPERTY_NAME = "allureVersion";

    private static final String REPORT_MANAGER_PREFIX = "[ReportManager] ";

    private static final String SHAFT_ENGINE_LOGS_ATTACHMENT_TYPE = "SHAFT Engine Logs";

    private static final String OS_WINDOWS = "Windows-64";

    private static final String allureExtractionLocation = System.getProperty("user.home") + File.separator + ".m2" + File.separator + "repository" + File.separator + "allure" + File.separator;

    static int actionCounter = 1;

    private static String fullLog = "";

    private static String issuesLog = "";

    private static int issueCounter = 1;

    private static boolean discreteLogging = false;

    private static int totalNumberOfTests = 0;

    private static int testCasesCounter = 0;

    private static boolean debugMode = false;

    private static int oreplacedsuesForFailedTestsCounter = 0;

    private static int oreplacedsuesForPreplacededTestsCounter = 0;

    private static int failedTestsWithoutOreplacedsuesCounter = 0;

    private static String allureResultsFolderPath = "";

    private static String allureBinaryPath = "";

    // TODO: refactor to regular clreplaced that can be instantiated within the test and
    private static List<List<String>> listOfOreplacedsuesForFailedTests = new ArrayList<>();

    private static List<List<String>> listOfOreplacedsuesForPreplacededTests = new ArrayList<>();

    private static List<List<String>> listOfNewIssuesForFailedTests = new ArrayList<>();

    private static String featureName = "";

    private static String extentReportsFolderPath = "";

    private static ExtentReports extentReport;

    private static ExtentTest extentTest;

    private static String extentReportFileName;

    private static String generateExtentReports;

    public static String getExtentReportFileName() {
        return extentReportFileName;
    }

    public static void setOreplacedsuesForFailedTestsCounter(int oreplacedsuesForFailedTestsCounter) {
        ReportManagerHelper.oreplacedsuesForFailedTestsCounter = oreplacedsuesForFailedTestsCounter;
    }

    public static void setOreplacedsuesForPreplacededTestsCounter(int oreplacedsuesForPreplacededTestsCounter) {
        ReportManagerHelper.oreplacedsuesForPreplacededTestsCounter = oreplacedsuesForPreplacededTestsCounter;
    }

    public static void setFailedTestsWithoutOreplacedsuesCounter(int failedTestsWithoutOreplacedsuesCounter) {
        ReportManagerHelper.failedTestsWithoutOreplacedsuesCounter = failedTestsWithoutOreplacedsuesCounter;
    }

    public static void setListOfOreplacedsuesForFailedTests(List<List<String>> listOfOreplacedsuesForFailedTests) {
        ReportManagerHelper.listOfOreplacedsuesForFailedTests = listOfOreplacedsuesForFailedTests;
    }

    public static void setListOfOreplacedsuesForPreplacededTests(List<List<String>> listOfOreplacedsuesForPreplacededTests) {
        ReportManagerHelper.listOfOreplacedsuesForPreplacededTests = listOfOreplacedsuesForPreplacededTests;
    }

    public static void setListOfNewIssuesForFailedTests(List<List<String>> listOfNewIssuesForFailedTests) {
        ReportManagerHelper.listOfNewIssuesForFailedTests = listOfNewIssuesForFailedTests;
    }

    public static void logIssue(String issue) {
        if (issuesLog.trim().equals("")) {
            issuesLog += issueCounter + ", " + issue.trim();
        } else {
            issuesLog += System.lineSeparator() + issueCounter + ", " + issue.trim();
        }
        issueCounter++;
    }

    public static String prepareIssuesLog() {
        if (!listOfNewIssuesForFailedTests.isEmpty()) {
            listOfNewIssuesForFailedTests.forEach(issue -> logIssue("Test Method \"" + issue.get(0) + "." + issue.get(1) + "\" failed. Please investigate and open a new Issue if needed.\n"));
        }
        if (!listOfOreplacedsuesForPreplacededTests.isEmpty()) {
            listOfOreplacedsuesForPreplacededTests.forEach(issue -> {
                if (!issue.get(3).trim().equals("")) {
                    logIssue("Test Method \"" + issue.get(0) + "." + issue.get(1) + "\" preplaceded. Please validate and close this open issue \"" + issue.get(2) + "\": \"" + issue.get(3) + "\".\n");
                } else {
                    logIssue("Test Method \"" + issue.get(0) + "." + issue.get(1) + "\" preplaceded. Please validate and close this open issue \"" + issue.get(2) + "\".\n");
                }
            });
        }
        if (!listOfOreplacedsuesForFailedTests.isEmpty()) {
            listOfOreplacedsuesForFailedTests.forEach(issue -> {
                if (!issue.get(3).trim().equals("")) {
                    logIssue("Test Method \"" + issue.get(0) + "." + issue.get(1) + "\" failed with open issue \"" + issue.get(2) + "\": \"" + issue.get(3) + "\".\n");
                } else {
                    logIssue("Test Method \"" + issue.get(0) + "." + issue.get(1) + "\" failed with open issue \"" + issue.get(2) + "\".\n");
                }
            });
        }
        if (!issuesLog.trim().equals("")) {
            return "Issue Summary: Total Issues = " + (issueCounter - 1) + ", New issues for Failed Tests = " + failedTestsWithoutOreplacedsuesCounter + ", Open issues for Preplaceded Tests = " + oreplacedsuesForPreplacededTestsCounter + ", Open issues for Failed Tests = " + oreplacedsuesForFailedTestsCounter + ". Kindly check the attached Issue details.";
        } else {
            return "";
        }
    }

    /**
     * @return the discreteLogging
     */
    public static boolean isDiscreteLogging() {
        return discreteLogging;
    }

    /**
     * @param discreteLogging the discreteLogging to set
     */
    public static void setDiscreteLogging(boolean discreteLogging) {
        if (debugMode) {
            ReportManager.logDiscrete("Setting discrete logging to: \"" + discreteLogging + "\"");
        }
        ReportManagerHelper.discreteLogging = discreteLogging;
    }

    public static int getTestCasesCounter() {
        return testCasesCounter;
    }

    public static int getTotalNumberOfTests() {
        return totalNumberOfTests;
    }

    public static void setTotalNumberOfTests(int totalNumberOfTests) {
        ReportManagerHelper.totalNumberOfTests = totalNumberOfTests;
    }

    public static void setDebugMode(Boolean debugMode) {
        ReportManagerHelper.debugMode = debugMode;
    }

    public static void prepareAllureReportingEnvironment() {
        ReportManager.logDiscrete("Preparing Allure Reporting Environment...");
        boolean discreteLoggingState = isDiscreteLogging();
        allureResultsFolderPath = System.getProperty("allureResultsFolderPath").trim();
        if (System.getProperty("executionAddress").trim().equals("local") || (System.getProperty("mobile_platformName") != null && !System.getProperty("mobile_platformName").trim().equals(""))) {
            setDiscreteLogging(true);
            clereplacedlureResultsDirectory();
            downloadAndExtractAllureBinaries();
            writeGenerateReportShellFilesToProjectDirectory();
        }
        writeEnvironmentVariablesToAllureResultsDirectory();
        setDiscreteLogging(discreteLoggingState);
    }

    public static void logEngineVersion() {
        String engineVersion = "Detected SHAFT Engine Version: [" + System.getProperty(SHAFT_ENGINE_VERSION_PROPERTY_NAME) + "]";
        createImportantReportEntry(engineVersion, true);
    }

    public static synchronized void logTestInformation(String clreplacedName, String testMethodName, String testDescription) {
        testCasesCounter++;
        if (!testDescription.equals("")) {
            createImportantReportEntry("Starting Execution:\t[" + testCasesCounter + " out of " + totalNumberOfTests + "] test cases in the current suite\nTest Method:\t\t[" + clreplacedName + "." + testMethodName + "]\nTest Description:\t[" + testDescription + "]", false);
        } else {
            createImportantReportEntry("Starting Execution:\t[" + testCasesCounter + " out of " + totalNumberOfTests + "] test cases in the current suite\nTest Method:\t\t[" + clreplacedName + "." + testMethodName + "]", false);
        }
    }

    public static synchronized void logScenarioInformation(String keyword, String name, String steps) {
        testCasesCounter++;
        createImportantReportEntry("Starting Execution:\t[" + testCasesCounter + " out of " + totalNumberOfTests + "] scenarios in the [" + featureName + "] feature" + "\n" + keyword + " Name:\t\t[" + name + "]\n" + keyword + " Steps:\n" + steps, false);
    }

    public static void logConfigurationMethodInformation(String clreplacedName, String testMethodName) {
        // In TestNG Reporter, this log entry is logged at the end of the previous test
        // (or null for the first test)
        createImportantReportEntry("Starting Execution of a Configuration (Setup or Teardown) Method\nTest Method:\t\t[" + clreplacedName + "." + testMethodName + "]", false);
    }

    public static String formatStackTraceToLogEntry(Throwable t) {
        return formatStackTraceToLogEntry(t, false);
    }

    /**
     * Adds a new attachment using the input parameters provided. The attachment is
     * displayed as a step in the execution report. Used for Screenshots.
     *
     * @param attachmentType    the type of this attachment
     * @param attachmentName    the name of this attachment
     * @param attachmentContent the content of this attachment
     */
    public static void attach(String attachmentType, String attachmentName, InputStream attachmentContent) {
        createAttachment(attachmentType, attachmentName, attachmentContent);
    }

    /**
     * Adds a new attachment using the input parameters provided. The attachment is
     * displayed as a step in the execution report. Used for Screenshots.
     *
     * @param attachmentType    the type of this attachment
     * @param attachmentName    the name of this attachment
     * @param attachmentContent the content of this attachment
     */
    public static void attach(String attachmentType, String attachmentName, String attachmentContent) {
        if (!attachmentContent.trim().equals("")) {
            createAttachment(attachmentType, attachmentName, new ByteArrayInputStream(attachmentContent.getBytes()));
        }
    }

    /**
     * Returns the log of the current test, and attaches it in the end of the test
     * execution report.
     *
     * @param currentMethodName name of the current test method to be used in the attachment name
     * @param testLog           content of the text log to be used as the attachment value
     */
    public static void attachTestLog(String currentMethodName, String testLog) {
        appendToFullLog(testLog);
        appendToFullLog(System.lineSeparator());
        if (!testLog.isBlank()) {
            createAttachment(SHAFT_ENGINE_LOGS_ATTACHMENT_TYPE, "Current Method log: " + currentMethodName, new ByteArrayInputStream(testLog.getBytes()));
        }
    }

    public static void attachFullLog(String executionEndTimestamp) {
        if (!fullLog.trim().equals("")) {
            String fullLogCreated = "Successfully created attachment [" + SHAFT_ENGINE_LOGS_ATTACHMENT_TYPE + " - " + "Execution log" + "]";
            createReportEntry(fullLogCreated, true);
            String copyrights = "This test run was powered by SHAFT Engine Version: [" + System.getProperty(SHAFT_ENGINE_VERSION_PROPERTY_NAME) + "]" + System.lineSeparator() + "SHAFT Engine is licensed under the MIT License: [https://github.com/MohabMohie/SHAFT_ENGINE/blob/master/LICENSE].";
            createImportantReportEntry(copyrights, true);
            createAttachment(SHAFT_ENGINE_LOGS_ATTACHMENT_TYPE, "Execution log: " + executionEndTimestamp, new ByteArrayInputStream(fullLog.trim().getBytes()));
        }
    }

    public static void attachIssuesLog(String executionEndTimestamp) {
        String issueSummary = prepareIssuesLog();
        if (!issuesLog.trim().equals("")) {
            log(issueSummary, Collections.singletonList(Arrays.asList(SHAFT_ENGINE_LOGS_ATTACHMENT_TYPE, "Issues log CSV: " + executionEndTimestamp, new ByteArrayInputStream(issuesLog.trim().getBytes()))));
        }
    }

    protected static void openAllureReportAfterExecution() {
        String commandToOpenAllureReport;
        if (Boolean.TRUE.equals(Boolean.valueOf(System.getProperty("openAllureReportAfterExecution").trim())) && System.getProperty("executionAddress").trim().equals("local")) {
            if (SystemUtils.IS_OS_WINDOWS) {
                commandToOpenAllureReport = ("generate_allure_report.bat");
            } else {
                commandToOpenAllureReport = ("sh generate_allure_report.sh");
            }
            new TerminalActions(true).performTerminalCommand(commandToOpenAllureReport);
        }
    }

    protected static void generateAllureReportArchive() {
        if (Boolean.TRUE.equals(Boolean.valueOf(System.getProperty("generateAllureReportArchive").trim())) && System.getProperty("executionAddress").trim().equals("local")) {
            ReportManager.logDiscrete("Generating Allure Report Archive...");
            boolean discreteLoggingState = isDiscreteLogging();
            setDiscreteLogging(true);
            writeOpenReportShellFilesToGeneratedDirectory();
            writeAllureReportToGeneratedDirectory();
            createAllureReportArchiveAndCleanGeneratedDirectory();
            setDiscreteLogging(discreteLoggingState);
        }
    }

    public static String getCallingMethodFullName() {
        StackTraceElement[] callingStack = Thread.currentThread().getStackTrace();
        StringBuilder callingMethodFullName = new StringBuilder();
        for (int i = 1; i < callingStack.length; i++) {
            if (!callingStack[i].getClreplacedName().contains("com.shaft")) {
                callingMethodFullName.append(callingStack[i].getClreplacedName());
                if (!callingStack[i].getMethodName().isEmpty()) {
                    callingMethodFullName.append(".");
                    callingMethodFullName.append(callingStack[i].getMethodName());
                }
                break;
            }
        }
        return callingMethodFullName.toString();
    }

    public static String getTestClreplacedName() {
        return Reporter.getCurrentTestResult().getMethod().getTestClreplaced().getName();
    }

    public static String getTestMethodName() {
        return Reporter.getCurrentTestResult().getMethod().getMethodName();
    }

    public static void setTestCaseName(String scenarioName) {
        Allure.getLifecycle().updateTestCase(testResult -> testResult.setName(scenarioName));
        if (!"".equals(featureName)) {
            Allure.getLifecycle().updateTestCase(testResult -> testResult.setFullName(featureName + ": " + scenarioName));
        }
    }

    public static void setTestCaseDescription(String scenarioSteps) {
        if (scenarioSteps.contains("و")) {
            Allure.getLifecycle().updateTestCase(testResult -> testResult.setDescriptionHtml("<p dir=\"rtl\">" + scenarioSteps + "</p>"));
        } else {
            Allure.getLifecycle().updateTestCase(testResult -> testResult.setDescriptionHtml("<p dir=\"ltr\">" + scenarioSteps + "</p>"));
        }
    }

    public static Boolean isCurrentTestPreplaceded() {
        return Reporter.getCurrentTestResult().isSuccess();
    }

    public static void setFeatureName(String featureName) {
        ReportManagerHelper.featureName = featureName;
    }

    private static boolean generateExtentReports() {
        if (generateExtentReports == null) {
            generateExtentReports = System.getProperty("generateExtentReports").trim();
        }
        return Boolean.parseBoolean(generateExtentReports);
    }

    public static void initializeExtentReports() {
        if (Boolean.TRUE.equals(generateExtentReports())) {
            extentReportsFolderPath = System.getProperty("extentReportsFolderPath").trim();
            cleanExtentReportsDirectory();
            extentReportFileName = extentReportsFolderPath + "ExtentReports_" + (new SimpleDateFormat("dd-MM-yyyy_HH-mm-ss-SSSS-aaa")).format(System.currentTimeMillis()) + ".html";
            extentReport = new ExtentReports();
            ExtentSparkReporter spark = new ExtentSparkReporter(extentReportFileName).viewConfigurer().viewOrder().as(new ViewName[] { ViewName.DASHBOARD, ViewName.TEST, ViewName.EXCEPTION }).apply();
            extentReport.attachReporter(spark);
            spark.config().setTheme(Theme.STANDARD);
            spark.config().setDoreplacedentreplacedle("Extent Reports");
            spark.config().setReportName("Extent Reports - Powered by SHAFT_Engine");
        }
    }

    private static void cleanExtentReportsDirectory() {
        if (Boolean.TRUE.equals(Boolean.valueOf(System.getProperty("cleanExtentReportsDirectoryBeforeExecution")))) {
            FileActions.deleteFolder(extentReportsFolderPath.substring(0, extentReportsFolderPath.length() - 1));
        }
    }

    public static void extentReportsReset() {
        extentTest = null;
    }

    public static void extentReportsCreateTest(String testName, String testDescription) {
        if (Boolean.TRUE.equals(generateExtentReports())) {
            if (testDescription.equals("")) {
                extentTest = extentReport.createTest(testName);
            } else {
                extentTest = extentReport.createTest(testDescription);
            }
        }
    }

    public static void extentReportsPreplaced(String message) {
        if (Boolean.TRUE.equals(generateExtentReports())) {
            extentTest.preplaced(message);
        }
    }

    public static void extentReportsFail(String message) {
        if (Boolean.TRUE.equals(generateExtentReports())) {
            extentTest.fail(message);
        }
    }

    public static void extentReportsFail(Throwable t) {
        if (Boolean.TRUE.equals(generateExtentReports())) {
            extentTest.fail(t);
        }
    }

    public static void extentReportsSkip(String message) {
        if (Boolean.TRUE.equals(generateExtentReports())) {
            extentTest.skip(message);
        }
    }

    public static void extentReportsSkip(Throwable t) {
        if (Boolean.TRUE.equals(generateExtentReports())) {
            extentTest.skip(t);
        }
    }

    public static void extentReportsFlush() {
        if (Boolean.TRUE.equals(generateExtentReports())) {
            extentReport.flush();
        }
    }

    protected static void logClosureActivitiesInitialization() {
        String closureActivities = "Test Closure Activities";
        createImportantReportEntry(closureActivities, true);
    }

    private static String formatStackTraceToLogEntry(Throwable t, boolean isCause) {
        StringBuilder logBuilder = new StringBuilder();
        if (t != null) {
            StackTraceElement[] trace = t.getStackTrace();
            if (isCause) {
                logBuilder.append(System.lineSeparator()).append("Caused by: ");
            }
            logBuilder.append(t.getClreplaced().getName()).append(":").append(System.lineSeparator()).append(t.getMessage()).append(System.lineSeparator());
            for (StackTraceElement stackTraceElement : trace) {
                logBuilder.append(stackTraceElement.toString()).append(System.lineSeparator());
            }
            logBuilder.append(formatStackTraceToLogEntry(t.getCause(), true));
        }
        return logBuilder.toString();
    }

    static void createLogEntry(String logText) {
        String timestamp = (new SimpleDateFormat(TIMESTAMP_FORMAT)).format(new Date(System.currentTimeMillis()));
        if (logText == null) {
            logText = "null";
        }
        String log = REPORT_MANAGER_PREFIX + logText.trim() + " @" + timestamp;
        slf4jLogger.info(log);
        Reporter.log(log, false);
    }

    /**
     * Appends a log entry to the complete log of the current execution session.
     *
     * @param log the log entry that needs to be appended to the full log
     */
    private static void appendToFullLog(String log) {
        fullLog += log;
    }

    private static void createReportEntry(String logText, Boolean addToFullLog) {
        String timestamp = (new SimpleDateFormat(TIMESTAMP_FORMAT)).format(new Date(System.currentTimeMillis()));
        if (logText == null) {
            logText = "null";
        }
        String log = REPORT_MANAGER_PREFIX + logText.trim() + " @" + timestamp;
        Reporter.log(log, true);
        if (extentTest != null && !logText.contains("created attachment") && !logText.contains("<html")) {
            extentTest.info(logText);
        }
        if (addToFullLog) {
            appendToFullLog(log);
            appendToFullLog(System.lineSeparator());
        }
    }

    private static void createImportantReportEntry(String logText, Boolean addToFullLog) {
        boolean initialLoggingStatus = discreteLogging;
        // force log even if discrete logging was turned on
        setDiscreteLogging(false);
        String log = System.lineSeparator() + "################################################################################################################################################" + System.lineSeparator() + logText.trim() + System.lineSeparator() + "################################################################################################################################################";
        Reporter.log(log, true);
        if (Boolean.TRUE.equals(addToFullLog)) {
            appendToFullLog(log);
            appendToFullLog(System.lineSeparator());
        }
        setDiscreteLogging(initialLoggingStatus);
    }

    /**
     * Formats logText and adds timestamp, then logs it as a step in the execution
     * report.
     *
     * @param logText the text that needs to be logged in this action
     */
    @Step("Action [{actionCounter}]: {logText}")
    static void writeStepToReport(@SuppressWarnings("UnusedParameters") int actionCounter, String logText) {
        createReportEntry(logText, false);
    }

    @Step("Action [{actionCounter}]: {logText}")
    static void writeStepToReport(@SuppressWarnings("UnusedParameters") int actionCounter, String logText, List<List<Object>> attachments) {
        createReportEntry(logText, false);
        if (attachments != null) {
            attachments.forEach(attachment -> {
                if (attachment != null && attachment.get(2).getClreplaced().toString().toLowerCase().contains("string") && !attachment.get(2).getClreplaced().toString().contains("StringInputStream")) {
                    if (!attachment.get(2).toString().isEmpty()) {
                        attach(attachment.get(0).toString(), attachment.get(1).toString(), attachment.get(2).toString());
                    }
                } else if (attachment != null) {
                    if (attachment.get(2) instanceof byte[]) {
                        attach(attachment.get(0).toString(), attachment.get(1).toString(), new ByteArrayInputStream((byte[]) attachment.get(2)));
                    } else {
                        attach(attachment.get(0).toString(), attachment.get(1).toString(), (InputStream) attachment.get(2));
                    }
                }
            });
        }
    }

    private static void createAttachment(String attachmentType, String attachmentName, InputStream attachmentContent) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            attachmentContent.transferTo(baos);
        } catch (IOException e) {
            String error = "Error while creating Attachment";
            slf4jLogger.info(error, e);
            Reporter.log(error, false);
        }
        String attachmentDescription = "Attachment: " + attachmentType + " - " + attachmentName;
        attachBasedOnFileType(attachmentType, attachmentName, baos, attachmentDescription);
        logAttachmentAction(attachmentType, attachmentName, baos);
    }

    private static synchronized void attachBasedOnFileType(String attachmentType, String attachmentName, ByteArrayOutputStream attachmentContent, String attachmentDescription) {
        if (attachmentType.toLowerCase().contains("screenshot")) {
            Allure.addAttachment(attachmentDescription, "image/png", new ByteArrayInputStream(attachmentContent.toByteArray()), ".png");
            attachImageToExtentReport("image/png", new ByteArrayInputStream(attachmentContent.toByteArray()));
        } else if (attachmentType.toLowerCase().contains("recording")) {
            Allure.addAttachment(attachmentDescription, "video/mp4", new ByteArrayInputStream(attachmentContent.toByteArray()), ".mp4");
        // attachmentDescription, "video/quicktime", attachmentContent, ".mov");
        // attachmentDescription, "video/webm", attachmentContent, ".webm");
        // attachmentDescription, "video/mp4", attachmentContent, ".mp4");
        // attachmentDescription, "video/ogg", attachmentContent, ".ogg");
        } else if (attachmentType.toLowerCase().contains("gif")) {
            Allure.addAttachment(attachmentDescription, "image/gif", new ByteArrayInputStream(attachmentContent.toByteArray()), ".gif");
            attachImageToExtentReport("image/gif", new ByteArrayInputStream(attachmentContent.toByteArray()));
        } else if (attachmentType.toLowerCase().contains("csv") || attachmentName.toLowerCase().contains("csv")) {
            Allure.addAttachment(attachmentDescription, "text/csv", new ByteArrayInputStream(attachmentContent.toByteArray()), ".csv");
            attachCodeBlockToExtentReport("text/csv", new ByteArrayInputStream(attachmentContent.toByteArray()));
        } else if (attachmentType.toLowerCase().contains("xml") || attachmentName.toLowerCase().contains("xml")) {
            Allure.addAttachment(attachmentDescription, "text/xml", new ByteArrayInputStream(attachmentContent.toByteArray()), ".xml");
            attachCodeBlockToExtentReport("text/xml", new ByteArrayInputStream(attachmentContent.toByteArray()));
        } else if (attachmentType.toLowerCase().contains("excel") || attachmentName.toLowerCase().contains("excel")) {
            Allure.addAttachment(attachmentDescription, "application/vnd.openxmlformats-officedoreplacedent.spreadsheetml.sheet", new ByteArrayInputStream(attachmentContent.toByteArray()), ".xlsx");
        } else if (attachmentType.toLowerCase().contains("json") || attachmentName.toLowerCase().contains("json")) {
            Allure.addAttachment(attachmentDescription, "text/json", new ByteArrayInputStream(attachmentContent.toByteArray()), ".json");
            attachCodeBlockToExtentReport("text/json", new ByteArrayInputStream(attachmentContent.toByteArray()));
        } else if (attachmentType.toLowerCase().contains("engine logs")) {
            Allure.addAttachment(attachmentDescription, "text/plain", new ByteArrayInputStream(attachmentContent.toByteArray()), ".txt");
        } else {
            Allure.addAttachment(attachmentDescription, new ByteArrayInputStream(attachmentContent.toByteArray()));
        }
    }

    private static synchronized void logAttachmentAction(String attachmentType, String attachmentName, ByteArrayOutputStream attachmentContent) {
        if (!(attachmentType.equals(SHAFT_ENGINE_LOGS_ATTACHMENT_TYPE) && attachmentName.equals("Execution log"))) {
            createReportEntry("Successfully created attachment [" + attachmentType + " - " + attachmentName + "]", false);
        }
        if (debugMode && !attachmentType.contains(SHAFT_ENGINE_LOGS_ATTACHMENT_TYPE) && !attachmentType.equalsIgnoreCase("Selenium WebDriver Logs") && !attachmentType.toLowerCase().contains("screenshot") && !attachmentType.toLowerCase().contains("recording") && !attachmentType.toLowerCase().contains("gif") && !attachmentType.toLowerCase().contains("engine logs")) {
            String timestamp = (new SimpleDateFormat(TIMESTAMP_FORMAT)).format(new Date(System.currentTimeMillis()));
            String theString;
            BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(attachmentContent.toByteArray()), StandardCharsets.UTF_8));
            theString = br.lines().collect(Collectors.joining(System.lineSeparator()));
            if (!theString.isEmpty()) {
                String logEntry = REPORT_MANAGER_PREFIX + "Debugging Attachment Entry" + " @" + timestamp + System.lineSeparator() + theString + System.lineSeparator();
                slf4jLogger.info(logEntry);
            }
        }
    }

    private static void attachCodeBlockToExtentReport(String attachmentType, InputStream attachmentContent) {
        if (extentTest != null) {
            try {
                String codeBlock = IOUtils.toString(attachmentContent, StandardCharsets.UTF_8.name());
                switch(attachmentType) {
                    case "text/json":
                        extentTest.info(MarkupHelper.createCodeBlock(codeBlock, CodeLanguage.JSON));
                    case "text/xml":
                        extentTest.info(MarkupHelper.createCodeBlock(codeBlock, CodeLanguage.XML));
                    default:
                        extentTest.info(MarkupHelper.createCodeBlock(codeBlock));
                }
            } catch (IOException e) {
                ReportManager.logDiscrete("Failed to attach code block to extentReport.");
            }
        }
    }

    private static void attachImageToExtentReport(String attachmentType, InputStream attachmentContent) {
        if (extentTest != null) {
            try {
                String image = Base64.getEncoder().encodeToString(IOUtils.toByteArray(attachmentContent));
                if (attachmentType.toLowerCase().contains("gif")) {
                    extentTest.addScreenCaptureFromBase64String(image);
                } else {
                    extentTest.info(MediaEnreplacedyBuilder.createScreenCaptureFromBase64String(image).build());
                }
            } catch (IOException e) {
                ReportManager.logDiscrete("Failed to attach screenshot to extentReport.");
            }
        }
    }

    private static void clereplacedlureResultsDirectory() {
        // clean allure-results directory before execution
        if (Boolean.TRUE.equals(Boolean.valueOf(System.getProperty("clereplacedlureResultsDirectoryBeforeExecution")))) {
            FileActions.deleteFolder(allureResultsFolderPath.substring(0, allureResultsFolderPath.length() - 1));
        }
    }

    private static void writeEnvironmentVariablesToAllureResultsDirectory() {
        // reads all environment variables and then formats and writes them to be read
        // by the Allure report
        Properties props = System.getProperties();
        StringBuilder propertiesFileBuilder = new StringBuilder();
        propertiesFileBuilder.append("<environment>");
        // read properties from any explicit properties files
        for (int i = 0; i < props.size(); i++) {
            String propertyKey = ((String) (props.keySet().toArray())[i]).trim();
            String propertyValue = props.getProperty(propertyKey).trim();
            // excluding empty values, system properties (all system properties have "." in
            // their names), and any git branch issues
            if (!propertyValue.equals("") && !propertyValue.contains("==") && !propertyKey.contains(">>>") && !propertyKey.contains("<<<")) {
                if (propertyValue.contains("&")) {
                    propertyValue = propertyValue.replace("&", "&");
                }
                String parameter = "<parameter>" + "<key>" + propertyKey + "</key>" + "<value>" + propertyValue + "</value>" + "</parameter>";
                if (propertyKey.equals(SHAFT_ENGINE_VERSION_PROPERTY_NAME)) {
                    // there's an open issue, when fixed this will be displayed properly
                    // https://github.com/allure-framework/allure2/issues/382
                    propertiesFileBuilder.insert(13, parameter);
                } else {
                    propertiesFileBuilder.append(parameter);
                }
            }
        }
        propertiesFileBuilder.append("</environment>");
        FileActions.writeToFile(System.getProperty("allureResultsFolderPath"), "environment.xml", RestActions.formatXML(propertiesFileBuilder.toString()));
    }

    private static void downloadAndExtractAllureBinaries() {
        // extract allure from jar file to src/main/resources directory if it doesn't
        // already exist
        String allureVersion = System.getProperty(ALLURE_VERSION_PROPERTY_NAME);
        allureBinaryPath = allureExtractionLocation + "allure-" + allureVersion + File.separator + "bin" + File.separator + "allure";
        if (!FileActions.doesFileExist(allureBinaryPath)) {
            FileActions.deleteFolder(allureExtractionLocation);
            // download allure binary
            URL allureArchive = FileActions.downloadFile("https://repo.maven.apache.org/maven2/io/qameta/allure/allure-commandline/" + allureVersion + "/allure-commandline-" + allureVersion + ".zip", "target" + File.separator + "allureBinary.zip");
            FileActions.unpackArchive(allureArchive, allureExtractionLocation);
            // extract allure from SHAFT_Engine jar
            URL allureSHAFTConfigArchive = ReportManagerHelper.clreplaced.getResource("/resources/allure/allureBinary_SHAFTEngineConfigFiles.zip");
            FileActions.unpackArchive(allureSHAFTConfigArchive, allureExtractionLocation + "allure-" + allureVersion + File.separator);
            if (!System.getProperty(TARGET_OS_PROPERTY_NAME).equals(OS_WINDOWS)) {
                // make allure executable on unix-based shells
                (new TerminalActions()).performTerminalCommand("chmod u+x " + allureBinaryPath);
            }
        }
    }

    private static void writeGenerateReportShellFilesToProjectDirectory() {
        String allureVersion = System.getProperty(ALLURE_VERSION_PROPERTY_NAME);
        // create generate_allure_report.sh or generate_allure_report.bat
        List<String> commandsToServeAllureReport;
        if (SystemUtils.IS_OS_WINDOWS) {
            // create windows batch file
            commandsToServeAllureReport = Arrays.asList("@echo off", "set path=" + allureExtractionLocation + "allure-" + allureVersion + "\\bin;" + System.getProperty("java.home") + "\\bin;%path%", "allure serve " + allureResultsFolderPath.substring(0, allureResultsFolderPath.length() - 1), "pause", "exit");
            FileActions.writeToFile("", "generate_allure_report.bat", commandsToServeAllureReport);
        } else {
            // create unix-based sh file
            commandsToServeAllureReport = Arrays.asList("#!/bin/bash", "parent_path=$( cd \"$(dirname \"${BASH_SOURCE[0]}\")\" ; pwd -P )", "cd \"" + allureExtractionLocation + "allure-" + allureVersion + "/bin/\"", "bash allure serve \"$parent_path/" + allureResultsFolderPath.substring(0, allureResultsFolderPath.length() - 1) + "\"", "exit");
            FileActions.writeToFile("", "generate_allure_report.sh", commandsToServeAllureReport);
            // make allure executable on unix-based shells
            (new TerminalActions()).performTerminalCommand("chmod u+x generate_allure_report.sh");
        }
    }

    static Boolean isInternalStep() {
        String callingMethodName = (new Throwable()).getStackTrace()[2].toString();
        return callingMethodName.contains("com.shaft");
    }

    /**
     * Adds a new attachment using the input parameters provided. The attachment is
     * displayed as a step in the execution report. Used for Screenshots.
     *
     * @param attachmentType    the type of this attachment
     * @param attachmentName    the name of this attachment
     * @param attachmentContent the content of this attachment
     */
    @Step("Attachment: {attachmentType} - {attachmentName}")
    static void attachreplacedtep(String attachmentType, String attachmentName, InputStream attachmentContent) {
        createAttachment(attachmentType, attachmentName, attachmentContent);
    }

    private static void writeOpenReportShellFilesToGeneratedDirectory() {
        List<String> commandsToOpenAllureReport;
        // create unix-based sh file
        commandsToOpenAllureReport = Arrays.asList("#!/bin/bash", "parent_path=$( cd \"$(dirname \"${BASH_SOURCE[0]}\")\" ; pwd -P )", "cd \"$parent_path/allure/allure-" + System.getProperty(ALLURE_VERSION_PROPERTY_NAME) + "/bin/\"", "bash allure open \"$parent_path/allure-report\"", "exit");
        FileActions.writeToFile("generatedReport/", "open_allure_report.sh", commandsToOpenAllureReport);
        // create windows batch file
        commandsToOpenAllureReport = Arrays.asList("@echo off", "set path=allure\\allure-" + System.getProperty(ALLURE_VERSION_PROPERTY_NAME) + "\\bin;" + System.getProperty("java.home") + ";%path%", "allure open allure-report", "pause", "exit");
        FileActions.writeToFile("generatedReport/", "open_allure_report.bat", commandsToOpenAllureReport);
    }

    private static void writeAllureReportToGeneratedDirectory() {
        // add correct file extension based on target OS
        String targetOperatingSystem = System.getProperty(TARGET_OS_PROPERTY_NAME);
        String commandToCreateAllureReport;
        allureBinaryPath = allureExtractionLocation + "allure-" + System.getProperty(ALLURE_VERSION_PROPERTY_NAME) + "/bin/allure";
        if (targetOperatingSystem.equals(OS_WINDOWS)) {
            commandToCreateAllureReport = allureBinaryPath + ".bat" + " generate \"" + allureResultsFolderPath.substring(0, allureResultsFolderPath.length() - 1) + "\" -o \"generatedReport/allure-report\"";
        } else {
            commandToCreateAllureReport = allureBinaryPath + " generate \"" + allureResultsFolderPath.substring(0, allureResultsFolderPath.length() - 1) + "\" -o \"generatedReport/allure-report\"";
        }
        (new TerminalActions()).performTerminalCommand(commandToCreateAllureReport);
    }

    private static void createAllureReportArchiveAndCleanGeneratedDirectory() {
        if (FileActions.doesFileExist(allureExtractionLocation)) {
            FileActions.copyFolder(FileActions.getAbsolutePath(allureExtractionLocation), "generatedReport/allure");
            FileActions.zipFiles("generatedReport/", "generatedReport_" + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()) + ".zip");
        }
        FileActions.deleteFile("generatedReport/");
    }

    public static void log(String logText, List<List<Object>> attachments) {
        if (isDiscreteLogging() && !logText.toLowerCase().contains("failed") && isInternalStep()) {
            createLogEntry(logText);
            if (attachments != null) {
                attachments.forEach(attachment -> {
                    if (attachment != null) {
                        if (attachment.get(2) instanceof String) {
                            attachreplacedtep(attachment.get(0).toString(), attachment.get(1).toString(), new ByteArrayInputStream(attachment.get(2).toString().getBytes()));
                        } else {
                            attachreplacedtep(attachment.get(0).toString(), attachment.get(1).toString(), (InputStream) attachment.get(2));
                        }
                    }
                });
            }
        } else {
            writeStepToReport(actionCounter, logText, attachments);
            actionCounter++;
        }
    }

    /**
     * Format an exception message and stack trace, and calls attach to add it as a
     * log entry.
     *
     * @param t the throwable (exception or error) that will be logged in this
     *          action
     */
    public static void log(Throwable t) {
        String logText;
        logText = formatStackTraceToLogEntry(t);
        if (t.getMessage() != null) {
            log("An Exception Occured with this Message: " + t.getMessage().split("\n")[0].trim() + ".", Collections.singletonList(Arrays.asList("Exception Stack Trace", t.getClreplaced().getName(), logText)));
        } else {
            log("An Exception Occured", Collections.singletonList(Arrays.asList("Exception Stack Trace", t.getClreplaced().getName(), logText)));
        }
        actionCounter++;
    }

    public static void logDiscrete(Throwable t) {
        createLogEntry(formatStackTraceToLogEntry(t));
    }
}

17 Source : MyExtentTestNgFormatter.java
with MIT License
from Jsir07

/**
 * Adds a info log message to the node
 *
 * @param logMessage The log message string
 * @param nodeName   The name of the node
 */
public void addInfoLogToNode(String logMessage, String nodeName) {
    ITestResult result = Reporter.getCurrentTestResult();
    Preconditions.checkState(result != null);
    ExtentTest test = (ExtentTest) result.getAttribute(nodeName);
    test.info(logMessage);
}

17 Source : MyExtentTestNgFormatter.java
with MIT License
from Jsir07

public void onStart(ISuite iSuite) {
    if (iSuite.getXmlSuite().getTests().size() > 0) {
        ExtentTest suite = reporter.createTest(iSuite.getName());
        String configFile = iSuite.getParameter("report.config");
        if (!Strings.isNullOrEmpty(configFile)) {
            htmlReporter.loadXMLConfig(configFile);
        }
        String systemInfoCustomImplName = iSuite.getParameter("system.info");
        if (!Strings.isNullOrEmpty(systemInfoCustomImplName)) {
            generateSystemInfo(systemInfoCustomImplName);
        }
        iSuite.setAttribute(REPORTER_ATTR, reporter);
        iSuite.setAttribute(SUITE_ATTR, suite);
    }
}

17 Source : MyExtentTestNgFormatter.java
with MIT License
from Jsir07

private void addNewNode(String parent, String nodeName) {
    ITestResult result = Reporter.getCurrentTestResult();
    Preconditions.checkState(result != null);
    ExtentTest parentNode = (ExtentTest) result.getAttribute(parent);
    ExtentTest childNode = parentNode.createNode(nodeName);
    result.setAttribute(nodeName, childNode);
}

17 Source : MyExtentTestNgFormatter.java
with MIT License
from Jsir07

public void onFinish(ITestContext iTestContext) {
    ExtentTest testContext = (ExtentTest) iTestContext.getAttribute("testContext");
    if (iTestContext.getFailedTests().size() > 0) {
        testContext.fail("Failed");
    } else if (iTestContext.getSkippedTests().size() > 0) {
        testContext.skip("Skipped");
    } else {
        testContext.preplaced("Preplaceded");
    }
}

17 Source : ExtentTestCommons.java
with Apache License 2.0
from extent-framework

public static void replacedignGroups(ExtentTest test, String[] groups) {
    if (groups.length > 0) {
        for (String g : groups) {
            if (g.startsWith("d:") || g.startsWith("device:")) {
                String d = g.replace("d:", "").replace("device:", "");
                test.replacedignDevice(d);
            } else if (g.startsWith("a:") || g.startsWith("author:")) {
                String a = g.replace("a:", "").replace("author:", "");
                test.replacedignAuthor(a);
            } else if (g.startsWith("t:") || g.startsWith("tag:")) {
                String t = g.replace("t:", "").replace("tag:", "");
                test.replacedignCategory(t);
            } else {
                test.replacedignCategory(g);
            }
        }
    }
}

16 Source : ExtentReportsBuilder.java
with MIT License
from prashant-ramcharan

private void addBase64ScreenCapture(ExtentTest node, String base64Image) {
    node.log(Status.INFO, "", MediaEnreplacedyBuilder.createScreenCaptureFromBase64String(base64Image).build());
}

16 Source : ExtentReportsBuilder.java
with MIT License
from prashant-ramcharan

private void addFeatures(ExtentReports extentReports, List<Feature> features) {
    final ExtentTest featureNode = createBddTest(extentReports, features.get(0).getName());
    features.forEach(feature -> {
        if (feature.getScenarios().size() > 1) {
            addFeatureStartAndEndTime(featureNode, feature);
        }
        for (Scenario scenario : feature.getScenarios()) {
            if (scenario.getKeyword().startsWith("Scenario")) {
                addScenario(featureNode, scenario);
                addScenarioStartAndEndTime(featureNode, scenario);
            }
        }
    });
}

16 Source : ExtentReportsBuilder.java
with MIT License
from prashant-ramcharan

private ExtentTest createBddTest(ExtentReports extentReports, String featureName) {
    ExtentTest featureNode = extentReports.createTest(featureName);
    featureNode.getModel().setBddType(com.aventstack.extentreports.gherkin.model.Feature.clreplaced);
    return featureNode;
}

16 Source : ExtentReportsBuilder.java
with MIT License
from prashant-ramcharan

private void addFeatureStartAndEndTime(ExtentTest featureNode, Feature feature) {
    Date featureStartTime = getEarliestStartTime(feature.getScenarios());
    Date featureEndTime = getEndTime(featureStartTime.getTime(), feature.getScenarios());
    addStartAndEndTime(featureNode, featureStartTime, featureEndTime);
}

16 Source : ExtentTestManager.java
with Apache License 2.0
from extent-framework

public static synchronized ExtentTest createMethod(ITestResult result) {
    String methodName = result.getMethod().getMethodName();
    if (result.getParameters().length > 0) {
        if (methodTest.get() != null && methodTest.get().getModel().getName().equals(methodName))
            ;
        else
            createTest(result, null);
        String paramName = Arrays.asList(result.getParameters()).toString();
        ExtentTest paramTest = methodTest.get().createNode(paramName);
        dataProviderTest.set(paramTest);
    } else {
        dataProviderTest.set(null);
        createTest(result, null);
    }
    return methodTest.get();
}

16 Source : GherkinKeywordTest.java
with Apache License 2.0
from extent-framework

@Test
public void testEnglishGherkinKeywords() throws ClreplacedNotFoundException, UnsupportedEncodingException {
    ExtentReports extent = extent();
    extent.setGherkinDialect("en");
    ExtentTest feature = extent.createTest(new GherkinKeyword("Feature"), "Refund item VM");
    ExtentTest scenario = feature.createNode(new GherkinKeyword("Scenario"), "Jeff returns a faulty microwave");
    ExtentTest given = scenario.createNode(new GherkinKeyword("Given"), "Jeff has bought a microwave for $100").skip("skip");
    ExtentTest and = scenario.createNode(new GherkinKeyword("And"), "he has a receipt").preplaced("preplaced");
    ExtentTest when = scenario.createNode(new GherkinKeyword("When"), "he returns the microwave").preplaced("preplaced");
    ExtentTest then = scenario.createNode(new GherkinKeyword("Then"), "Jeff should be refunded $100").skip("skip");
    replacedert.replacedertEquals(feature.getModel().getBddType(), Feature.clreplaced);
    replacedert.replacedertEquals(scenario.getModel().getBddType(), Scenario.clreplaced);
    replacedert.replacedertEquals(given.getModel().getBddType(), Given.clreplaced);
    replacedert.replacedertEquals(and.getModel().getBddType(), And.clreplaced);
    replacedert.replacedertEquals(when.getModel().getBddType(), When.clreplaced);
    replacedert.replacedertEquals(then.getModel().getBddType(), Then.clreplaced);
}

16 Source : GherkinKeywordTest.java
with Apache License 2.0
from extent-framework

@Test
public void testMixedGherkinKeywords() throws UnsupportedEncodingException, ClreplacedNotFoundException {
    ExtentTest and = null, when = null, then = null;
    ExtentReports extent = extent();
    extent.setGherkinDialect("de");
    // the below tests should preplaced since GherkinKeywords are valid German words
    ExtentTest feature = extent.createTest(new GherkinKeyword("Funktionalität"), "Refund item VM");
    ExtentTest scenario = feature.createNode(new GherkinKeyword("Szenario"), "Jeff returns a faulty microwave");
    ExtentTest given = scenario.createNode(new GherkinKeyword("Angenommen"), "Jeff has bought a microwave for $100").skip("skip");
    replacedert.replacedertEquals(feature.getModel().getBddType(), Feature.clreplaced);
    replacedert.replacedertEquals(scenario.getModel().getBddType(), Scenario.clreplaced);
    replacedert.replacedertEquals(given.getModel().getBddType(), Given.clreplaced);
    // all below tests should fail since all GherkinKeywords are not valid German words
    // each ExtentTest object should equal NULL
    try {
        and = scenario.createNode(new GherkinKeyword("And"), "he has a receipt").preplaced("preplaced");
    } catch (ClreplacedNotFoundException e) {
    }
    try {
        when = scenario.createNode(new GherkinKeyword("When"), "he returns the microwave").preplaced("preplaced");
    } catch (ClreplacedNotFoundException e) {
    }
    try {
        then = scenario.createNode(new GherkinKeyword("Then"), "Jeff should be refunded $100").skip("skip");
    } catch (ClreplacedNotFoundException e) {
    }
    replacedert.replacedertEquals(and, null);
    replacedert.replacedertEquals(when, null);
    replacedert.replacedertEquals(then, null);
}

16 Source : GherkinKeywordTest.java
with Apache License 2.0
from extent-framework

@Test
public void testGermanGherkinKeywords() throws ClreplacedNotFoundException, UnsupportedEncodingException {
    ExtentReports extent = extent();
    extent.setGherkinDialect("de");
    ExtentTest feature = extent.createTest(new GherkinKeyword("Funktionalität"), "Refund item VM");
    ExtentTest scenario = feature.createNode(new GherkinKeyword("Szenario"), "Jeff returns a faulty microwave");
    ExtentTest given = scenario.createNode(new GherkinKeyword("Angenommen"), "Jeff has bought a microwave for $100").skip("skip");
    ExtentTest and = scenario.createNode(new GherkinKeyword("Und"), "he has a receipt").preplaced("preplaced");
    ExtentTest when = scenario.createNode(new GherkinKeyword("Wenn"), "he returns the microwave").preplaced("preplaced");
    ExtentTest then = scenario.createNode(new GherkinKeyword("Dann"), "Jeff should be refunded $100").skip("skip");
    replacedert.replacedertEquals(feature.getModel().getBddType(), Feature.clreplaced);
    replacedert.replacedertEquals(scenario.getModel().getBddType(), Scenario.clreplaced);
    replacedert.replacedertEquals(given.getModel().getBddType(), Given.clreplaced);
    replacedert.replacedertEquals(and.getModel().getBddType(), And.clreplaced);
    replacedert.replacedertEquals(when.getModel().getBddType(), When.clreplaced);
    replacedert.replacedertEquals(then.getModel().getBddType(), Then.clreplaced);
}

15 Source : ExtentReportsBuilder.java
with MIT License
from prashant-ramcharan

private void addAdditionalStepDetails(ExtentTest stepNode, Step step) {
    String error = step.getResult().getErrorMessage();
    List<String> output = step.getOutput();
    List<Embedding> embeddings = step.getEmbeddings();
    addOutputs(stepNode, output);
    addError(stepNode, error);
    addImageEmbeddings(stepNode, embeddings);
}

15 Source : ExtentReportsBuilder.java
with MIT License
from prashant-ramcharan

private ExtentTest createStepNode(ExtentTest scenarioNode, Step step, Date startTime) {
    ExtentTest stepNode = createGherkinNode(scenarioNode, step.getKeyword().trim(), step.getName(), true);
    stepNode.getModel().setStartTime(startTime);
    return stepNode;
}

14 Source : ExtentReportsBuilder.java
with MIT License
from prashant-ramcharan

private void addScenario(ExtentTest featureNode, Scenario scenario) {
    final ExtentTest scenarioNode = createGherkinNode(featureNode, "Scenario", scenario.getName(), false);
    addBeforeOrAfterDetails(scenarioNode, scenario.getBefore());
    addSteps(scenarioNode, scenario);
    addBeforeOrAfterDetails(scenarioNode, scenario.getAfter());
    replacedignCategoryToScenario(scenarioNode, scenario.getTags());
}

14 Source : ExtentReportsBuilder.java
with MIT License
from prashant-ramcharan

private void addSteps(ExtentTest scenarioNode, Scenario scenario) {
    Date startTime = getStartTime(scenario.getStartTimestamp());
    List<Step> steps = scenario.getSteps();
    steps.forEach(step -> {
        addBeforeOrAfterDetails(scenarioNode, step.getBefore());
        ExtentTest stepNode = createStepNode(scenarioNode, step, startTime);
        addAdditionalStepDetails(stepNode, step);
        setStepResult(stepNode, step);
        addBeforeOrAfterDetails(scenarioNode, step.getAfter());
    });
}

14 Source : ExtentReportsBuilder.java
with MIT License
from prashant-ramcharan

private void addScenarioStartAndEndTime(ExtentTest scenarioNode, Scenario scenario) {
    List<Scenario> scenarios = new ArrayList<>();
    scenarios.add(scenario);
    Date scenarioStartTime = getStartTime(scenario.getStartTimestamp());
    Date scenarioEndTime = getEndTime(scenarioStartTime.getTime(), scenarios);
    addStartAndEndTime(scenarioNode, scenarioStartTime, scenarioEndTime);
}

14 Source : ExtentReportsBuilder.java
with MIT License
from prashant-ramcharan

private void setStepResult(ExtentTest extentTest, Step step) {
    if (step.skipped()) {
        extentTest.skip("");
    } else if (step.preplaceded()) {
        extentTest.preplaced("");
    } else {
        extentTest.fail("");
    }
}

14 Source : MyExtentTestNgFormatter.java
with MIT License
from Jsir07

public void afterInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {
    if (iInvokedMethod.isTestMethod()) {
        ExtentTest test = (ExtentTest) iTestResult.getAttribute("test");
        List<String> logs = Reporter.getOutput(iTestResult);
        for (String log : logs) {
            test.info(log);
        }
        int status = iTestResult.getStatus();
        if (ITestResult.SUCCESS == status) {
            test.preplaced("Preplaceded");
        } else if (ITestResult.FAILURE == status) {
            test.fail(iTestResult.getThrowable());
        } else {
            test.skip("Skipped");
        }
        for (String group : iInvokedMethod.getTestMethod().getGroups()) {
            test.replacedignCategory(group);
        }
    }
}

14 Source : RawEntityConverter.java
with Apache License 2.0
from extent-framework

private void addMedia(Log log, ExtentTest extentTest, Throwable ex) {
    Media m = log.getMedia();
    if (m.getPath() != null) {
        extentTest.log(log.getStatus(), ex, MediaEnreplacedyBuilder.createScreenCaptureFromPath(m.getPath()).build());
    } else if (((ScreenCapture) m).getBase64() != null) {
        extentTest.log(log.getStatus(), ex, MediaEnreplacedyBuilder.createScreenCaptureFromBase64String(((ScreenCapture) m).getBase64()).build());
    }
}

14 Source : RawEntityConverter.java
with Apache License 2.0
from extent-framework

private void addMedia(Test test, ExtentTest extentTest) {
    if (test.getMedia() != null) {
        for (Media m : test.getMedia()) {
            if (m.getPath() != null) {
                extentTest.addScreenCaptureFromPath(m.getPath());
            } else if (m instanceof ScreenCapture) {
                extentTest.addScreenCaptureFromBase64String(((ScreenCapture) m).getBase64());
            }
        }
    }
}

13 Source : ExtentTestManager.java
with Apache License 2.0
from extent-framework

public static synchronized ExtentTest createMethod(ITestResult result, Boolean createAsChild) {
    if (!createAsChild)
        return createMethod(result);
    String clreplacedName = result.getInstance().getClreplaced().getSimpleName();
    String methodName = result.getMethod().getMethodName();
    String desc = result.getMethod().getDescription();
    ExtentTest clreplacedTest;
    if (clreplacedTestMap.containsKey(clreplacedName)) {
        clreplacedTest = clreplacedTestMap.get(clreplacedName);
    } else {
        clreplacedTest = ExtentService.getInstance().createTest(clreplacedName, desc);
        clreplacedTestMap.put(clreplacedName, clreplacedTest);
    }
    if (result.getParameters().length > 0) {
        boolean anyMatch = clreplacedTest.getModel().getChildren().stream().anyMatch(x -> x.getName().equals(methodName));
        if (!anyMatch)
            createTest(result, clreplacedTest);
        String paramName = Arrays.asList(result.getParameters()).toString();
        ExtentTest paramTest = methodTest.get().createNode(paramName);
        dataProviderTest.set(paramTest);
    } else {
        dataProviderTest.set(null);
        createTest(result, clreplacedTest);
    }
    return methodTest.get();
}

13 Source : RawEntityConverter.java
with Apache License 2.0
from extent-framework

public void convertAndApply(File jsonFile) throws IOException {
    if (!jsonFile.exists())
        return;
    extent.setReportUsesManualConfiguration(true);
    List<Test> tests = new JsonDeserializer(jsonFile).deserialize();
    for (Test test : tests) {
        try {
            if (test.getBddType() == null) {
                createDomain(test, extent.createTest(test.getName(), test.getDescription()));
            } else {
                ExtentTest extentTest = extent.createTest(new GherkinKeyword(test.getBddType().getSimpleName()), test.getName(), test.getDescription());
                createDomain(test, extentTest);
            }
        } catch (ClreplacedNotFoundException e) {
            e.printStackTrace();
        }
    }
}

12 Source : ExtentCucumberAdapter.java
with Apache License 2.0
from extent-framework

private synchronized void createTestCase(TestCase testCase) {
    TestSourcesModel.AstNode astNode = testSources.getAstNode(currentFeatureFile.get(), testCase.getLine());
    if (astNode != null) {
        ScenarioDefinition scenarioDefinition = TestSourcesModel.getScenarioDefinition(astNode);
        ExtentTest parent = scenarioOutlineThreadLocal.get() != null ? scenarioOutlineThreadLocal.get() : featureTestThreadLocal.get();
        ExtentTest t = parent.createNode(com.aventstack.extentreports.gherkin.model.Scenario.clreplaced, scenarioDefinition.getName(), scenarioDefinition.getDescription());
        scenarioThreadLocal.set(t);
    }
    if (!testCase.getTags().isEmpty()) {
        testCase.getTags().stream().map(PickleTag::getName).forEach(scenarioThreadLocal.get()::replacedignCategory);
    }
}

11 Source : ExtentTestNGIReporterListener.java
with MIT License
from PacktPublishing

/**
 * processTestResults method to create report
 *
 * @param r
 * @throws Exception
 */
private void processTestResults(ISuiteResult r) throws Exception {
    ExtentTest test = null;
    Status status = null;
    String message = null;
    // gather results
    Set<ITestResult> preplaceded = r.getTestContext().getPreplacededTests().getAllResults();
    Set<ITestResult> failed = r.getTestContext().getFailedTests().getAllResults();
    Set<ITestResult> skipped = r.getTestContext().getSkippedTests().getAllResults();
    Set<ITestResult> configs = r.getTestContext().getFailedConfigurations().getAllResults();
    Set<ITestResult> tests = new HashSet<ITestResult>();
    tests.addAll(preplaceded);
    tests.addAll(skipped);
    tests.addAll(failed);
    // process results
    if (tests.size() > 0) {
        // sort results by the Date field
        List<ITestResult> resultList = new LinkedList<ITestResult>(tests);
        clreplaced ResultComparator implements Comparator<ITestResult> {

            public int compare(ITestResult r1, ITestResult r2) {
                return getTime(r1.getStartMillis()).compareTo(getTime(r2.getStartMillis()));
            }
        }
        Collections.sort(resultList, new ResultComparator());
        for (ITestResult result : resultList) {
            if (getTestParams(result).isEmpty()) {
                test = extent.createTest(result.getMethod().getMethodName());
            } else {
                if (getTestParams(result).split(",")[0].contains(result.getMethod().getMethodName())) {
                    test = extent.createTest(getTestParams(result).split(",")[0], getTestParams(result).split(",")[1]);
                } else {
                    test = extent.createTest(result.getMethod().getMethodName(), getTestParams(result).split(",")[1]);
                }
            }
            test.getModel().setStartTime(getTime(result.getStartMillis()));
            test.getModel().setEndTime(getTime(result.getEndMillis()));
            for (String group : result.getMethod().getGroups()) {
                if (!group.isEmpty()) {
                    test.replacedignCategory(group);
                } else {
                    int size = result.getMethod().getTestClreplaced().toString().split("\\.").length;
                    String testName = result.getMethod().getRealClreplaced().getName().toString().split("\\.")[size - 1];
                    test.replacedignCategory(testName);
                }
            }
            // get status
            switch(result.getStatus()) {
                case 1:
                    status = Status.Preplaced;
                    break;
                case 2:
                    status = Status.FAIL;
                    break;
                case 3:
                    status = Status.SKIP;
                    break;
                default:
                    status = Status.INFO;
                    break;
            }
            // set colors of status
            if (status.equals(Status.Preplaced)) {
                message = "<font color=#00af00>" + status.toString().toUpperCase() + "</font>";
            } else if (status.equals(Status.FAIL)) {
                message = "<font color=#F7464A>" + status.toString().toUpperCase() + "</font>";
            } else if (status.equals(Status.SKIP)) {
                message = "<font color=#2196F3>" + status.toString().toUpperCase() + "</font>";
            } else {
                message = "<font color=black>" + status.toString().toUpperCase() + "</font>";
            }
            // log status in report
            test.log(status, message);
            if (!getTestParams(result).isEmpty()) {
                test.log(Status.INFO, "TEST DATA = [" + getTestParams(result) + "]");
            }
            if (result.getThrowable() != null) {
                test.log(Status.INFO, "EXCEPTION = [" + result.getThrowable().getMessage() + "]");
                if (!getTestParams(result).isEmpty()) {
                    // must capture screenshot to include in report
                    if (result.getAttribute("testBitmap") != null) {
                        test.log(Status.INFO, "SCREENSHOT", MediaEnreplacedyBuilder.createScreenCaptureFromPath(bitmapDir + result.getAttribute("testBitmap")).build());
                    }
                    test.log(Status.INFO, "STACKTRACE" + getStrackTrace(result));
                }
            }
        }
    }
}

11 Source : ReportEntityTest.java
with Apache License 2.0
from extent-framework

@org.testng.annotations.Test
public void deviceCtx() {
    ExtentReports extent = extent();
    ExtentTest test = extent.createTest("Test");
    NamedAttributeContextManager<Device> context = extent.getReport().getDeviceCtx();
    replacedert.replacedertFalse(context.hasItems());
    test.replacedignDevice("x");
    replacedert.replacedertTrue(context.hasItems());
    replacedert.replacedertTrue(context.getSet().stream().anyMatch(x -> x.getAttr().getName().equals("x")));
    replacedert.replacedertTrue(context.getSet().stream().anyMatch(x -> x.getTestList().size() == 1));
    replacedert.replacedertTrue(context.getSet().stream().flatMap(x -> x.getTestList().stream()).anyMatch(x -> x.getName().equals("Test")));
}

11 Source : ExtentCucumberAdapter.java
with Apache License 2.0
from extent-framework

private synchronized void handleEmbed(EmbedEvent event) {
    String mimeType = event.mimeType;
    String extension = MIME_TYPES_EXTENSIONS.get(mimeType);
    if (extension != null) {
        StringBuilder fileName = new StringBuilder("embedded").append(EMBEDDED_INT.incrementAndGet()).append(".").append(extension);
        try {
            URL url = toUrl(fileName.toString());
            writeBytesToURL(event.data, url);
            try {
                File f = new File(url.toURI());
                if (stepTestThreadLocal.get() == null) {
                    ExtentTest t = scenarioThreadLocal.get().createNode(Asterisk.clreplaced, "Embed");
                    stepTestThreadLocal.set(t);
                }
                stepTestThreadLocal.get().info("", MediaEnreplacedyBuilder.createScreenCaptureFromPath(screenshotRelPath + f.getName()).build());
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

See More Examples