How to use ReporterException class of com.paypal.selion.internal.reports.html package

Best SeLion code snippet using com.paypal.selion.internal.reports.html.ReporterException

Source:HtmlReporterListener.java Github

copy

Full Screen

...84 try {85 ve.init();86 } catch (Exception e) { // catching exception because thats what is87 // mentioned as being thrown88 ReporterException re = new ReporterException(e);89 throw re;90 }91 statusMap.put(ITestResult.SUCCESS, "passed");92 statusMap.put(ITestResult.FAILURE, "failed");93 statusMap.put(ITestResult.SKIP, "skipped");94 }95 @Override96 public void generateReport(List<XmlSuite> xmlSuite, List<ISuite> suites, String outputDir) {97 logger.entering(new Object[] { xmlSuite, suites, outputDir });98 if (ListenerManager.isCurrentMethodSkipped(this)) {99 logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG);100 return;101 }102 this.outputDir = outputDir;103 ReportDataGenerator.initReportData(suites);104 out = createWriter(outputDir);105 startHtml(out);106 List<Line> lines = createSummary(suites);107 createDetail(lines);108 createMethodContent(suites, outputDir);109 endHtml(out);110 out.flush();111 out.close();112 logger.exiting();113 }114 115 private void createDetail(List<Line> lines) {116 logger.entering(lines);117 for (Line line : lines) {118 createContent(line);119 }120 logger.exiting();121 }122 private void createContent(Line line) {123 logger.entering(line);124 try {125 File f = new File(outputDir + "/html/", line.getId() + ".html");126 logger.fine("generating method " + f.getAbsolutePath());127 Writer fileSystemWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(128 new FileOutputStream(f), "UTF8")));129 Map<ITestNGMethod, List<ITestResult>> resultByMethod = new HashMap<ITestNGMethod, List<ITestResult>>();130 // find all methods131 for (ITestResult result : line.getAssociatedResults()) {132 List<ITestResult> list = resultByMethod.get(result.getMethod());133 if (list == null) {134 list = new ArrayList<ITestResult>();135 resultByMethod.put(result.getMethod(), list);136 }137 list.add(result);138 }139 // for each method, find all the status140 for (Entry<ITestNGMethod, List<ITestResult>> method : resultByMethod.entrySet()) {141 List<ITestResult> passed = new ArrayList<ITestResult>();142 List<ITestResult> failed = new ArrayList<ITestResult>();143 List<ITestResult> skipped = new ArrayList<ITestResult>();144 List<ITestResult> results = method.getValue();145 for (ITestResult result : results) {146 switch (result.getStatus()) {147 case ITestResult.SUCCESS:148 passed.add(result);149 break;150 case ITestResult.FAILURE:151 failed.add(result);152 break;153 case ITestResult.SKIP:154 skipped.add(result);155 break;156 default:157 throw new ReporterException(158 "Implementation exists only for tests with status as : Success, Failure and Skipped");159 }160 }161 // for each status // method, create the html162 if (passed.size() > 0) {163 Template t = ve.getTemplate("/templates/method.part.html");164 VelocityContext context = new VelocityContext();165 context.put("status", "passed");166 context.put("method", passed.get(0).getMethod());167 StringBuilder buff = new StringBuilder();168 for (ITestResult result : passed) {169 buff.append(getContent(result));170 }171 context.put("content", buff.toString());172 StringWriter writer = new StringWriter();173 t.merge(context, writer);174 fileSystemWriter.write(writer.toString());175 }176 if (failed.size() > 0) {177 Template t = ve.getTemplate("/templates/method.part.html");178 VelocityContext context = new VelocityContext();179 context.put("status", "failed");180 context.put("method", failed.get(0).getMethod());181 StringBuilder buff = new StringBuilder();182 for (ITestResult result : failed) {183 buff.append(getContent(result));184 }185 context.put("content", buff.toString());186 StringWriter writer = new StringWriter();187 t.merge(context, writer);188 fileSystemWriter.write(writer.toString());189 }190 if (skipped.size() > 0) {191 Template t = ve.getTemplate("/templates/method.part.html");192 VelocityContext context = new VelocityContext();193 context.put("status", "skipped");194 context.put("method", skipped.get(0).getMethod());195 StringBuilder buff = new StringBuilder();196 for (ITestResult result : skipped) {197 buff.append(getContent(result));198 }199 context.put("content", buff.toString());200 StringWriter writer = new StringWriter();201 t.merge(context, writer);202 fileSystemWriter.write(writer.toString());203 }204 }205 fileSystemWriter.flush();206 fileSystemWriter.close();207 } catch (Exception e) {208 ReporterException re = new ReporterException(e);209 throw re;210 }211 logger.exiting();212 }213 private void createMethodContent(List<ISuite> suites, String outdir) {214 logger.entering(new Object[] { suites, outdir });215 for (ISuite suite : suites) {216 Map<String, ISuiteResult> r = suite.getResults();217 for (ISuiteResult r2 : r.values()) {218 ITestContext ctx = r2.getTestContext();219 ITestNGMethod[] methods = ctx.getAllTestMethods();220 for (int i = 0; i < methods.length; i++) {221 createMethod(ctx, methods[i], outdir);222 }223 }224 }225 logger.exiting();226 }227 private String getContent(ITestResult result) {228 logger.entering(result);229 StringBuilder contentBuffer = new StringBuilder();230 contentBuffer.append(String.format("Total duration of this instance run : %02d sec. ",231 (result.getEndMillis() - result.getStartMillis()) / 1000));232 Object[] parameters = result.getParameters();233 boolean hasParameters = parameters != null && parameters.length > 0;234 List<String> msgs = Reporter.getOutput(result);235 boolean hasReporterOutput = msgs.size() > 0;236 Throwable exception = result.getThrowable();237 boolean hasThrowable = exception != null;238 List<String> imgForFilmStrip = new ArrayList<String>();239 if (hasReporterOutput || hasThrowable) {240 if (hasParameters) {241 contentBuffer.append("<h2 class='yuk_grey_midpnl_ltitle'>");242 for (int i = 0; i < parameters.length; i++) {243 Object p = parameters[i];244 String paramAsString = "null";245 if (p != null) {246 paramAsString = p.toString() + "<i>(" + p.getClass().getSimpleName() + ")</i> , ";247 }248 contentBuffer.append(paramAsString);249 }250 contentBuffer.append("</h2>");251 }252 if (hasReporterOutput || hasThrowable) {253 contentBuffer.append("<div class='leftContent' style='float: left; width: 70%;'>");254 contentBuffer.append("<h3>Test Log</h3>");255 for (String line : msgs) {256 BaseLog logLine = new BaseLog(line);257 if (logLine.getScreen() != null) {258 imgForFilmStrip.add(logLine.getScreenURL());259 }260 String htmllog = logLine.getMsg();261 // Attaching ralogId to each of the page title.262 if ((logLine.getHref() != null) && (logLine.getHref().length() > 1)) {263 htmllog = "<a href='../" + logLine.getHref() + "' title='" + logLine.getLocation() + "' >"264 + (StringUtils.isNotEmpty(htmllog) ? htmllog : "Page Source") + "</a>";265 266 }267 // Don't output blank message w/o any Href.268 if ((logLine.getHref() != null) || logLine.getMsg() != null && !logLine.getMsg().isEmpty()) {269 contentBuffer.append(htmllog);270 contentBuffer.append("<br/>");271 }272 }273 if (hasThrowable) {274 generateExceptionReport(exception, result.getMethod(), contentBuffer);275 }276 }277 contentBuffer.append("</div>"); // end of278 // leftContent279 contentBuffer.append("<div class='filmStripContainer' style='float: right; width: 100%;'>");280 contentBuffer.append("<b>Preview</b>");281 contentBuffer.append("<div class=\"filmStrip\">");282 contentBuffer.append("<ul>");283 for (String imgPath : imgForFilmStrip) {284 contentBuffer.append("<li>");285 contentBuffer.append("<a href=\"../" + imgPath + "\" > <img src=\"../" + imgPath286 + "\" width=\"200\" height=\"200\" /> </a>");287 contentBuffer.append("</li>");288 }289 contentBuffer.append("</ul>");290 contentBuffer.append("</div>");291 contentBuffer.append("</div>");292 }293 contentBuffer.append("<div class='clear_both'></div>");294 // Not logging the return value, because it will clog the logs295 logger.exiting();296 return contentBuffer.toString();297 }298 protected void generateExceptionReport(Throwable exception, ITestNGMethod method, StringBuilder contentBuffer) {299 logger.entering(new Object[] { exception, method, contentBuffer });300 Throwable fortile = exception;301 String title = fortile.getMessage();302 if (title == null) {303 title = "Encountered problems when attempting to extract a meaningful Root cause.";304 if (fortile.getCause() != null && !fortile.getCause().getMessage().trim().isEmpty()) {305 title = fortile.getCause().getMessage();306 }307 }308 generateExceptionReport(exception, method, title, contentBuffer);309 logger.exiting();310 }311 private void generateExceptionReport(Throwable exception, ITestNGMethod method, String title,312 StringBuilder contentBuffer) {313 generateTheStackTrace(exception, method, title, contentBuffer);314 }315 private void generateTheStackTrace(Throwable exception, ITestNGMethod method, String title,316 StringBuilder contentBuffer) {317 logger.entering(new Object[] { exception, method, title, contentBuffer });318 contentBuffer.append(" <div class='stContainer' >" + exception.getClass() + ":" + title// escape(title)319 + "<a class='exceptionlnk' href='#'>(+)</a>");320 contentBuffer.append("<div class='exception' style='display:none'>");321 StackTraceElement[] s1 = exception.getStackTrace();322 Throwable t2 = exception.getCause();323 if ((t2 != null) && (t2.equals(exception))) {324 t2 = null;325 }326 for (int x = 0; x < s1.length; x++) {327 contentBuffer.append((x > 0 ? "<br/>at " : "") + escape(s1[x].toString()));328 }329 if (t2 != null) {330 generateExceptionReport(t2, method, "Caused by " + t2.getLocalizedMessage(), contentBuffer);331 }332 contentBuffer.append("</div></div>");333 logger.exiting();334 }335 private static String escape(String string) {336 if (null == string) {337 return string;338 }339 return string.replaceAll("<", "&lt;").replaceAll(">", "&gt;");340 }341 private void createMethod(ITestContext ctx, ITestNGMethod method, String outdir) {342 logger.entering(new Object[] { ctx, method, outdir });343 try {344 File f = new File(outdir + "/html/", method.getId() + ".html");345 logger.fine("generating method " + f.getAbsolutePath());346 Writer fileSystemWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(347 new FileOutputStream(f), "UTF8")));348 Template t = ve.getTemplate("/templates/method.part.html");349 Set<ITestResult> passed = ctx.getPassedTests().getResults(method);350 for (ITestResult result : passed) {351 VelocityContext context = new VelocityContext();352 context.put("method", method);353 context.put("status", "passed");354 context.put("result", result);355 context.put("content", getContent(result));356 StringWriter writer = new StringWriter();357 t.merge(context, writer);358 fileSystemWriter.write(writer.toString());359 }360 Set<ITestResult> failed = ctx.getFailedTests().getResults(method);361 for (ITestResult result : failed) {362 VelocityContext context = new VelocityContext();363 context.put("method", method);364 context.put("status", "failed");365 context.put("result", result);366 context.put("content", getContent(result));367 StringWriter writer = new StringWriter();368 t.merge(context, writer);369 fileSystemWriter.write(writer.toString());370 }371 Set<ITestResult> skipped = ctx.getSkippedTests().getResults(method);372 for (ITestResult result : skipped) {373 VelocityContext context = new VelocityContext();374 context.put("method", method);375 context.put("status", "skipped");376 context.put("result", result);377 context.put("content", getContent(result));378 StringWriter writer = new StringWriter();379 t.merge(context, writer);380 fileSystemWriter.write(writer.toString());381 }382 fileSystemWriter.flush();383 fileSystemWriter.close();384 } catch (Exception e) { // catching exception because velocity throws385 // that and we can't change it386 ReporterException re = new ReporterException(e);387 throw re;388 }389 logger.exiting();390 }391 private List<Line> createSummary(List<ISuite> suites) {392 logger.entering(suites);393 try {394 Template t = ve.getTemplate("/templates/summaryTabs.part.html");395 VelocityContext context = new VelocityContext();396 List<GroupingView> views = new ArrayList<GroupingView>();397 GroupingView view = new GroupingView("managerView", "per class", "Overview organized per class", ve,398 suites, new ByClassSplitter());399 views.add(view);400 GroupingView view2 = new GroupingView("managerView2", "per package", "Overview organized per package", ve,401 suites, new ByPackageSplitter());402 views.add(view2);403 GroupingView view3 = new GroupingView("managerView3", "per method", "Overview organized per method", ve,404 suites, new ByMethodSplitter());405 views.add(view3);406 GroupingView view9 = new GroupingView("managerView9", "per testName", "Overview organized per testName",407 ve, suites, new ByTestNameSplitter());408 views.add(view9);409 /*********************************/410 Filter f2 = new StateFilter(ITestResult.FAILURE);411 GroupingView view6 = new GroupingView("managerView6", "failed methods only",412 "Overview organized per failed methods", ve, suites, new ByMethodSplitter(), f2);413 views.add(view6);414 GroupingView view7 = new GroupingView("managerView7", "per group", "Overview organized per group", ve,415 suites, new ByGroupSplitter());416 views.add(view7);417 context.put("views", views);418 StringWriter writer = new StringWriter();419 t.merge(context, writer);420 out.write(writer.toString());421 List<Line> lines = new ArrayList<Line>();422 for (GroupingView v : views) {423 for (Line line : v.getSplitter().getLines().values()) {424 lines.add(line);425 }426 }427 logger.exiting(lines);428 return lines;429 } catch (Exception e) {430 ReporterException re = new ReporterException("Error occurred while generating report summary", e);431 throw re;432 }433 }434 /** Starts HTML stream */435 protected void startHtml(PrintWriter out) {436 logger.entering(out);437 try {438 Template t = ve.getTemplate("/templates/header.part.html");439 VelocityContext context = new VelocityContext();440 StringBuilder output = new StringBuilder();441 for (Entry<String, String> temp : ConfigSummaryData.getConfigSummary().entrySet()) {442 Entry<String, String> formattedTemp = ReporterDateFormatter.formatReportDataForBrowsableReports(temp);443 output.append(formattedTemp.getKey()).append(" : <b>").append(formattedTemp.getValue()).append("</b><br>");444 }445 context.put("configSummary", output.toString());446 StringWriter writer = new StringWriter();447 t.merge(context, writer);448 out.write(writer.toString());449 } catch (Exception e) {450 logger.log(Level.SEVERE, e.getMessage(), e);451 }452 logger.exiting();453 }454 private void endHtml(PrintWriter out) {455 logger.entering(out);456 try {457 Template t = ve.getTemplate("/templates/footer.part.html");458 VelocityContext context = new VelocityContext();459 StringWriter writer = new StringWriter();460 t.merge(context, writer);461 out.write(writer.toString());462 } catch (Exception e) {463 ReporterException re = new ReporterException(e);464 throw re;465 }466 logger.exiting();467 }468 protected PrintWriter createWriter(String outdir) {469 logger.entering(outdir);470 File f = new File(outdir + "/html/", "report.html");471 if (f.exists()) {472 Format formatter = new SimpleDateFormat("MM-dd-yyyy-HH-mm");473 String currentDate = formatter.format(new Date());474 f.renameTo(new File(outdir + "/html/", "report-" + currentDate + ".html")); // NOSONAR475 }476 logger.info("generating report " + f.getAbsolutePath());477 try {478 PrintWriter pw = new PrintWriter(479 new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF8")));480 logger.exiting(pw);481 return pw;482 } catch (Exception e) {483 ReporterException re = new ReporterException(e);484 throw re;485 }486 }487 @Override488 public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {489 try {490 if (ListenerManager.isCurrentMethodSkipped(this)) {491 logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG);492 return;493 }494 Test testMethod = method.getTestMethod().getConstructorOrMethod().getMethod().getAnnotation(Test.class);495 if (testMethod != null) {496 String testName = testMethod.testName();497 if (StringUtils.isNotEmpty(testName)) {...

Full Screen

Full Screen

Source:JsonRuntimeReporterHelper.java Github

copy

Full Screen

...37import com.google.gson.JsonParseException;38import com.google.gson.JsonParser;39import com.paypal.selion.configuration.Config;40import com.paypal.selion.configuration.Config.ConfigProperty;41import com.paypal.selion.internal.reports.html.ReporterException;42import com.paypal.selion.internal.reports.services.ReporterDateFormatter;43import com.paypal.selion.logger.SeLionLogger;44import com.paypal.selion.reports.services.ConfigSummaryData;45import com.paypal.selion.reports.services.ReporterConfigMetadata;46import com.paypal.test.utilities.logging.SimpleLogger;47/**48 * JsonRuntimeReporterHelper will provide methods to create JSON file which contains information about list of test49 * methods and configuration methods executed with their corresponding status.50 * 51 */52public class JsonRuntimeReporterHelper {53 public static final String IS_COMPLETED = "isCompleted";54 private static final int ONE_MINUTE = 60000;55 private static final String AFTER_METHOD = "AfterMethod";56 private static final String AFTER_CLASS = "AfterClass";57 private static final String AFTER_GROUP = "AfterGroup";58 private static final String AFTER_TEST = "AfterTest";59 private static final String AFTER_SUITE = "AfterSuite";60 private static final String BEFORE_METHOD = "BeforeMethod";61 private static final String BEFORE_CLASS = "BeforeClass";62 private static final String BEFORE_GROUP = "BeforeGroup";63 private static final String BEFORE_TEST = "BeforeTest";64 private static final String BEFORE_SUITE = "BeforeSuite";65 private final List<TestMethodInfo> runningTest = new ArrayList<TestMethodInfo>();;66 private final List<ConfigMethodInfo> runningConfig = new ArrayList<ConfigMethodInfo>();67 private List<TestMethodInfo> completedTest = new ArrayList<TestMethodInfo>();68 private File jsonCompletedTest;69 private File jsonCompletedConfig;70 private final JsonArray testJsonLocalConfigSummary = new JsonArray();71 private JsonObject jsonConfigSummary;72 private long previousTime;73 private static SimpleLogger logger = SeLionLogger.getLogger();74 public JsonRuntimeReporterHelper() {75 try {76 File workingDir = new File(Config.getConfigProperty(ConfigProperty.WORK_DIR));77 boolean isCreated = workingDir.mkdirs();78 logger.log(Level.FINER, "Working directory created successfully: " + isCreated);79 jsonCompletedTest = File.createTempFile("selion-rrct", null, workingDir);80 jsonCompletedTest.deleteOnExit();81 jsonCompletedConfig = File.createTempFile("selion-rrcf", null, workingDir);82 jsonCompletedConfig.deleteOnExit();83 } catch (IOException e) {84 logger.log(Level.SEVERE, e.getMessage(), e);85 throw new ReporterException(e);86 }87 }88 /**89 * This method will generate Configuration summary by fetching the details from ReportDataGenerator90 */91 private JsonObject generateConfigSummary() throws JsonParseException {92 logger.entering();93 if (jsonConfigSummary == null) {94 jsonConfigSummary = new JsonObject();95 for (Entry<String, String> temp : ConfigSummaryData.getConfigSummary().entrySet()) {96 jsonConfigSummary.addProperty(temp.getKey(), temp.getValue());97 }98 }99 logger.exiting(jsonConfigSummary);100 return jsonConfigSummary;101 }102 /**103 * This method will generate local Configuration summary by fetching the details from ReportDataGenerator104 * 105 * @param suiteName106 * suite name of the test method.107 * @param testName108 * test name of the test method.109 */110 public void generateLocalConfigSummary(String suiteName, String testName) {111 logger.entering(new Object[] { suiteName, testName });112 try {113 Map<String, String> testLocalConfigValues = ConfigSummaryData.getLocalConfigSummary(testName);114 JsonObject json = new JsonObject();115 if (testLocalConfigValues == null) {116 json.addProperty(ReporterDateFormatter.CURRENTDATE, ReporterDateFormatter.getISO8601String(new Date()));117 } else {118 for (Entry<String, String> temp : testLocalConfigValues.entrySet()) {119 json.addProperty(temp.getKey(), temp.getValue());120 }121 }122 json.addProperty("suite", suiteName);123 json.addProperty("test", testName);124 // Sometimes json objects getting null value when data provider parallelism enabled125 // To solve this added synchronized block126 synchronized (this) {127 this.testJsonLocalConfigSummary.add(json);128 }129 } catch (JsonParseException e) {130 logger.log(Level.SEVERE, e.getMessage(), e);131 throw new ReporterException(e);132 }133 logger.exiting();134 }135 /**136 * This method is used to insert test method details based on the methods suite, test, groups and class name.137 * 138 * @param suite139 * suite name of the test method.140 * @param test141 * test name of the test method.142 * @param packages143 * group name of the test method. If the test method doesn't belong to any group then we should pass144 * null.145 * @param classname146 * class name of the test method.147 * @param result148 * ITestResult instance of the test method.149 */150 public synchronized void insertTestMethod(String suite, String test, String packages, String classname,151 ITestResult result) {152 logger.entering(new Object[] { suite, test, packages, classname, result });153 TestMethodInfo test1 = new TestMethodInfo(suite, test, packages, classname, result);154 if (result.getStatus() == ITestResult.STARTED) {155 runningTest.add(test1);156 return;157 }158 for (TestMethodInfo temp : runningTest) {159 if (temp.getResult().getMethod().equals(result.getMethod())) {160 runningTest.remove(temp);161 break;162 }163 }164 completedTest.add(test1);165 logger.exiting();166 }167 private void appendFile(File file, String data) {168 logger.entering(new Object[] { file, data });169 try {170 FileUtils.writeStringToFile(file, data, "UTF-8", true);171 } catch (IOException e) {172 logger.log(Level.SEVERE, e.getMessage(), e);173 throw new ReporterException(e);174 }175 logger.exiting();176 }177 /**178 * This method is used to insert configuration method details based on the suite, test, groups and class name.179 * 180 * @param suite181 * suite name of the configuration method.182 * @param test183 * test name of the configuration method.184 * @param packages185 * group name of the configuration method. If the configuration method doesn't belong to any group then186 * we should pass null.187 * @param classname188 * class name of the configuration method.189 * @param result190 * ITestResult instance of the configuration method.191 */192 public synchronized void insertConfigMethod(String suite, String test, String packages, String classname,193 ITestResult result) {194 logger.entering(new Object[] { suite, test, packages, classname, result });195 String type = null;196 if (result.getMethod().isBeforeSuiteConfiguration()) {197 type = BEFORE_SUITE;198 } else if (result.getMethod().isBeforeTestConfiguration()) {199 type = BEFORE_TEST;200 } else if (result.getMethod().isBeforeGroupsConfiguration()) {201 type = BEFORE_GROUP;202 } else if (result.getMethod().isBeforeClassConfiguration()) {203 type = BEFORE_CLASS;204 } else if (result.getMethod().isBeforeMethodConfiguration()) {205 type = BEFORE_METHOD;206 } else if (result.getMethod().isAfterSuiteConfiguration()) {207 type = AFTER_SUITE;208 } else if (result.getMethod().isAfterTestConfiguration()) {209 type = AFTER_TEST;210 } else if (result.getMethod().isAfterGroupsConfiguration()) {211 type = AFTER_GROUP;212 } else if (result.getMethod().isAfterClassConfiguration()) {213 type = AFTER_CLASS;214 } else if (result.getMethod().isAfterMethodConfiguration()) {215 type = AFTER_METHOD;216 }217 ConfigMethodInfo config1 = new ConfigMethodInfo(suite, test, packages, classname, type, result);218 if (result.getStatus() == ITestResult.STARTED) {219 runningConfig.add(config1);220 return;221 }222 for (ConfigMethodInfo temp : runningConfig) {223 if (temp.getResult().getMethod().equals(result.getMethod())) {224 runningConfig.remove(temp);225 break;226 }227 }228 appendFile(jsonCompletedConfig, config1.toJson().concat(",\n"));229 logger.exiting();230 }231 /**232 * Generate the final report.json from the completed test and completed configuration temporary files.233 * 234 * @param outputDirectory235 * output directory236 * @param bForceWrite237 * setting true will forcibly generate the report.json238 */239 public synchronized void writeJSON(String outputDirectory, boolean bForceWrite) {240 logger.entering(new Object[] { outputDirectory, bForceWrite });241 long currentTime = System.currentTimeMillis();242 if (!bForceWrite && (currentTime - previousTime < ONE_MINUTE)) {243 return;244 }245 previousTime = currentTime;246 parseCompletedTest();247 generateReports(outputDirectory);248 logger.exiting();249 }250 /**251 * Parse the list of completed test and write to the completed temp file252 */253 private void parseCompletedTest() {254 logger.entering();255 List<TestMethodInfo> tempCompletedTest = new ArrayList<TestMethodInfo>();256 for (TestMethodInfo temp : completedTest) {257 Object isCompleted = temp.getResult().getAttribute(IS_COMPLETED);258 if (isCompleted != null && (boolean) isCompleted) {259 appendFile(jsonCompletedTest, temp.toJson().concat(",\n"));260 } else {261 tempCompletedTest.add(temp);262 }263 }264 completedTest = tempCompletedTest;265 logger.exiting();266 }267 /**268 * Generate JSON report and HTML report269 * 270 * @param outputDirectory271 */272 private void generateReports(String outputDirectory) {273 logger.entering(outputDirectory);274 ClassLoader localClassLoader = this.getClass().getClassLoader();275 try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputDirectory + File.separator + "index.html"));276 BufferedWriter jsonWriter = new BufferedWriter(new FileWriter(outputDirectory + File.separator277 + "report.json"));278 BufferedReader templateReader = new BufferedReader(new InputStreamReader(279 localClassLoader.getResourceAsStream("templates/RuntimeReporter/index.html")));) {280 JsonObject reporter = buildJSONReport();281 Gson gson = new GsonBuilder().setPrettyPrinting().create();282 String jsonReport = gson.toJson(reporter);283 jsonWriter.write(jsonReport);284 jsonWriter.newLine();285 generateHTMLReport(writer, templateReader, jsonReport);286 } catch (IOException | JsonParseException e) {287 logger.log(Level.SEVERE, e.getMessage(), e);288 throw new ReporterException(e);289 }290 logger.exiting();291 }292 /**293 * Writing JSON content to HTML file294 *295 * @param writer296 * @param templateReader297 * @param jsonReport298 * @throws IOException299 */300 private void generateHTMLReport(BufferedWriter writer, BufferedReader templateReader, String jsonReport)301 throws IOException {302 logger.entering(new Object[] { writer, templateReader, jsonReport });303 String readLine = null;304 while ((readLine = templateReader.readLine()) != null) {305 if (readLine.trim().equals("${reports}")) {306 writer.write(jsonReport);307 writer.newLine();308 } else {309 writer.write(readLine);310 writer.newLine();311 }312 }313 logger.exiting();314 }315 /**316 * Construct the JSON report for report generation317 * 318 * @return A {@link JsonObject} which represents the report.319 */320 private JsonObject buildJSONReport() {321 logger.entering();322 Gson gson = new GsonBuilder().setPrettyPrinting().create();323 JsonArray testObjects = loadJSONArray(jsonCompletedTest);324 for (TestMethodInfo temp : completedTest) {325 testObjects.add(gson.fromJson(temp.toJson(), JsonElement.class));326 }327 for (TestMethodInfo temp : runningTest) {328 testObjects.add(gson.fromJson(temp.toJson(), JsonElement.class));329 }330 JsonArray configObjects = loadJSONArray(jsonCompletedConfig);331 for (ConfigMethodInfo temp : runningConfig) {332 configObjects.add(gson.fromJson(temp.toJson(), JsonElement.class));333 }334 JsonObject summary = new JsonObject();335 summary.add("testMethodsSummary", getReportSummaryCounts(testObjects));336 summary.add("configurationMethodsSummary", getReportSummaryCounts(configObjects));337 JsonElement reportMetadata = gson.fromJson(ReporterConfigMetadata.toJsonAsString(), JsonElement.class);338 JsonObject reporter = new JsonObject();339 reporter.add("reportSummary", summary);340 reporter.add("testMethods", testObjects);341 reporter.add("configurationMethods", configObjects);342 reporter.add("configSummary", generateConfigSummary());343 reporter.add("localConfigSummary", testJsonLocalConfigSummary);344 reporter.add("reporterMetadata", reportMetadata);345 logger.exiting(reporter);346 return reporter;347 }348 /**349 * Provides a JSON object representing the counts of tests passed, failed, skipped and running.350 * 351 * @param testObjects352 * Array of the current tests as a {@link JsonArray}.353 * @return A {@link JsonObject} with counts for various test results.354 */355 private JsonObject getReportSummaryCounts(JsonArray testObjects) {356 logger.entering(testObjects);357 int runningCount = 0;358 int skippedCount = 0;359 int passedCount = 0;360 int failedCount = 0;361 String result;362 for (JsonElement test : testObjects) {363 result = test.getAsJsonObject().get("status").getAsString();364 switch (result) {365 case "Running":366 runningCount += 1;367 break;368 case "Passed":369 passedCount += 1;370 break;371 case "Failed":372 failedCount += 1;373 break;374 case "Skipped":375 skippedCount += 1;376 break;377 default:378 logger.warning("Found invalid status of the test being run. Status: " + result);379 }380 }381 JsonObject testSummary = new JsonObject();382 if (0 < runningCount) {383 testSummary.addProperty("running", runningCount);384 }385 testSummary.addProperty("passed", passedCount);386 testSummary.addProperty("failed", failedCount);387 testSummary.addProperty("skipped", skippedCount);388 logger.exiting(testSummary);389 return testSummary;390 }391 /**392 * Load the json array for the given file393 * 394 * @param jsonFile395 * json file location396 * @return JSONArray397 * @throws JSONException398 */399 private JsonArray loadJSONArray(File jsonFile) throws JsonParseException {400 logger.entering(jsonFile);401 String jsonTxt;402 try {403 jsonTxt = FileUtils.readFileToString(jsonFile, "UTF-8");404 } catch (IOException e) {405 logger.log(Level.SEVERE, e.getMessage(), e);406 throw new ReporterException(e);407 }408 StringBuilder completeJSONTxt = new StringBuilder("[");409 completeJSONTxt.append(StringUtils.removeEnd(jsonTxt, ",\n"));410 completeJSONTxt.append("]");411 JsonArray testObjects = (new JsonParser()).parse(completeJSONTxt.toString()).getAsJsonArray();412 logger.exiting(testObjects);413 return testObjects;414 }415 /**416 * Get list of test methods.417 * 418 * @return A list of {@link TestMethodInfo}.419 */420 public List<TestMethodInfo> getCompletedTestContent() {...

Full Screen

Full Screen

Source:ReporterException.java Github

copy

Full Screen

...15package com.paypal.selion.internal.reports.html;16/**17 * This exception is to be thrown when something goes wrong while running the flow to report test case execution/result18 */19public class ReporterException extends RuntimeException {20 private static final long serialVersionUID = 8071686053553550147L;21 public ReporterException(Exception e) {22 super(e);23 }24 public ReporterException(String msg) {25 super(msg);26 }27 public ReporterException(String msg, Exception e) {28 super(msg, e);29 }30}...

Full Screen

Full Screen

ReporterException

Using AI Code Generation

copy

Full Screen

1package com.paypal.selion.sample.webtests;2import org.testng.annotations.Test;3import com.paypal.selion.annotations.WebTest;4import com.paypal.selion.platform.grid.Grid;5import com.paypal.selion.platform.html.Button;6import com.paypal.selion.platform.html.CheckBox;7import com.paypal.selion.platform.html.Link;8import com.paypal.selion.platform.html.TextField;9import com.paypal.selion.platform.utilities.WebDriverWaitUtils;10import com.paypal.selion.testcomponents.BasicPageImpl;11import com.paypal.selion.testcomponents.FlightFinderPage;12import com.paypal.selion.testcomponents.HomePage;13import com.paypal.selion.testcomponents.LoggedInPage;14import com.paypal.selion.testcomponents.LoginPage;15import com.paypal.selion.testcomponents.SignOnPage;16import com.paypal.selion.testcomponents.YourItineraryPage;17import com.paypal.selion.internal.reports.html.ReporterException;18public class Test3 {19 public void testLogin() throws Exception {20 HomePage homePage = new HomePage();21 homePage.verifyTitle("Welcome: Mercury Tours");22 homePage.getLink("SIGN-ON").click();23 SignOnPage signOnPage = new SignOnPage();24 signOnPage.verifyTitle("Sign-on: Mercury Tours");25 signOnPage.getTextField("userName").type("mercury");26 signOnPage.getPasswordField("password").type("mercury");27 signOnPage.getButton("login").click();28 LoggedInPage loggedInPage = new LoggedInPage();29 loggedInPage.verifyTitle("Login: Mercury Tours");30 loggedInPage.getLink("SIGN-OFF").click();31 homePage.verifyTitle("Welcome: Mercury Tours");32 }33}34package com.paypal.selion.sample.webtests;35import org.testng.annotations.Test;36import com.paypal.selion.annotations.WebTest;37import com.paypal.selion.platform.grid.Grid;38import com.paypal.selion.platform.html.Button;39import com.paypal.selion.platform.html.CheckBox;40import com.paypal.selion.platform.html.Link;41import com.paypal.selion.platform.html.TextField;42import com.paypal.selion.platform.utilities.WebDriverWaitUtils;43import com.paypal.selion.testcomponents.BasicPageImpl;

Full Screen

Full Screen

ReporterException

Using AI Code Generation

copy

Full Screen

1import com.paypal.selion.internal.reports.html.ReporterException;2public class 3 {3 public static void main(String[] args) {4 try {5 throw new ReporterException("This is a sample exception");6 } catch (ReporterException e) {7 System.out.println(e.getMessage());8 }9 }10}11import java.io.PrintWriter;12import java.io.StringWriter;13public class ReporterException extends Exception {14 private static final long serialVersionUID = 1L;15 public ReporterException(String message) {16 super(message);17 }18 public ReporterException(String message, Throwable cause) {19 super(message, cause);20 }21 public ReporterException(Throwable cause) {22 super(cause);23 }24 public String toString() {25 StringWriter sw = new StringWriter();26 PrintWriter pw = new PrintWriter(sw);27 printStackTrace(pw);28 return sw.toString();29 }30}31Related Posts: Java.io.FileNotFoundException: (The system cannot…32Java.io.FileNotFoundException: (The system cannot…

Full Screen

Full Screen

ReporterException

Using AI Code Generation

copy

Full Screen

1import com.paypal.selion.internal.reports.html.ReporterException;2public class ExceptionTest {3 public static void main(String[] args) {4 try {5 throw new ReporterException("Test ReporterException");6 } catch (ReporterException e) {7 e.printStackTrace();8 }9 }10}11 at ExceptionTest.main(ExceptionTest.java:8)

Full Screen

Full Screen

ReporterException

Using AI Code Generation

copy

Full Screen

1package com.paypal.selion.testcomponents;2import org.testng.annotations.Test;3import com.paypal.selion.internal.reports.html.ReporterException;4public class ReporterExceptionTest {5public void testReporterException() throws ReporterException {6ReporterException reporterException = new ReporterException("ReporterException");7throw reporterException;8}9}

Full Screen

Full Screen

ReporterException

Using AI Code Generation

copy

Full Screen

1import com.paypal.selion.internal.reports.html.ReporterException;2public class TestClass {3 public void testMethod() {4 try {5 } catch (Exception e) {6 throw new ReporterException(e);7 }8 }9}10import com.paypal.selion.internal.reports.html.ReporterException;11public class TestClass {12 public void testMethod() {13 try {14 } catch (Exception e) {15 throw new ReporterException("Exception Message", e);16 }17 }18}19import com.paypal.selion.internal.reports.html.ReporterException;20public class TestClass {21 public void testMethod() {22 try {23 } catch (Exception e) {24 throw new ReporterException("Exception Message");25 }26 }27}28import com.paypal.selion.internal.reports.html.ReporterException;29public class TestClass {30 public void testMethod() {31 try {32 } catch (Exception e) {33 throw new ReporterException("Exception Message", e, true);34 }35 }36}37import com.paypal.selion.internal.reports.html.ReporterException;38public class TestClass {39 public void testMethod() {40 try {41 } catch (Exception e) {42 throw new ReporterException("Exception Message", e, false);43 }44 }45}46import com.paypal.selion.internal.reports.html.ReporterException;47public class TestClass {48 public void testMethod() {49 try {50 } catch (Exception e) {51 throw new ReporterException("Exception Message", true);52 }53 }54}

Full Screen

Full Screen

ReporterException

Using AI Code Generation

copy

Full Screen

1import com.paypal.selion.internal.reports.html.ReporterException;2public class SelionReporterExceptionDemo {3 public static void main(String[] args) {4 try {5 throw new ReporterException("This is a test");6 } catch (ReporterException e) {7 System.out.println(e.getMessage());8 }9 }10}

Full Screen

Full Screen

ReporterException

Using AI Code Generation

copy

Full Screen

1package com.paypal.selion.internal.reports.html;2import org.testng.Reporter;3public class ReporterException {4public static void main(String[] args) {5Reporter.log("this is a log statement");6}7}8package com.paypal.selion.internal.platform.grid;9import org.testng.Reporter;10public class ReporterException {11public static void main(String[] args) {12Reporter.log("this is a log statement");13}14}15package com.paypal.selion.internal.platform.grid.browsercapabilities;16import org.testng.Reporter;17public class ReporterException {18public static void main(String[] args) {19Reporter.log("this is a log statement");20}21}22package com.paypal.selion.internal.platform.grid.browsercapabilities;23import org.testng.Reporter;24public class ReporterException {25public static void main(String[] args) {26Reporter.log("this is a log statement");27}28}29package com.paypal.selion.internal.platform.grid.browsercapabilities;30import org.testng.Reporter;31public class ReporterException {32public static void main(String[] args) {33Reporter.log("this is a log statement");34}35}36package com.paypal.selion.internal.platform.grid.browsercapabilities;37import org.testng.Reporter;38public class ReporterException {39public static void main(String[] args) {40Reporter.log("this is a log statement");41}42}43package com.paypal.selion.internal.platform.grid.browsercapabilities;44import org.testng.Reporter;45public class ReporterException {46public static void main(String[] args) {47Reporter.log("this is a log statement");48}49}50package com.paypal.selion.internal.platform.grid.browsercapabilities;51import

Full Screen

Full Screen

ReporterException

Using AI Code Generation

copy

Full Screen

1import com.paypal.selion.internal.reports.html.Reporter;2import com.paypal.selion.internal.reports.html.ReporterException;3import org.testng.annotations.Test;4public class Test3 {5public void test3() {6Reporter.logException(new ReporterException("Error message"));7}8}9import com.paypal.selion.internal.reports.html.Reporter;10import com.paypal.selion.internal.reports.html.ReporterException;11import org.testng.annotations.Test;12public class Test4 {13public void test4() {14Reporter.logException(new ReporterException("Error message", new Exception("Exception message")));15}16}17import com.paypal.selion.internal.reports.html.Reporter;18import com.paypal.selion.internal.reports.html.ReporterException;19import org.testng.annotations.Test;20public class Test5 {21public void test5() {22Reporter.logException(new ReporterException("Error message", new Exception("Exception message"), true));23}24}25import com.paypal.selion.internal.reports.html.Reporter;26import com.paypal.selion.internal.reports.html.ReporterException;27import org.testng.annotations.Test;28public class Test6 {29public void test6() {30Reporter.logException(new ReporterException("Error message", new Exception("Exception message"), true, true));31}32}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run SeLion automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in ReporterException

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful