Best Testng code snippet using org.testng.reporters.EmailableReporter.endHtml
Source:EmailableReporter.java
...50 startHtml(m_out);51 generateSuiteSummaryReport(suites);52 generateMethodSummaryReport(suites);53 generateMethodDetailReport(suites);54 endHtml(m_out);55 m_out.flush();56 m_out.close();57// SendMail.szFileName=outdir;58//// m_out.println("<h1>" + SendMail.path + "</h1>");59 }60 protected PrintWriter createWriter(String outdir) throws IOException {61 new File(outdir).mkdirs();62 return new PrintWriter(new BufferedWriter(new FileWriter(new File(outdir,63 "emailable-report2.html"))));64 }65 /** Creates a table showing the highlights of each test method with links to the method details */66 protected void generateMethodSummaryReport(List<ISuite> suites) {67 m_methodIndex = 0;68 startResultSummaryTable("methodOverview");69 int testIndex = 1;70 for (ISuite suite : suites) {71 if(suites.size()>1) {72 titleRow(suite.getName(), 5);73 }74 Map<String, ISuiteResult> r = suite.getResults();75 for (ISuiteResult r2 : r.values()) {76 ITestContext testContext = r2.getTestContext();77 String testName = testContext.getName();78 m_testIndex = testIndex;79 resultSummary(suite, testContext.getFailedConfigurations(), testName,80 "failed", " (configuration methods)");81 resultSummary(suite, testContext.getFailedTests(), testName, "failed",82 "");83 resultSummary(suite, testContext.getSkippedConfigurations(), testName,84 "skipped", " (configuration methods)");85 resultSummary(suite, testContext.getSkippedTests(), testName,86 "skipped", "");87 resultSummary(suite, testContext.getPassedTests(), testName, "passed",88 "");89 testIndex++;90 }91 }92 m_out.println("</table>");93 }94 /** Creates a section showing known results for each method */95 protected void generateMethodDetailReport(List<ISuite> suites) {96 m_methodIndex = 0;97 for (ISuite suite : suites) {98 Map<String, ISuiteResult> r = suite.getResults();99 for (ISuiteResult r2 : r.values()) {100 ITestContext testContext = r2.getTestContext();101 if (r.values().size() > 0) {102 m_out.println("<h1>" + testContext.getName() + "</h1>");103 }104 resultDetail(testContext.getFailedConfigurations());105 resultDetail(testContext.getFailedTests());106 resultDetail(testContext.getSkippedConfigurations());107 resultDetail(testContext.getSkippedTests());108 resultDetail(testContext.getPassedTests());109 }110 }111 }112 /**113 * @param tests114 */115 private void resultSummary(ISuite suite, IResultMap tests, String testname, String style,116 String details) {117 if (tests.getAllResults().size() > 0) {118 StringBuffer buff = new StringBuffer();119 String lastClassName = "";120 int mq = 0;121 int cq = 0;122 for (ITestNGMethod method : getMethodSet(tests, suite)) {123 m_row += 1;124 m_methodIndex += 1;125 ITestClass testClass = method.getTestClass();126 String className = testClass.getName();127 if (mq == 0) {128 String id = (m_testIndex == null ? null : "t" + Integer.toString(m_testIndex));129 titleRow(testname + " — " + style + details, 5, id);130 m_testIndex = null;131 }132 if (!className.equalsIgnoreCase(lastClassName)) {133 if (mq > 0) {134 cq += 1;135 m_out.print("<tr class=\"" + style136 + (cq % 2 == 0 ? "even" : "odd") + "\">" + "<td");137 if (mq > 1) {138 m_out.print(" rowspan=\"" + mq + "\"");139 }140 m_out.println(">" + lastClassName + "</td>" + buff);141 }142 mq = 0;143 buff.setLength(0);144 lastClassName = className;145 }146 Set<ITestResult> resultSet = tests.getResults(method);147 long end = Long.MIN_VALUE;148 long start = Long.MAX_VALUE;149 for (ITestResult testResult : tests.getResults(method)) {150 if (testResult.getEndMillis() > end) {151 end = testResult.getEndMillis();152 }153 if (testResult.getStartMillis() < start) {154 start = testResult.getStartMillis();155 }156 }157 mq += 1;158 if (mq > 1) {159 buff.append("<tr class=\"" + style + (cq % 2 == 0 ? "odd" : "even")160 + "\">");161 }162 String description = method.getDescription();163 String testInstanceName = resultSet.toArray(new ITestResult[]{})[0].getTestName();164 buff.append("<td><a href=\"#m" + m_methodIndex + "\">"165 + qualifiedName(method)166 + " " + (description != null && description.length() > 0167 ? "(\"" + description + "\")"168 : "")169 + "</a>" + (null == testInstanceName ? "" : "<br>(" + testInstanceName + ")")170 + "</td>"171 + "<td class=\"numi\">" + resultSet.size() + "</td>"172 + "<td>" + start + "</td>"173 + "<td class=\"numi\">" + (end - start) + "</td>"174 + "</tr>");175 }176 if (mq > 0) {177 cq += 1;178 m_out.print("<tr class=\"" + style + (cq % 2 == 0 ? "even" : "odd")179 + "\">" + "<td");180 if (mq > 1) {181 m_out.print(" rowspan=\"" + mq + "\"");182 }183 m_out.println(">" + lastClassName + "</td>" + buff);184 }185 }186 }187 /** Starts and defines columns result summary table */188 private void startResultSummaryTable(String style) {189 tableStart(style, "summary");190 m_out.println("<tr><th>Class</th>"191 + "<th>Method</th><th># of<br/>Scenarios</th><th>Start</th><th>Time<br/>(ms)</th></tr>");192 m_row = 0;193 }194 private String qualifiedName(ITestNGMethod method) {195 StringBuilder addon = new StringBuilder();196 String[] groups = method.getGroups();197 int length = groups.length;198 if (length > 0 && !"basic".equalsIgnoreCase(groups[0])) {199 addon.append("(");200 for (int i = 0; i < length; i++) {201 if (i > 0) {202 addon.append(", ");203 }204 addon.append(groups[i]);205 }206 addon.append(")");207 }208 return "<b>" + method.getMethodName() + "</b> " + addon;209 }210 private void resultDetail(IResultMap tests) {211 for (ITestResult result : tests.getAllResults()) {212 ITestNGMethod method = result.getMethod();213 m_methodIndex++;214 String cname = method.getTestClass().getName();215 m_out.println("<h2 id=\"m" + m_methodIndex + "\">" + cname + ":"216 + method.getMethodName() + "</h2>");217 Set<ITestResult> resultSet = tests.getResults(method);218 generateForResult(result, method, resultSet.size());219 m_out.println("<p class=\"totop\"><a href=\"#summary\">back to summary </a></p>");220 }221 }222 private void generateForResult(ITestResult ans, ITestNGMethod method, int resultSetSize) {223 Object[] parameters = ans.getParameters();224 boolean hasParameters = parameters != null && parameters.length > 0;225 if (hasParameters) {226 tableStart("result", null);227 m_out.print("<tr class=\"param\">");228 for (int x = 1; x <= parameters.length; x++) {229 m_out.print("<th>Parameter #" + x + "</th>");230 }231 m_out.println("</tr>");232 m_out.print("<tr class=\"param stripe\">");233 for (Object p : parameters) {234 m_out.println("<td>" + Utils.escapeHtml(Utils.toString(p,null)) + "</td>");235 }236 m_out.println("</tr>");237 }238 List<String> msgs = Reporter.getOutput(ans);239 boolean hasReporterOutput = msgs.size() > 0;240 Throwable exception=ans.getThrowable();241 boolean hasThrowable = exception!=null;242 if (hasReporterOutput||hasThrowable) {243 if (hasParameters) {244 m_out.print("<tr><td");245 if (parameters.length > 1) {246 m_out.print(" colspan=\"" + parameters.length + "\"");247 }248 m_out.println(">");249 }250 else {251 m_out.println("<div>");252 }253 if (hasReporterOutput) {254 if(hasThrowable) {255 m_out.println("<h3>Test Messages</h3>");256 }257 for (String line : msgs) {258 m_out.println(line + "<br/>");259 }260 }261 if(hasThrowable) {262 boolean wantsMinimalOutput = ans.getStatus()==ITestResult.SUCCESS;263 if(hasReporterOutput) {264 m_out.println("<h3>"265 +(wantsMinimalOutput?"Expected Exception":"Failure")266 +"</h3>");267 }268 generateExceptionReport(exception,method);269 }270 if (hasParameters) {271 m_out.println("</td></tr>");272 }273 else {274 m_out.println("</div>");275 }276 }277 if (hasParameters) {278 m_out.println("</table>");279 }280 }281 protected void generateExceptionReport(Throwable exception,ITestNGMethod method) {282 m_out.print("<div class=\"stacktrace\">");283 m_out.print(Utils.stackTrace(exception, true)[0]);284 m_out.println("</div>");285 }286 /**287 * Since the methods will be sorted chronologically, we want to return288 * the ITestNGMethod from the invoked methods.289 */290 private Collection<ITestNGMethod> getMethodSet(IResultMap tests, ISuite suite) {291 List<IInvokedMethod> r = Lists.newArrayList();292 List<IInvokedMethod> invokedMethods = suite.getAllInvokedMethods();293 for (IInvokedMethod im : invokedMethods) {294 if (tests.getAllMethods().contains(im.getTestMethod())) {295 r.add(im);296 }297 }298 Arrays.sort(r.toArray(new IInvokedMethod[r.size()]), new TestSorter());299 List<ITestNGMethod> result = Lists.newArrayList();300 // Add all the invoked methods301 for (IInvokedMethod m : r) {302 result.add(m.getTestMethod());303 }304 // Add all the methods that weren't invoked (e.g. skipped) that we305 // haven't added yet306 for (ITestNGMethod m : tests.getAllMethods()) {307 if (!result.contains(m)) {308 result.add(m);309 }310 }311 return result;312 }313 public void generateSuiteSummaryReport(List<ISuite> suites) {314 tableStart("testOverview", null);315 m_out.print("<tr>");316 tableColumnStart("Test");317 tableColumnStart("Methods<br/>Passed");318 tableColumnStart("# Passed");319 tableColumnStart("# skipped");320 tableColumnStart("# failed");321 tableColumnStart("# Passed<br/>rate");322 tableColumnStart("# skipped<br/>rate");323 tableColumnStart("# failed<br/>rate");324 tableColumnStart("Total<br/>Time");325 tableColumnStart("Included<br/>Groups");326 tableColumnStart("Excluded<br/>Groups");327 m_out.println("</tr>");328 NumberFormat formatter = new DecimalFormat("#,##0.0");329 int qty_tests = 0;330 int qty_pass_m = 0;//ææçtestæ¹æ³331 int qty_pass_s = 0;//pass个æ°332 int qty_skip = 0;//skip个æ°333 int qty_fail = 0;//fail个æ°334 double qty_pass_rate= 0;//passçå¹³å335 double qty_skip_rate = 0;//skipçå¹³å336 double qty_fail_rate = 0;//failçå¹³å337 //è·åæ ¼å¼å对象338 NumberFormat nt = NumberFormat.getPercentInstance();339 //设置ç¾åæ°ç²¾ç¡®åº¦2å³ä¿ç两ä½å°æ°340 nt.setMinimumFractionDigits(2);341 342 343 long time_start = Long.MAX_VALUE;344 long time_end = Long.MIN_VALUE;345 m_testIndex = 1;346 for (ISuite suite : suites) {347 if (suites.size() > 1) {348 titleRow(suite.getName(), 11);349 }350 Map<String, ISuiteResult> tests = suite.getResults();351 for (ISuiteResult r : tests.values()) {352 qty_tests += 1;353 ITestContext overview = r.getTestContext();354 startSummaryRow(overview.getName());355// int q = getMethodSet(overview.getPassedTests(), suite).size();356 int q = overview.getAllTestMethods().length;357 qty_pass_m += q;358 summaryCell(q,Integer.MAX_VALUE);359 360 361 q = overview.getPassedTests().size();362 double passed=q;363 qty_pass_s += q;364 summaryCell(q,Integer.MAX_VALUE);365 366 q = getMethodSet(overview.getSkippedTests(), suite).size();367 double skipped=q;368 qty_skip += q;369 summaryCell(q,0);370 371 q = getMethodSet(overview.getFailedTests(), suite).size();372 double failed=q;373 qty_fail += q;374 summaryCell(q,0);375 376 double all=passed+failed+skipped;377 qty_pass_rate+=(double)passed/all;378 qty_skip_rate+=(double)skipped/all;379 qty_fail_rate+=(double)failed/all;380 381 summaryCell(nt.format(passed/all),false);382 summaryCell(nt.format(skipped/all),false);383 summaryCell(nt.format(failed/all),false);384 385 time_start = Math.min(overview.getStartDate().getTime(), time_start);386 time_end = Math.max(overview.getEndDate().getTime(), time_end);387 summaryCell(formatter.format(388 (overview.getEndDate().getTime() - overview.getStartDate().getTime()) / 1000.)389 + " seconds", true);390 summaryCell(overview.getIncludedGroups());391 summaryCell(overview.getExcludedGroups());392 m_out.println("</tr>");393 m_testIndex++;394 }395 }396 if (qty_tests > 1) {// testå¤äº1个ï¼å失败çåçççç»è®¡397 m_out.println("<tr class=\"total\"><td>Total</td>");398 summaryCell(qty_pass_m,Integer.MAX_VALUE);399 summaryCell(qty_pass_s,Integer.MAX_VALUE);400 summaryCell(qty_skip,0);401 summaryCell(qty_fail,0);402 403 double passed_rate_average=qty_pass_rate/qty_tests;404 double skiped_rate_average=qty_skip_rate/qty_tests;405 double failed_rate_average=qty_fail_rate/qty_tests;406 407 summaryCell(nt.format(passed_rate_average),false);408 summaryCell(nt.format(skiped_rate_average),false);409 summaryCell(nt.format(failed_rate_average),false);410 411 summaryCell(formatter.format((time_end - time_start) / 1000.) + " seconds", true);412 m_out.println("<td colspan=\"2\"> </td></tr>");413 }414 m_out.println("</table>");415 }416 private void summaryCell(String[] val) {417 StringBuffer b = new StringBuffer();418 for (String v : val) {419 b.append(v + " ");420 }421 summaryCell(b.toString(),true);422 }423 private void summaryCell(String v,boolean isgood) {424 m_out.print("<td class=\"numi"+(isgood?"":"_attn")+"\">" + v + "</td>");425 }426 private void startSummaryRow(String label) {427 m_row += 1;428 m_out.print("<tr" + (m_row % 2 == 0 ? " class=\"stripe\"" : "")429 + "><td style=\"text-align:left;padding-right:2em\"><a href=\"#t"430 + m_testIndex + "\">" + label + "</a>"431 + "</td>");432 }433 private void summaryCell(int v,int maxexpected) {434 summaryCell(String.valueOf(v),v<=maxexpected);435 }436 private void tableStart(String cssclass, String id) {437 m_out.println("<table cellspacing=\"0\" cellpadding=\"0\""438 + (cssclass != null ? " class=\"" + cssclass + "\""439 : " style=\"padding-bottom:2em\"")440 + (id != null ? " id=\"" + id + "\"" : "")441 + ">");442 m_row = 0;443 }444 private void tableColumnStart(String label) {445 m_out.print("<th>" + label + "</th>");446 }447 private void titleRow(String label, int cq) {448 titleRow(label, cq, null);449 }450 private void titleRow(String label, int cq, String id) {451 m_out.print("<tr");452 if (id != null) {453 m_out.print(" id=\"" + id + "\"");454 }455 m_out.println( "><th colspan=\"" + cq + "\">" + label + "</th></tr>");456 m_row = 0;457 }458 /** Starts HTML stream */459 protected void startHtml(PrintWriter out) {460 out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">");461 out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");462 out.println("<head>");463 out.println("<title>TestNG Report</title>");464 out.println("<style type=\"text/css\">");465 out.println("table {margin-bottom:10px;border-collapse:collapse;empty-cells:show}");466 out.println("td,th {border:1px solid #009;padding:.25em .5em}");467 out.println(".result th {vertical-align:bottom}");468 out.println(".param th {padding-left:1em;padding-right:1em}");469 out.println(".param td {padding-left:.5em;padding-right:2em}");470 out.println(".stripe td,.stripe th {background-color: #E6EBF9}");471 out.println(".numi,.numi_attn {text-align:right}");472 out.println(".total td {font-weight:bold}");473 out.println(".passedodd td {background-color: #0A0}");474 out.println(".passedeven td {background-color: #3F3}");475 out.println(".skippedodd td {background-color: #CCC}");476 out.println(".skippedodd td {background-color: #DDD}");477 out.println(".failedodd td,.numi_attn {background-color: #F33}");478 out.println(".failedeven td,.stripe .numi_attn {background-color: #D00}");479 out.println(".stacktrace {white-space:pre;font-family:monospace}");480 out.println(".totop {font-size:85%;text-align:center;border-bottom:2px solid #000}");481 out.println("</style>");482 out.println("</head>");483 out.println("<body>");484 }485 /** Finishes HTML stream */486 protected void endHtml(PrintWriter out) {487 out.println("</body></html>");488 }489 // ~ Inner Classes --------------------------------------------------------490 /** Arranges methods by classname and method name */491 private static final class TestSorter implements Comparator<IInvokedMethod> {492 // ~ Methods -------------------------------------------------------------493 /** Arranges methods by classname and method name */494 @Override495 public int compare(IInvokedMethod o1, IInvokedMethod o2) {496// System.out.println("Comparing " + o1.getMethodName() + " " + o1.getDate()497// + " and " + o2.getMethodName() + " " + o2.getDate());498 return (int) (o1.getDate() - o2.getDate());499// int r = ((T) o1).getTestClass().getName().compareTo(((T) o2).getTestClass().getName());500// if (r == 0) {...
Source:EmailableSummaryReporter.java
...56 startHtml(m_out);57 generateSuiteSummaryReport(suites);58 // generateMethodSummaryReport(suites);59 // generateMethodDetailReport(suites);60 endHtml(m_out);61 m_out.flush();62 m_out.close();63 }64 protected PrintWriter createWriter(String outdir) throws IOException {65 new File(outdir).mkdirs();66 return new PrintWriter(new BufferedWriter(new FileWriter(new File(outdir,67 "emailable-report2.html"))));68 }69 /** Creates a table showing the highlights of each test method with links to the method details */70 protected void generateMethodSummaryReport(List<ISuite> suites) {71 m_methodIndex = 0;72 startResultSummaryTable("methodOverview");73 int testIndex = 1;74 for (ISuite suite : suites) {75 if(suites.size()>1) {76 titleRow(suite.getName(), 5);77 }78 Map<String, ISuiteResult> r = suite.getResults();79 for (ISuiteResult r2 : r.values()) {80 ITestContext testContext = r2.getTestContext();81 String testName = testContext.getName();82 m_testIndex = testIndex;83 resultSummary(suite, testContext.getFailedConfigurations(), testName,84 "failed", " (configuration methods)");85 resultSummary(suite, testContext.getFailedTests(), testName, "failed",86 "");87 resultSummary(suite, testContext.getSkippedConfigurations(), testName,88 "skipped", " (configuration methods)");89 resultSummary(suite, testContext.getSkippedTests(), testName,90 "skipped", "");91 resultSummary(suite, testContext.getPassedTests(), testName, "passed",92 "");93 testIndex++;94 }95 }96 m_out.println("</table>");97 }98 /** Creates a section showing known results for each method */99 protected void generateMethodDetailReport(List<ISuite> suites) {100 m_methodIndex = 0;101 for (ISuite suite : suites) {102 Map<String, ISuiteResult> r = suite.getResults();103 for (ISuiteResult r2 : r.values()) {104 ITestContext testContext = r2.getTestContext();105 if (r.values().size() > 0) {106 m_out.println("<h1>" + testContext.getName() + "</h1>");107 }108 resultDetail(testContext.getFailedConfigurations());109 resultDetail(testContext.getFailedTests());110 resultDetail(testContext.getSkippedConfigurations());111 resultDetail(testContext.getSkippedTests());112 resultDetail(testContext.getPassedTests());113 }114 }115 }116 /**117* @param tests118*/119 private void resultSummary(ISuite suite, IResultMap tests, String testname, String style,120 String details) {121 if (tests.getAllResults().size() > 0) {122 StringBuffer buff = new StringBuffer();123 String lastClassName = "";124 int mq = 0;125 int cq = 0;126 for (ITestNGMethod method : getMethodSet(tests, suite)) {127 m_row += 1;128 m_methodIndex += 1;129 ITestClass testClass = method.getTestClass();130 String className = testClass.getName();131 if (mq == 0) {132 String id = (m_testIndex == null ? null : "t" + Integer.toString(m_testIndex));133 titleRow(testname + " — " + style + details, 5, id);134 m_testIndex = null;135 }136 if (!className.equalsIgnoreCase(lastClassName)) {137 if (mq > 0) {138 cq += 1;139 m_out.print("<tr class=\"" + style140 + (cq % 2 == 0 ? "even" : "odd") + "\">" + "<td");141 if (mq > 1) {142 m_out.print(" rowspan=\"" + mq + "\"");143 }144 m_out.println(">" + lastClassName + "</td>" + buff);145 }146 mq = 0;147 buff.setLength(0);148 lastClassName = className;149 }150 Set<ITestResult> resultSet = tests.getResults(method);151 long end = Long.MIN_VALUE;152 long start = Long.MAX_VALUE;153 for (ITestResult testResult : tests.getResults(method)) {154 if (testResult.getEndMillis() > end) {155 end = testResult.getEndMillis();156 }157 if (testResult.getStartMillis() < start) {158 start = testResult.getStartMillis();159 }160 }161 mq += 1;162 if (mq > 1) {163 buff.append("<tr class=\"" + style + (cq % 2 == 0 ? "odd" : "even")164 + "\">");165 }166 String description = method.getDescription();167 String testInstanceName = resultSet.toArray(new ITestResult[]{})[0].getTestName();168 buff.append("<td><a href=\"#m" + m_methodIndex + "\">"169 + qualifiedName(method)170 + " " + (description != null && description.length() > 0171 ? "(\"" + description + "\")"172 : "")173 + "</a>" + (null == testInstanceName ? "" : "<br>(" + testInstanceName + ")")174 + "</td>"175 + "<td class=\"numi\">" + resultSet.size() + "</td>"176 + "<td>" + start + "</td>"177 + "<td class=\"numi\">" + (end - start) + "</td>"178 + "</tr>");179 }180 if (mq > 0) {181 cq += 1;182 m_out.print("<tr class=\"" + style + (cq % 2 == 0 ? "even" : "odd")183 + "\">" + "<td");184 if (mq > 1) {185 m_out.print(" rowspan=\"" + mq + "\"");186 }187 m_out.println(">" + lastClassName + "</td>" + buff);188 }189 }190 }191 /** Starts and defines columns result summary table */192 private void startResultSummaryTable(String style) {193 tableStart(style, "summary");194 m_out.println("<tr><th>Class</th>"195 + "<th>Method</th><th># of<br/>Scenarios</th><th>Start</th><th>Time<br/>(ms)</th></tr>");196 m_row = 0;197 }198 private String qualifiedName(ITestNGMethod method) {199 StringBuilder addon = new StringBuilder();200 String[] groups = method.getGroups();201 int length = groups.length;202 if (length > 0 && !"basic".equalsIgnoreCase(groups[0])) {203 addon.append("(");204 for (int i = 0; i < length; i++) {205 if (i > 0) {206 addon.append(", ");207 }208 addon.append(groups[i]);209 }210 addon.append(")");211 }212 return "<b>" + method.getMethodName() + "</b> " + addon;213 }214 private void resultDetail(IResultMap tests) {215 for (ITestResult result : tests.getAllResults()) {216 ITestNGMethod method = result.getMethod();217 m_methodIndex++;218 String cname = method.getTestClass().getName();219 m_out.println("<h2 id=\"m" + m_methodIndex + "\">" + cname + ":"220 + method.getMethodName() + "</h2>");221 Set<ITestResult> resultSet = tests.getResults(method);222 generateForResult(result, method, resultSet.size());223 m_out.println("<p class=\"totop\"><a href=\"#summary\">back to summary</a></p>");224 }225 }226 private void generateForResult(ITestResult ans, ITestNGMethod method, int resultSetSize) {227 Object[] parameters = ans.getParameters();228 boolean hasParameters = parameters != null && parameters.length > 0;229 if (hasParameters) {230 tableStart("result", null);231 m_out.print("<tr class=\"param\">");232 for (int x = 1; x <= parameters.length; x++) {233 m_out.print("<th>Parameter #" + x + "</th>");234 }235 m_out.println("</tr>");236 m_out.print("<tr class=\"param stripe\">");237 // for (Object p : parameters) {238 // m_out.println("<td>" + Utils.escapeHtml(Utils.toString(p)) + "</td>");239 // }240 m_out.println("</tr>");241 }242 List<String> msgs = Reporter.getOutput(ans);243 boolean hasReporterOutput = msgs.size() > 0;244 Throwable exception=ans.getThrowable();245 boolean hasThrowable = exception!=null;246 if (hasReporterOutput||hasThrowable) {247 if (hasParameters) {248 m_out.print("<tr><td");249 if (parameters.length > 1) {250 m_out.print(" colspan=\"" + parameters.length + "\"");251 }252 m_out.println(">");253 }254 else {255 m_out.println("<div>");256 }257 if (hasReporterOutput) {258 if(hasThrowable) {259 m_out.println("<h3>Test Messages</h3>");260 }261 for (String line : msgs) {262 m_out.println(line + "<br/>");263 }264 }265 if(hasThrowable) {266 boolean wantsMinimalOutput = ans.getStatus()==ITestResult.SUCCESS;267 if(hasReporterOutput) {268 m_out.println("<h3>"269 +(wantsMinimalOutput?"Expected Exception":"Failure")270 +"</h3>");271 }272 generateExceptionReport(exception,method);273 }274 if (hasParameters) {275 m_out.println("</td></tr>");276 }277 else {278 m_out.println("</div>");279 }280 }281 if (hasParameters) {282 m_out.println("</table>");283 }284 }285 protected void generateExceptionReport(Throwable exception,ITestNGMethod method) {286 m_out.print("<div class=\"stacktrace\">");287 m_out.print(Utils.stackTrace(exception, true)[0]);288 m_out.println("</div>");289 }290 /**291* Since the methods will be sorted chronologically, we want to return292* the ITestNGMethod from the invoked methods.293*/294 private Collection<ITestNGMethod> getMethodSet(IResultMap tests, ISuite suite) {295 List<IInvokedMethod> r = Lists.newArrayList();296 List<IInvokedMethod> invokedMethods = suite.getAllInvokedMethods();297 for (IInvokedMethod im : invokedMethods) {298 if (tests.getAllMethods().contains(im.getTestMethod())) {299 r.add(im);300 }301 }302 Arrays.sort(r.toArray(new IInvokedMethod[r.size()]), new TestSorter());303 List<ITestNGMethod> result = Lists.newArrayList();304 // Add all the invoked methods305 for (IInvokedMethod m : r) {306 result.add(m.getTestMethod());307 }308 // Add all the methods that weren't invoked (e.g. skipped) that we309 // haven't added yet310 for (ITestNGMethod m : tests.getAllMethods()) {311 if (!result.contains(m)) {312 result.add(m);313 }314 }315 return result;316 }317 public void generateSuiteSummaryReport(List<ISuite> suites) {318 tableStart("testOverview", null);319 m_out.print("<tr>");320 tableColumnStart("Test");321 tableColumnStart("Methods<br/>Passed");322 tableColumnStart("Scenarios<br/>Passed");323 tableColumnStart("# skipped");324 tableColumnStart("# failed");325 tableColumnStart("Total<br/>Time");326 tableColumnStart("Included<br/>Groups");327 tableColumnStart("Excluded<br/>Groups");328 m_out.println("</tr>");329 NumberFormat formatter = new DecimalFormat("#,##0.0");330 int qty_tests = 0;331 int qty_pass_m = 0;332 int qty_pass_s = 0;333 int qty_skip = 0;334 int qty_fail = 0;335 long time_start = Long.MAX_VALUE;336 long time_end = Long.MIN_VALUE;337 m_testIndex = 1;338 339 for (ISuite suite : suites) {340 if ((suites.size() > 1)&& suite.getResults().size()==0) {341 titleRow(suite.getName(), 8);342 }343 }344 345 for (ISuite suite : suites) {346 if ((suites.size() > 1)&& suite.getResults().size()>0) {347 titleRow(suite.getName(), 8);348 }349 Map<String, ISuiteResult> tests = suite.getResults();350 for (ISuiteResult r : tests.values()) {351 qty_tests += 1;352 ITestContext overview = r.getTestContext();353 startSummaryRow(overview.getName());354 int q = getMethodSet(overview.getPassedTests(), suite).size();355 qty_pass_m += q;356 summaryCell(q,Integer.MAX_VALUE);357 q = overview.getPassedTests().size();358 qty_pass_s += q;359 summaryCell(q,Integer.MAX_VALUE);360 q = getMethodSet(overview.getSkippedTests(), suite).size();361 qty_skip += q;362 summaryCell(q,0);363 q = getMethodSet(overview.getFailedTests(), suite).size();364 qty_fail += q;365 summaryCell(q,0);366 time_start = Math.min(overview.getStartDate().getTime(), time_start);367 time_end = Math.max(overview.getEndDate().getTime(), time_end);368 summaryCell(formatter.format(369 (overview.getEndDate().getTime() - overview.getStartDate().getTime()) / 1000.)370 + " seconds", true);371 summaryCell(overview.getIncludedGroups());372 summaryCell(overview.getExcludedGroups());373 m_out.println("</tr>");374 m_testIndex++;375 }376 }377 if (qty_tests > 1) {378 m_out.println("<tr class=\"total\"><td>Total</td>");379 summaryCell(qty_pass_m,Integer.MAX_VALUE);380 summaryCell(qty_pass_s,Integer.MAX_VALUE);381 summaryCell(qty_skip,0);382 summaryCell(qty_fail,0);383 summaryCell(formatter.format((time_end - time_start) / 1000.) + " seconds", true);384 m_out.println("<td colspan=\"2\"> </td></tr>");385 }386 m_out.println("</table>");387 }388 private void summaryCell(String[] val) {389 StringBuffer b = new StringBuffer();390 for (String v : val) {391 b.append(v + " ");392 }393 summaryCell(b.toString(),true);394 }395 private void summaryCell(String v,boolean isgood) {396 m_out.print("<td class=\"numi"+(isgood?"":"_attn")+"\">" + v + "</td>");397 }398 private void startSummaryRow(String label) {399 m_row += 1;400 m_out.print("<tr" + (m_row % 2 == 0 ? " class=\"stripe\"" : "")401 + "><td style=\"text-align:left;padding-right:2em\"><a href=\"#t"402 + m_testIndex + "\">" + label + "</a>"403 + "</td>");404 }405 private void summaryCell(int v,int maxexpected) {406 summaryCell(String.valueOf(v),v<=maxexpected);407 }408 private void tableStart(String cssclass, String id) {409 m_out.println("<table cellspacing=\"0\" cellpadding=\"0\""410 + (cssclass != null ? " class=\"" + cssclass + "\""411 : " style=\"padding-bottom:2em\"")412 + (id != null ? " id=\"" + id + "\"" : "")413 + ">");414 m_row = 0;415 }416 private void tableColumnStart(String label) {417 m_out.print("<th>" + label + "</th>");418 }419 private void titleRow(String label, int cq) {420 titleRow(label, cq, null);421 }422 private void titleRow(String label, int cq, String id) {423 m_out.print("<tr");424 if (id != null) {425 m_out.print(" id=\"" + id + "\"");426 }427 m_out.println( "><th colspan=\"" + cq + "\">" + label + "</th></tr>");428 m_row = 0;429 }430 /** Starts HTML stream */431 protected void startHtml(PrintWriter out) {432 out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">");433 out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");434 out.println("<head>");435 out.println("<title>TestNG Report</title>");436 out.println("<style type=\"text/css\">");437 out.println("table {margin-bottom:10px;border-collapse:collapse;empty-cells:show}");438 out.println("td,th {border:1px solid #009;padding:.25em .5em}");439 out.println(".result th {vertical-align:bottom}");440 out.println(".param th {padding-left:1em;padding-right:1em}");441 out.println(".param td {padding-left:.5em;padding-right:2em}");442 out.println(".stripe td,.stripe th {background-color: #E6EBF9}");443 out.println(".numi,.numi_attn {text-align:right}");444 out.println(".total td {font-weight:bold}");445 out.println(".passedodd td {background-color: #0A0}");446 out.println(".passedeven td {background-color: #3F3}");447 out.println(".skippedodd td {background-color: #CCC}");448 out.println(".skippedodd td {background-color: #DDD}");449 out.println(".failedodd td,.numi_attn {background-color: #F33}");450 out.println(".failedeven td,.stripe .numi_attn {background-color: #D00}");451 out.println(".stacktrace {white-space:pre;font-family:monospace}");452 out.println(".totop {font-size:85%;text-align:center;border-bottom:2px solid #000}");453 out.println("</style>");454 out.println("</head>");455 out.println("<body>");456 }457 /** Finishes HTML stream */458 protected void endHtml(PrintWriter out) {459 out.println("</body></html>");460 }461 // ~ Inner Classes --------------------------------------------------------462 /** Arranges methods by classname and method name */463 private class TestSorter implements Comparator<IInvokedMethod> {464 // ~ Methods -------------------------------------------------------------465 /** Arranges methods by classname and method name */466 public int compare(IInvokedMethod o1, IInvokedMethod o2) {467// System.out.println("Comparing " + o1.getMethodName() + " " + o1.getDate()468// + " and " + o2.getMethodName() + " " + o2.getDate());469 return (int) (o1.getDate() - o2.getDate());470// int r = ((T) o1).getTestClass().getName().compareTo(((T) o2).getTestClass().getName());471// if (r == 0) {472// r = ((T) o1).getMethodName().compareTo(((T) o2).getMethodName());...
Source:EmailReport.java
...48 startHtml(m_out);49 generateSuiteSummaryReport(suites);50 generateMethodSummaryReport(suites);51 generateMethodDetailReport(suites);52 endHtml(m_out);53 m_out.flush();54 m_out.close();55 }56 protected PrintWriter createWriter(String outdir) throws IOException {57 new File(outdir).mkdirs();58 String jvmArg = System.getProperty(JVM_ARG);59 if (jvmArg != null && !jvmArg.trim().isEmpty()) {60 fileName = jvmArg;61 }62 return new PrintWriter(new BufferedWriter(new FileWriter(new File(outdir, fileName))));63 }64 /**65 * Creates a table showing the highlights of each test method with links to the method details66 */67 protected void generateMethodSummaryReport(List<ISuite> suites) {68 m_methodIndex = 0;69 startResultSummaryTable();70 int testIndex = 1;71 for (ISuite suite : suites) {72 if (suites.size() > 1) {73 titleRow(suite.getName(), 5);74 }75 Map<String, ISuiteResult> r = suite.getResults();76 for (ISuiteResult r2 : r.values()) {77 ITestContext testContext = r2.getTestContext();78 String testName = testContext.getName();79 m_testIndex = testIndex;80 resultSummary(suite, testContext.getFailedConfigurations(), testName,81 "failed", " (configuration methods)");82 resultSummary(suite, testContext.getFailedTests(), testName, "failed",83 "");84 resultSummary(suite, testContext.getSkippedConfigurations(), testName,85 "skipped", " (configuration methods)");86 resultSummary(suite, testContext.getSkippedTests(), testName,87 "skipped", "");88 resultSummary(suite, testContext.getPassedTests(), testName, "passed",89 "");90 testIndex++;91 }92 }93 m_out.println("</table>");94 }95 /**96 * Creates a section showing known results for each method97 */98 protected void generateMethodDetailReport(List<ISuite> suites) {99 m_methodIndex = 0;100 for (ISuite suite : suites) {101 Map<String, ISuiteResult> r = suite.getResults();102 for (ISuiteResult r2 : r.values()) {103 ITestContext testContext = r2.getTestContext();104 if (r.values().size() > 0) {105 m_out.println("<h1>" + testContext.getName() + "</h1>");106 }107 resultDetail(testContext.getFailedConfigurations());108 resultDetail(testContext.getFailedTests());109 resultDetail(testContext.getSkippedConfigurations());110 resultDetail(testContext.getSkippedTests());111 resultDetail(testContext.getPassedTests());112 }113 }114 }115 /**116 * @param tests117 */118 private void resultSummary(ISuite suite, IResultMap tests, String testname, String style,119 String details) {120 if (!tests.getAllResults().isEmpty()) {121 StringBuilder buff = new StringBuilder();122 String lastClassName = "";123 int mq = 0;124 int cq = 0;125 for (ITestNGMethod method : getMethodSet(tests, suite)) {126 m_row += 1;127 m_methodIndex += 1;128 ITestClass testClass = method.getTestClass();129 String className = testClass.getName();130 if (mq == 0) {131 String id = (m_testIndex == null ? null : "t" + Integer.toString(m_testIndex));132 titleRow(testname + " — " + style + details, 5, id);133 m_testIndex = null;134 }135 if (!className.equalsIgnoreCase(lastClassName)) {136 if (mq > 0) {137 cq += 1;138 m_out.print("<tr class=\"" + style139 + (cq % 2 == 0 ? "even" : "odd") + "\">" + "<td");140 if (mq > 1) {141 m_out.print(" rowspan=\"" + mq + "\"");142 }143 m_out.println(">" + lastClassName + "</td>" + buff);144 }145 mq = 0;146 buff.setLength(0);147 lastClassName = className;148 }149 Set<ITestResult> resultSet = tests.getResults(method);150 long end = Long.MIN_VALUE;151 long start = Long.MAX_VALUE;152 for (ITestResult testResult : tests.getResults(method)) {153 if (testResult.getEndMillis() > end) {154 end = testResult.getEndMillis();155 }156 if (testResult.getStartMillis() < start) {157 start = testResult.getStartMillis();158 }159 }160 mq += 1;161 if (mq > 1) {162 buff.append("<tr class=\"").append(style).append(cq % 2 == 0 ? "odd" : "even")163 .append("\">");164 }165 String description = method.getDescription();166 String testInstanceName = resultSet.toArray(new ITestResult[]{})[0].getTestName();167 buff.append("<td><a href=\"#m").append(m_methodIndex).append("\">")168 .append(qualifiedName(method))169 .append(" ");170 if (description != null && !description.isEmpty()) {171 buff.append("(\"").append(description).append("\")");172 }173 buff.append("</a>");174 if (testInstanceName != null) {175 buff.append("<br>(").append(testInstanceName).append(")");176 }177 buff.append("</td>")178 .append("<td class=\"numi\">").append(resultSet.size()).append("</td>")179 .append("<td>").append(start).append("</td>")180 .append("<td class=\"numi\">").append(end - start).append("</td>")181 .append("</tr>");182 }183 if (mq > 0) {184 cq++;185 m_out.print("<tr class=\"" + style + (cq % 2 == 0 ? "even" : "odd")186 + "\">" + "<td");187 if (mq > 1) {188 m_out.print(" rowspan=\"" + mq + "\"");189 }190 m_out.println(">" + lastClassName + "</td>" + buff);191 }192 }193 }194 /**195 * Starts and defines columns result summary table196 */197 private void startResultSummaryTable() {198 tableStart("methodOverview", "summary");199 m_out.println("<tr><th>Class</th>"200 + "<th>Method</th><th># of<br/>Scenarios</th><th>Start</th><th>Time<br/>(ms)</th></tr>");201 m_row = 0;202 }203 private String qualifiedName(ITestNGMethod method) {204 StringBuilder addon = new StringBuilder();205 String[] groups = method.getGroups();206 int length = groups.length;207 if (length > 0 && !"basic".equalsIgnoreCase(groups[0])) {208 addon.append("(");209 for (int i = 0; i < length; i++) {210 if (i > 0) {211 addon.append(", ");212 }213 addon.append(groups[i]);214 }215 addon.append(")");216 }217 return "<b>" + method.getMethodName() + "</b> " + addon;218 }219 private void resultDetail(IResultMap tests) {220 for (ITestResult result : tests.getAllResults()) {221 ITestNGMethod method = result.getMethod();222 m_methodIndex++;223 String cname = method.getTestClass().getName();224 m_out.println("<h2 id=\"m" + m_methodIndex + "\">" + cname + ":"225 + method.getMethodName() + "</h2>");226 generateForResult(result, method);227 m_out.println("<p class=\"totop\"><a href=\"#summary\">back to summary</a></p>");228 }229 }230 private void generateForResult(ITestResult ans, ITestNGMethod method) {231 Object[] parameters = ans.getParameters();232 boolean hasParameters = parameters != null && parameters.length > 0;233 if (hasParameters) {234 tableStart("result", null);235 m_out.print("<tr class=\"param\">");236 for (int x = 1; x <= parameters.length; x++) {237 m_out.print("<th>Parameter #" + x + "</th>");238 }239 m_out.println("</tr>");240 m_out.print("<tr class=\"param stripe\">");241 for (Object p : parameters) {242 m_out.println("<td>" + Utils.escapeHtml(Utils.toString(p)) + "</td>");243 }244 m_out.println("</tr>");245 }246 List<String> msgs = Reporter.getOutput(ans);247 boolean hasReporterOutput = !msgs.isEmpty();248 Throwable exception = ans.getThrowable();249 boolean hasThrowable = exception != null;250 if (hasReporterOutput || hasThrowable) {251 if (hasParameters) {252 m_out.print("<tr><td");253 if (parameters.length > 1) {254 m_out.print(" colspan=\"" + parameters.length + "\"");255 }256 m_out.println(">");257 } else {258 m_out.println("<div>");259 }260 if (hasReporterOutput) {261 if (hasThrowable) {262 m_out.println("<h3>Test Messages</h3>");263 }264 for (String line : msgs) {265 m_out.println(line + "<br/>");266 }267 }268 if (hasThrowable) {269 boolean wantsMinimalOutput = ans.getStatus() == ITestResult.SUCCESS;270 if (hasReporterOutput) {271 m_out.println("<h3>"272 + (wantsMinimalOutput ? "Expected Exception" : "Failure")273 + "</h3>");274 }275 generateExceptionReport(exception, method);276 }277 if (hasParameters) {278 m_out.println("</td></tr>");279 } else {280 m_out.println("</div>");281 }282 }283 if (hasParameters) {284 m_out.println("</table>");285 }286 }287 protected void generateExceptionReport(Throwable exception, ITestNGMethod method) {288 m_out.print("<div class=\"stacktrace\">");289 m_out.print(Utils.shortStackTrace(exception, true));290 m_out.println("</div>");291 }292 /**293 * Since the methods will be sorted chronologically, we want to return294 * the ITestNGMethod from the invoked methods.295 */296 private Collection<ITestNGMethod> getMethodSet(IResultMap tests, ISuite suite) {297 List<IInvokedMethod> r = Lists.newArrayList();298 List<IInvokedMethod> invokedMethods = suite.getAllInvokedMethods();299 for (IInvokedMethod im : invokedMethods) {300 if (tests.getAllMethods().contains(im.getTestMethod())) {301 r.add(im);302 }303 }304 Arrays.sort(r.toArray(new IInvokedMethod[r.size()]), new EmailReport.TestSorter());305 List<ITestNGMethod> result = Lists.newArrayList();306 // Add all the invoked methods307 for (IInvokedMethod m : r) {308 result.add(m.getTestMethod());309 }310 // Add all the methods that weren't invoked (e.g. skipped) that we311 // haven't added yet312 for (ITestNGMethod m : tests.getAllMethods()) {313 if (!result.contains(m)) {314 result.add(m);315 }316 }317 return result;318 }319 public void generateSuiteSummaryReport(List<ISuite> suites) {320 tableStart("testOverview", null);321 m_out.print("<tr>");322 tableColumnStart("Test");323 tableColumnStart("Methods<br/>Passed");324 tableColumnStart("Scenarios<br/>Passed");325 tableColumnStart("# skipped");326 tableColumnStart("# failed");327 tableColumnStart("Total<br/>Time");328 tableColumnStart("Included<br/>Groups");329 tableColumnStart("Excluded<br/>Groups");330 m_out.println("</tr>");331 NumberFormat formatter = new DecimalFormat("#,##0.0");332 int qty_tests = 0;333 int qty_pass_m = 0;334 int qty_pass_s = 0;335 int qty_skip = 0;336 int qty_fail = 0;337 long time_start = Long.MAX_VALUE;338 long time_end = Long.MIN_VALUE;339 m_testIndex = 1;340 for (ISuite suite : suites) {341 if (suites.size() > 1) {342 titleRow(suite.getName(), 8);343 }344 Map<String, ISuiteResult> tests = suite.getResults();345 for (ISuiteResult r : tests.values()) {346 qty_tests += 1;347 ITestContext overview = r.getTestContext();348 startSummaryRow(overview.getName());349 int q = getMethodSet(overview.getPassedTests(), suite).size();350 qty_pass_m += q;351 summaryCell(q, Integer.MAX_VALUE);352 q = overview.getPassedTests().size();353 qty_pass_s += q;354 summaryCell(q, Integer.MAX_VALUE);355 q = getMethodSet(overview.getSkippedTests(), suite).size();356 qty_skip += q;357 summaryCell(q, 0);358 q = getMethodSet(overview.getFailedTests(), suite).size();359 qty_fail += q;360 summaryCell(q, 0);361 time_start = Math.min(overview.getStartDate().getTime(), time_start);362 time_end = Math.max(overview.getEndDate().getTime(), time_end);363 summaryCell(formatter.format(364 (overview.getEndDate().getTime() - overview.getStartDate().getTime()) / 1000.)365 + " seconds", true);366 summaryCell(overview.getIncludedGroups());367 summaryCell(overview.getExcludedGroups());368 m_out.println("</tr>");369 m_testIndex++;370 }371 }372 if (qty_tests > 1) {373 m_out.println("<tr class=\"total\"><td>Total</td>");374 summaryCell(qty_pass_m, Integer.MAX_VALUE);375 summaryCell(qty_pass_s, Integer.MAX_VALUE);376 summaryCell(qty_skip, 0);377 summaryCell(qty_fail, 0);378 summaryCell(formatter.format((time_end - time_start) / 1000.) + " seconds", true);379 m_out.println("<td colspan=\"2\"> </td></tr>");380 }381 m_out.println("</table>");382 }383 private void summaryCell(String[] val) {384 StringBuilder b = new StringBuilder();385 for (String v : val) {386 b.append(v).append(" ");387 }388 summaryCell(b.toString(), true);389 }390 private void summaryCell(String v, boolean isGood) {391 m_out.print("<td class=\"numi" + (isGood ? "" : "_attn") + "\">" + v + "</td>");392 }393 private void startSummaryRow(String label) {394 m_row++;395 m_out.print("<tr" + (m_row % 2 == 0 ? " class=\"stripe\"" : "")396 + "><td style=\"text-align:left;padding-right:2em\"><a href=\"#t"397 + m_testIndex + "\">" + label + "</a>"398 + "</td>");399 }400 private void summaryCell(int v, int maxexpected) {401 summaryCell(String.valueOf(v), v <= maxexpected);402 }403 private void tableStart(String cssclass, String id) {404 m_out.println("<table cellspacing=\"0\" cellpadding=\"0\""405 + (cssclass != null ? " class=\"" + cssclass + "\""406 : " style=\"padding-bottom:2em\"")407 + (id != null ? " id=\"" + id + "\"" : "")408 + ">");409 m_row = 0;410 }411 private void tableColumnStart(String label) {412 m_out.print("<th>" + label + "</th>");413 }414 private void titleRow(String label, int cq) {415 titleRow(label, cq, null);416 }417 private void titleRow(String label, int cq, String id) {418 m_out.print("<tr");419 if (id != null) {420 m_out.print(" id=\"" + id + "\"");421 }422 m_out.println("><th colspan=\"" + cq + "\">" + label + "</th></tr>");423 m_row = 0;424 }425 /**426 * Starts HTML stream427 */428 protected void startHtml(PrintWriter out) {429 out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">");430 out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");431 out.println("<head>");432 out.println("<title>TestNG Report</title>");433 out.println("<style type=\"text/css\">");434 out.println("table {margin-bottom:10px;border-collapse:collapse;empty-cells:show}");435 out.println("td,th {border:1px solid #009;padding:.25em .5em}");436 out.println(".result th {vertical-align:bottom}");437 out.println(".param th {padding-left:1em;padding-right:1em}");438 out.println(".param td {padding-left:.5em;padding-right:2em}");439 out.println(".stripe td,.stripe th {background-color: #E6EBF9}");440 out.println(".numi,.numi_attn {text-align:right}");441 out.println(".total td {font-weight:bold}");442 out.println(".passedodd td {background-color: #0A0}");443 out.println(".passedeven td {background-color: #3F3}");444 out.println(".skippedodd td {background-color: #CCC}");445 out.println(".skippedodd td {background-color: #DDD}");446 out.println(".failedodd td,.numi_attn {background-color: #F33}");447 out.println(".failedeven td,.stripe .numi_attn {background-color: #D00}");448 out.println(".stacktrace {white-space:pre;font-family:monospace}");449 out.println(".totop {font-size:85%;text-align:center;border-bottom:2px solid #000}");450 out.println("</style>");451 out.println("</head>");452 out.println("<body>");453 }454 /**455 * Finishes HTML stream456 */457 protected void endHtml(PrintWriter out) {458 out.println("</body></html>");459 }460 // ~ Inner Classes --------------------------------------------------------461 /**462 * Arranges methods by classname and method name463 */464 private static final class TestSorter implements Comparator<IInvokedMethod> {465 // ~ Methods -------------------------------------------------------------466 /**467 * Arranges methods by classname and method name468 */469 @Override470 public int compare(IInvokedMethod o1, IInvokedMethod o2) {471 return (int) (o1.getDate() - o2.getDate());...
endHtml
Using AI Code Generation
1package com.test;2import java.io.File;3import java.io.IOException;4import java.util.ArrayList;5import java.util.List;6import org.testng.IReporter;7import org.testng.ISuite;8import org.testng.ISuiteResult;9import org.testng.ITestContext;10import org.testng.ITestResult;11import org.testng.TestListenerAdapter;12import org.testng.TestNG;13import org.testng.collections.Lists;14import org.testng.internal.Utils;15import org.testng.reporters.EmailableReporter;16import org.testng.xml.XmlSuite;17public class TestNGTest extends TestListenerAdapter implements IReporter {18 private static final String TEST_OUTPUT_DIRECTORY = "test-output";19 private static final String TEST_OUTPUT_HTML_DIRECTORY = "test-output/html";20 private static final String TEST_OUTPUT_HTML_FILE = "test-output/html/emailable-report.html";21 public static void main(String[] args) {22 TestNG tng = new TestNG();23 List<String> suites = new ArrayList<String>();24 suites.add("testng.xml");25 tng.setTestSuites(suites);26 tng.run();27 }28 public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {29 try {30 File dir = new File(TEST_OUTPUT_HTML_DIRECTORY);31 if (!dir.exists()) {32 dir.mkdirs();33 }34 EmailableReporter reporter = new EmailableReporter();35 reporter.setOutputDirectory(TEST_OUTPUT_DIRECTORY);36 reporter.generateReport(xmlSuites, suites, TEST_OUTPUT_HTML_DIRECTORY);37 reporter.endHtml();38 System.out.println("Report generated: " + TEST_OUTPUT_HTML_FILE);39 } catch (IOException e) {40 Utils.log("Unable to generate report", 0);41 }42 }43 public void onTestFailure(ITestResult tr) {44 super.onTestFailure(tr);45 generateReport();46 }47 public void onTestSkipped(ITestResult tr) {48 super.onTestSkipped(tr);49 generateReport();50 }51 public void onTestSuccess(ITestResult tr) {52 super.onTestSuccess(tr);53 generateReport();54 }55 private void generateReport() {56 TestNG tng = new TestNG();57 tng.setOutputDirectory(TEST_OUTPUT_DIRECTORY);58 tng.setTestClasses(new Class[] { this.getClass() });59 tng.setUseDefaultListeners(false);60 tng.setVerbose(0);
endHtml
Using AI Code Generation
1package com.test;2import java.io.File;3import java.io.IOException;4import java.lang.reflect.Method;5import org.testng.annotations.AfterMethod;6import org.testng.annotations.BeforeMethod;7import org.testng.annotations.DataProvider;8import org.testng.annotations.Test;9import com.relevantcodes.extentreports.ExtentReports;10import com.relevantcodes.extentreports.ExtentTest;11import com.relevantcodes.extentreports.LogStatus;12public class TestClass {13 ExtentReports extent;14 ExtentTest test;15 String reportPath = "C:\\Users\\Public\\Documents\\test.html";16 String imagePath = "C:\\Users\\Public\\Documents\\test.png";17 public void beforeMethod(Method method) {18 extent = new ExtentReports(reportPath, true);19 test = extent.startTest(method.getName(), "Test Description");20 }21 @Test(dataProvider = "dp")22 public void testMethod(String data) {23 test.log(LogStatus.INFO, "Test data: " + data);24 test.log(LogStatus.INFO, "Screenshot: " + test.addScreenCapture(imagePath));25 }26 public void afterMethod() {27 extent.endTest(test);28 extent.flush();29 extent.close();30 }31 public Object[][] dp() {32 return new Object[][] { new Object[] { "data1" }, new Object[] { "data2" } };33 }34}35package com.test;36import java.io.File;37import java.io.IOException;38import java.lang.reflect.Method;39import org.testng.annotations.AfterMethod;40import org.testng.annotations.BeforeMethod;41import org.testng.annotations.DataProvider;42import org.testng.annotations.Test;43import com.relevantcodes.extentreports.ExtentReports;44import com.relevantcodes.extentreports.ExtentTest;45import com.relevantcodes.extentreports.LogStatus;46public class TestClass {47 ExtentReports extent;48 ExtentTest test;49 String reportPath = "C:\\Users\\Public\\Documents\\test.html";50 String imagePath = "C:\\Users\\Public\\Documents\\test.png";51 public void beforeMethod(Method method) {52 extent = new ExtentReports(reportPath, true);53 test = extent.startTest(method.getName(), "Test Description");54 }55 @Test(dataProvider = "dp")56 public void testMethod(String data) {57 test.log(LogStatus.INFO, "Test data: " + data);58 test.log(LogStatus.INFO, "Screenshot: " + test.addScreen
endHtml
Using AI Code Generation
1package com.automation;2import org.testng.annotations.Test;3public class TestNGEmailableReport {4 public void test1() {5 System.out.println("Test 1");6 }7 public void test2() {8 System.out.println("Test 2");9 }10 public void test3() {11 System.out.println("Test 3");12 }13}
endHtml
Using AI Code Generation
1import org.testng.reporters.EmailableReporter2import org.apache.commons.mail.DefaultAuthenticator3import org.apache.commons.mail.Email4import org.apache.commons.mail.SimpleEmail5import java.util.Date6import java.io.File7import java.nio.file.Files8import java.nio.file.Paths9import java.nio.file.Path10import java.nio.file.StandardCopyOption11def email = new SimpleEmail()12email.setHostName("smtp.gmail.com")13email.setSmtpPort(465)14email.setAuthenticator(new DefaultAuthenticator("username", "password"))15email.setSSLOnConnect(true)16email.setFrom("
TestNG is a Java-based open-source framework for test automation that includes various test types, such as unit testing, functional testing, E2E testing, etc. TestNG is in many ways similar to JUnit and NUnit. But in contrast to its competitors, its extensive features make it a lot more reliable framework. One of the major reasons for its popularity is its ability to structure tests and improve the scripts' readability and maintainability. Another reason can be the important characteristics like the convenience of using multiple annotations, reliance, and priority that make this framework popular among developers and testers for test design. You can refer to the TestNG tutorial to learn why you should choose the TestNG framework.
You can push your abilities to do automated testing using TestNG and advance your career by earning a TestNG certification. Check out our TestNG certification.
Watch this complete tutorial to learn how you can leverage the capabilities of the TestNG framework for Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!