/
HtmlReporter.scala
1103 lines (987 loc) · 49.1 KB
/
HtmlReporter.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2001-2013 Artima, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.scalatest.tools
import org.scalatest._
import org.scalatest.events._
import HtmlReporter._
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream
import java.io.OutputStreamWriter
import java.io.PrintWriter
import java.io.StringWriter
import java.net.URL
import java.nio.channels.Channels
import java.text.DecimalFormat
import java.util.Iterator
import java.util.Set
import java.util.UUID
import org.scalatest.exceptions.StackDepth
import scala.annotation.tailrec
import scala.collection.mutable.ListBuffer
import scala.io.Source
import scala.xml.Node
import scala.xml.NodeBuffer
import scala.xml.NodeSeq
import scala.xml.XML
import PrintReporter.BufferSize
import StringReporter.makeDurationString
import Suite.unparsedXml
import Suite.xmlContent
import org.scalatest.exceptions.TestFailedException
import org.commonmark.parser.Parser
import org.commonmark.renderer.html.HtmlRenderer
/**
* A <code>Reporter</code> that prints test status information in HTML format to a file.
*/
private[scalatest] class HtmlReporter(
directoryPath: String,
presentAllDurations: Boolean,
cssUrl: Option[URL],
resultHolder: Option[SuiteResultHolder]
) extends ResourcefulReporter {
private val specIndent = 15
private val targetDir = new File(directoryPath)
private val imagesDir = new File(targetDir, "images")
private val jsDir = new File(targetDir, "js")
private val cssDir = new File(targetDir, "css")
if (!targetDir.exists)
targetDir.mkdirs()
if (!imagesDir.exists)
imagesDir.mkdirs()
if (!jsDir.exists)
jsDir.mkdirs()
if (!cssDir.exists)
cssDir.mkdirs()
private def copyResource(url: URL, toDir: File, targetFileName: String): Unit = {
val inputStream = url.openStream
try {
val outputStream = new FileOutputStream(new File(toDir, targetFileName))
try {
outputStream.getChannel().transferFrom(Channels.newChannel(inputStream), 0, Long.MaxValue)
}
finally {
outputStream.flush()
outputStream.close()
}
}
finally {
inputStream.close()
}
}
private def getResource(resourceName: String): URL =
classOf[Suite].getClassLoader.getResource(resourceName)
cssUrl.foreach(copyResource(_, cssDir, "custom.css"))
copyResource(getResource("org/scalatest/HtmlReporter.css"), cssDir, "styles.css")
copyResource(getResource("org/scalatest/sorttable.js"), jsDir, "sorttable.js")
copyResource(getResource("org/scalatest/d3.v2.min.js"), jsDir, "d3.v2.min.js")
copyResource(getResource("images/greenbullet.gif"), imagesDir, "testsucceeded.gif")
copyResource(getResource("images/redbullet.gif"), imagesDir, "testfailed.gif")
copyResource(getResource("images/yellowbullet.gif"), imagesDir, "testignored.gif")
copyResource(getResource("images/yellowbullet.gif"), imagesDir, "testcanceled.gif")
copyResource(getResource("images/yellowbullet.gif"), imagesDir, "testpending.gif")
copyResource(getResource("images/graybullet.gif"), imagesDir, "infoprovided.gif")
private val results = resultHolder.getOrElse(new SuiteResultHolder)
try {
Class.forName("com.vladsch.flexmark.profile.pegdown.PegdownOptionsAdapter")
}
catch {
case _: ClassNotFoundException =>
throw new ClassNotFoundException(Resources.flexmarkClassNotFound)
}
private val parser = Parser.builder().build()
private val renderer = HtmlRenderer.builder().build()
private def markdownToHtml(s: String): String = renderer.render(parser.parse(s))
private def withPossibleLineNumber(stringToPrint: String, throwable: Option[Throwable]): String = {
throwable match {
case Some(testFailedException: TestFailedException) =>
testFailedException.failedCodeFileNameAndLineNumberString match {
case Some(lineNumberString) =>
Resources.printedReportPlusLineNumber(stringToPrint, lineNumberString)
case None => stringToPrint
}
case _ => stringToPrint
}
}
private def stringsToPrintOnError(noteMessageFun: => String, errorMessageFun: Any => String, message: String, throwable: Option[Throwable],
formatter: Option[Formatter], suiteName: Option[String], testName: Option[String], duration: Option[Long]): String = {
formatter match {
case Some(IndentedText(_, rawText, _)) =>
Resources.specTextAndNote(rawText, noteMessageFun)
case _ =>
// Deny MotionToSuppress directives in error events, because error info needs to be seen by users
suiteName match {
case Some(sn) =>
testName match {
case Some(tn) => errorMessageFun(sn + ": " + tn)
case None => errorMessageFun(sn)
}
// Should not get here with built-in ScalaTest stuff, but custom stuff could get here.
case None => errorMessageFun(Resources.noNameSpecified)
}
}
}
private def stringToPrintWhenNoError(messageFun: Any => String, formatter: Option[Formatter], suiteName: String, testName: Option[String]): Option[String] =
stringToPrintWhenNoError(messageFun, formatter, suiteName, testName, None)
private def stringToPrintWhenNoError(messageFun: Any => String, formatter: Option[Formatter], suiteName: String, testName: Option[String], duration: Option[Long]): Option[String] = {
formatter match {
case Some(IndentedText(_, rawText, _)) =>
duration match {
case Some(milliseconds) =>
if (presentAllDurations)
Some(Resources.withDuration(rawText, makeDurationString(milliseconds)))
else
Some(rawText)
case None => Some(rawText)
}
case Some(MotionToSuppress) => None
case _ =>
val arg =
testName match {
case Some(tn) => suiteName + ": " + tn
case None => suiteName
}
val unformattedText = messageFun(arg)
duration match {
case Some(milliseconds) =>
if (presentAllDurations)
Some(Resources.withDuration(unformattedText, makeDurationString(milliseconds)))
else
Some(unformattedText)
case None => Some(unformattedText)
}
}
}
private def getIndentLevel(formatter: Option[Formatter]) =
formatter match {
case Some(IndentedText(formattedText, rawText, indentationLevel)) => indentationLevel
case _ => 0
}
private def getSuiteFileName(suiteResult: SuiteResult) =
suiteResult.suiteClassName.getOrElse(suiteResult.suiteName)
private def makeSuiteFile(suiteResult: SuiteResult): Unit = {
val name = getSuiteFileName(suiteResult)
val pw = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(new File(targetDir, name + ".html")), BufferSize), "UTF-8"))
try {
pw.println {
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n" +
"<!DOCTYPE html" + "\n" +
" PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"" + "\n" +
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">" + "\n" +
getSuiteHtml(name, suiteResult)
}
}
finally {
pw.flush()
pw.close()
}
}
private def appendCombinedStatus(name: String, r: SuiteResult) =
if (r.testsFailedCount > 0)
name + "_with_failed"
else if (r.testsIgnoredCount > 0 || r.testsPendingCount > 0 || r.testsCanceledCount > 0)
name + "_passed"
else
name + "_passed_all"
private def transformStringForResult(s: String, suiteResult: SuiteResult): String =
s + (if (suiteResult.testsFailedCount > 0) "_failed" else "_passed")
private def getSuiteHtml(name: String, suiteResult: SuiteResult) =
<html>
<head>
<title>ScalaTest Suite { name } Results</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Expires" content="-1" />
<meta http-equiv="Pragma" content="no-cache" />
<link href="css/styles.css" rel="stylesheet" />
{
cssUrl match {
case Some(cssUrl) =>
<link href="css/custom.css" rel="stylesheet" />
case None => NodeSeq.Empty
}
}
<script type="text/javascript">
{
unparsedXml(
"""
function toggleDetails(contentId, linkId) {
var ele = document.getElementById(contentId);
var text = document.getElementById(linkId);
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "(Show Details)";
}
else {
ele.style.display = "block";
text.innerHTML = "(Hide Details)";
}
}
function hideOpenInNewTabIfRequired() {
if (top === self) { document.getElementById('printlink').style.display = 'none'; }
}
"""
)
}
</script>
</head>
<body class="specification">
<div id="suite_header_name">{ suiteResult.suiteName }</div>
<div id={ transformStringForResult("suite_header_statistic", suiteResult) }>
{ "Tests: total " + (suiteResult.testsSucceededCount + suiteResult.testsFailedCount + suiteResult.testsCanceledCount + suiteResult.testsIgnoredCount + suiteResult.testsPendingCount) + ", succeeded " +
suiteResult.testsSucceededCount + ", failed " + suiteResult.testsFailedCount + ", canceled " + suiteResult.testsCanceledCount + ", ignored " + suiteResult.testsIgnoredCount + ", pending " +
suiteResult.testsPendingCount }
</div>
{
val scopeStack = new collection.mutable.Stack[String]()
suiteResult.eventList.map { e =>
e match {
case ScopeOpened(ordinal, message, nameInfo, formatter, location, payload, threadName, timeStamp) =>
val testNameInfo = nameInfo.testName
val stringToPrint = stringToPrintWhenNoError(Resources.scopeOpened _, formatter, nameInfo.suiteName, nameInfo.testName)
stringToPrint match {
case Some(string) =>
val elementId = generateElementId
scopeStack.push(elementId)
scope(elementId, string, getIndentLevel(formatter) + 1)
case None =>
NodeSeq.Empty
}
case ScopeClosed(ordinal, message, nameInfo, formatter, location, payload, threadName, timeStamp) =>
scopeStack.pop
NodeSeq.Empty
case ScopePending(ordinal, message, nameInfo, formatter, location, payload, threadName, timeStamp) =>
val testNameInfo = nameInfo.testName
val stringToPrint = stringToPrintWhenNoError(Resources.scopePending _, formatter, nameInfo.suiteName, nameInfo.testName)
stringToPrint match {
case Some(string) =>
val elementId = generateElementId
scope(elementId, string, getIndentLevel(formatter) + 1)
case None =>
NodeSeq.Empty
}
case TestSucceeded(ordinal, suiteName, suiteId, suiteClassName, testName, testText, recordedEvents, duration, formatter, location, rerunnable, payload, threadName, timeStamp) =>
val stringToPrint = stringToPrintWhenNoError(Resources.testSucceeded _, formatter, suiteName, Some(testName), duration)
val nodeSeq =
stringToPrint match {
case Some(string) =>
val elementId = generateElementId
test(elementId, List(string), getIndentLevel(formatter) + 1, "test_passed")
case None =>
NodeSeq.Empty
}
nodeSeq :: recordedEvents.map(processInfoMarkupProvided(_, "test_passed")).toList
case TestFailed(ordinal, message, suiteName, suiteId, suiteClassName, testName, testText, recordedEvents, analysis, throwable, duration, formatter, location, rerunnable, payload, threadName, timeStamp) =>
val stringToPrint = stringsToPrintOnError(Resources.failedNote, Resources.testFailed _, message, throwable, formatter, Some(suiteName), Some(testName), duration)
val elementId = generateElementId
val nodeSeq = testWithDetails(elementId, List(stringToPrint), message, throwable, getIndentLevel(formatter) + 1, "test_failed")
nodeSeq :: recordedEvents.map(processInfoMarkupProvided(_, "test_failed")).toList
case TestIgnored(ordinal, suiteName, suiteId, suiteClassName, testName, testText, formatter, location, payload, threadName, timeStamp) =>
val stringToPrint =
formatter match {
case Some(IndentedText(_, rawText, _)) => Some(Resources.specTextAndNote(rawText, Resources.ignoredNote))
case Some(MotionToSuppress) => None
case _ => Some(Resources.testIgnored(suiteName + ": " + testName))
}
stringToPrint match {
case Some(string) =>
val elementId = generateElementId
test(elementId, List(string), getIndentLevel(formatter) + 1, "test_ignored")
case None =>
NodeSeq.Empty
}
case TestPending(ordinal, suiteName, suiteId, suiteClassName, testName, testText, recordedEvents, duration, formatter, location, payload, threadName, timeStamp) =>
val stringToPrint =
formatter match {
case Some(IndentedText(_, rawText, _)) => Some(Resources.specTextAndNote(rawText, Resources.pendingNote))
case Some(MotionToSuppress) => None
case _ => Some(Resources.testPending(suiteName + ": " + testName))
}
val nodeSeq =
stringToPrint match {
case Some(string) =>
val elementId = generateElementId
test(elementId, List(string), getIndentLevel(formatter) + 1, "test_pending")
case None =>
NodeSeq.Empty
}
nodeSeq :: recordedEvents.map(processInfoMarkupProvided(_, "test_pending")).toList
case TestCanceled(ordinal, message, suiteName, suiteId, suiteClassName, testName, testText, recordedEvents, throwable, duration, formatter, location, rerunner, payload, threadName, timeStamp) =>
val stringToPrint = stringsToPrintOnError(Resources.canceledNote, Resources.testCanceled _, message, throwable, formatter, Some(suiteName), Some(testName), duration)
val elementId = generateElementId
val nodeSeq = testWithDetails(elementId, List(stringToPrint), message, throwable, getIndentLevel(formatter) + 1, "test_canceled")
nodeSeq :: recordedEvents.map(processInfoMarkupProvided(_, "test_canceled")).toList
case infoProvided: InfoProvided =>
processInfoMarkupProvided(infoProvided, "info")
case markupProvided: MarkupProvided =>
processInfoMarkupProvided(markupProvided, "markup")
// TO CONTINUE: XML element must be last
// Allow AlertProvided and NoteProvided to use this case, because we don't want that showing up in the HTML report.
case _ => NodeSeq.Empty
}
}
}
<table id="suite_footer">
<tr id="suite_footer_id">
<td id={ transformStringForResult("suite_footer_id_label", suiteResult) }>Suite ID</td>
<td id="suite_footer_id_value" colspan="5">{ suiteResult.suiteId }</td>
</tr>
<tr id="suite_footer_class">
<td id={ transformStringForResult("suite_footer_class_label", suiteResult) }>Class name</td>
<td id="suite_footer_class_value" colspan="5">{ suiteResult.suiteClassName.getOrElse("-") }</td>
</tr>
<tr id="suite_footer_duration">
<td id={ transformStringForResult("suite_footer_duration_label", suiteResult) }>Total duration</td>
<td id="suite_footer_duration_value" colspan="2">
{
suiteResult.duration match {
case Some(duration) => makeDurationString(duration)
case None => "-"
}
}
</td>
</tr>
</table>
<div id="printlink">(<a href={ getSuiteFileName(suiteResult) + ".html" } target="_blank">Open { suiteResult.suiteName } in new tab</a>)</div>
</body>
<script type="text/javascript">
//<![CDATA[
hideOpenInNewTabIfRequired();
//]]>
</script>
</html>
private def processInfoMarkupProvided(event: Event, theClass: String) = {
event match {
case InfoProvided(ordinal, message, nameInfo, throwable, formatter, location, payload, threadName, timeStamp) =>
val (suiteName, testName) =
nameInfo match {
case Some(NameInfo(suiteName, _, _, testName)) => (Some(suiteName), testName)
case None => (None, None)
}
val infoContent = stringsToPrintOnError(Resources.infoProvidedNote, Resources.infoProvided _, message, throwable, formatter, suiteName, testName, None)
val elementId = generateElementId
test(elementId, List(infoContent), getIndentLevel(formatter) + 1, theClass)
case MarkupProvided(ordinal, text, nameInfo, formatter, location, payload, threadName, timeStamp) =>
val (suiteName, testName) =
nameInfo match {
case Some(NameInfo(suiteName, _, _, testName)) => (Some(suiteName), testName)
case None => (None, None)
}
val elementId = generateElementId
markup(elementId, text, getIndentLevel(formatter) + 1, theClass)
case _ => NodeSeq.Empty
}
}
private def makeIndexFile(completeMessageFun: => String, completeInMessageFun: String => String, duration: Option[Long]): Unit = {
val pw = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(new File(targetDir, "index.html")), BufferSize), "UTF-8"))
try {
pw.println {
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!DOCTYPE html\n" +
"PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n" +
"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" +
getIndexHtml(completeMessageFun, completeInMessageFun, duration)
}
}
finally {
pw.flush()
pw.close()
}
}
private def getHeaderStatusColor(summary: Summary) =
if (summary.testsFailedCount == 0) "scalatest-header-passed" else "scalatest-header-failed"
private def getPieChartScript(summary: Summary) = {
import summary._
"/* modified from http://www.permadi.com/tutorial/cssGettingBackgroundColor/index.html - */" + "\n" +
"function getBgColor(elementId)" + "\n" +
"{" + "\n" +
" var element = document.getElementById(elementId);" + "\n" +
" if (element.currentStyle)" + "\n" +
" return element.currentStyle.backgroundColor;" + "\n" +
" if (window.getComputedStyle)" + "\n" +
" {" + "\n" +
" var elementStyle=window.getComputedStyle(element,\"\");" + "\n" +
" if (elementStyle)" + "\n" +
" return elementStyle.getPropertyValue(\"background-color\");" + "\n" +
" }" + "\n" +
" // Return 0 if both methods failed." + "\n" +
" return 0;" + "\n" +
"}" + "\n" +
"var data = [" + testsSucceededCount + ", " + testsFailedCount + ", " + testsIgnoredCount + ", " + testsPendingCount + ", " + testsCanceledCount + "];" + "\n" +
"var color = [getBgColor('summary_view_row_1_legend_succeeded_label'), " + "\n" +
" getBgColor('summary_view_row_1_legend_failed_label'), " + "\n" +
" getBgColor('summary_view_row_1_legend_ignored_label'), " + "\n" +
" getBgColor('summary_view_row_1_legend_pending_label'), " + "\n" +
" getBgColor('summary_view_row_1_legend_canceled_label')" + "\n" +
" ];" + "\n" +
"var width = document.getElementById('chart_div').offsetWidth," + "\n" +
" height = document.getElementById('chart_div').offsetHeight," + "\n" +
" outerRadius = Math.min(width, height) / 2," + "\n" +
" innerRadius = 0," + "\n" +
" donut = d3.layout.pie()," + "\n" +
" arc = d3.svg.arc().innerRadius(innerRadius).outerRadius(outerRadius);" + "\n" +
"var vis = d3.select(\"#chart_div\")" + "\n" +
" .append(\"svg\")" + "\n" +
" .data([data])" + "\n" +
" .attr(\"width\", width)" + "\n" +
" .attr(\"height\", height);" + "\n" +
"var arcs = vis.selectAll(\"g.arc\")" + "\n" +
" .data(donut)" + "\n" +
" .enter().append(\"g\")" + "\n" +
" .attr(\"class\", \"arc\")" + "\n" +
" .attr(\"transform\", \"translate(\" + outerRadius + \",\" + outerRadius + \")\");" + "\n" +
"arcs.append(\"path\")" + "\n" +
" .attr(\"fill\", function(d, i) { return color[i]; })" + "\n" +
" .attr(\"d\", arc);\n"
}
private def getIndexHtml(completeMessageFun: => String, completeInMessageFun: String => String, duration: Option[Long]) = {
val summary = results.summary
import summary._
val decimalFormat = new DecimalFormat("#.##")
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>ScalaTest Results</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Expires" content="-1" />
<meta http-equiv="Pragma" content="no-cache" />
<link href="css/styles.css" rel="stylesheet" />
{
cssUrl match {
case Some(cssUrl) =>
<link href="css/custom.css" rel="stylesheet" />
case None => NodeSeq.Empty
}
}
<script type="text/javascript" src="js/d3.v2.min.js"></script>
<script type="text/javascript" src="js/sorttable.js"></script>
<script type="text/javascript">
{
unparsedXml(
"""
var tagMap = {};
var SUCCEEDED_BIT = 1;
var FAILED_BIT = 2;
var IGNORED_BIT = 4;
var PENDING_BIT = 8;
var CANCELED_BIT = 16;
function applyFilter() {
var mask = 0;
if (document.getElementById('succeeded_checkbox').checked)
mask |= SUCCEEDED_BIT;
if (document.getElementById('failed_checkbox').checked)
mask |= FAILED_BIT;
if (document.getElementById('ignored_checkbox').checked)
mask |= IGNORED_BIT;
if (document.getElementById('pending_checkbox').checked)
mask |= PENDING_BIT;
if (document.getElementById('canceled_checkbox').checked)
mask |= CANCELED_BIT;
for (var key in tagMap) {
if (tagMap.hasOwnProperty(key)) {
var bitSet = tagMap[key];
var element = document.getElementById(key);
if ((bitSet & mask) != 0)
element.style.display = "table-row";
else
element.style.display = "none";
}
}
}
function showDetails(suiteName) {
document.getElementById('details_view').innerHTML = "<iframe src='" + suiteName + ".html' width='100%' height='100%'></iframe>";
}
function resizeDetailsView() {
var headerView = document.getElementById('scalatest-header');
var detailsView = document.getElementById('details_view');
var summaryView = document.getElementById('summary_view');
var left = summaryView.offsetWidth + 30;
detailsView.style.left = left + "px";
detailsView.style.width = (window.innerWidth - left - 30) + "px";
detailsView.style.height = (window.innerHeight - headerView.offsetHeight - 20) + "px";
}"""
)
}
</script>
</head>
<body onresize="resizeDetailsView()">
<div class="scalatest-report">
{ header(completeMessageFun, completeInMessageFun, duration, summary) }
<table id="summary_view">
<tr id="summary_view_row_1">
<td id="summary_view_row_1_chart">
<div id="chart_div"></div>
</td>
<td id="summary_view_row_1_legend">
<table id="summary_view_row_1_legend_table">
<tr id="summary_view_row_1_legend_table_row_succeeded">
<td id="summary_view_row_1_legend_succeeded_label">Succeeded</td>
<td id="summary_view_row_1_legend_succeeded_count">{ testsSucceededCount }</td>
<td id="summary_view_row_1_legend_succeeded_percent">({ decimalFormat.format(testsSucceededCount * 100.0 / totalTestsCount) }%)</td>
</tr>
<tr id="summary_view_row_1_legend_table_row_failed">
<td id="summary_view_row_1_legend_failed_label">Failed</td>
<td id="summary_view_row_1_legend_failed_count">{ testsFailedCount }</td>
<td id="summary_view_row_1_legend_failed_percent">({ decimalFormat.format(testsFailedCount * 100.0 / totalTestsCount) }%)</td>
</tr>
<tr id="summary_view_row_1_legend_table_row_canceled">
<td id="summary_view_row_1_legend_canceled_label">Canceled</td>
<td id="summary_view_row_1_legend_canceled_count">{ testsCanceledCount }</td>
<td id="summary_view_row_1_legend_canceled_percent">({ decimalFormat.format(testsCanceledCount * 100.0 / totalTestsCount) }%)</td>
</tr>
<tr id="summary_view_row_1_legend_table_row_ignored">
<td id="summary_view_row_1_legend_ignored_label">Ignored</td>
<td id="summary_view_row_1_legend_ignored_count">{ testsIgnoredCount }</td>
<td id="summary_view_row_1_legend_ignored_percent">({ decimalFormat.format(testsIgnoredCount * 100.0 / totalTestsCount) }%)</td>
</tr>
<tr id="summary_view_row_1_legend_table_row_pending">
<td id="summary_view_row_1_legend_pending_label">Pending</td>
<td id="summary_view_row_1_legend_pending_count">{ testsPendingCount }</td>
<td id="summary_view_row_1_legend_pending_percent">({ decimalFormat.format(testsPendingCount * 100.0 / totalTestsCount) }%)</td>
</tr>
</table>
</td>
</tr>
<tr id="summary_view_row_2">
<td id="summary_view_row_2_results" colspan="2">
{ getStatistic(summary) }
{ suiteResults }
</td>
</tr>
</table>
<div id="details_view">
<span id="click_suite_hint">Click on suite name to view details.</span> <br />
<span id="click_column_hint">Click on column name to sort.</span>
</div>
</div>
<script type="text/javascript">
{ unparsedXml(getPieChartScript(summary)) }
</script>
<script type="text/javascript">
{ unparsedXml(tagMapScript) }
</script>
<script type="text/javascript">
resizeDetailsView();
</script>
</body>
</html>
}
// TODO: This needs to be internationalized
private def getStatistic(summary: Summary) =
<div id="display-filters">
<input id="succeeded_checkbox" name="succeeded_checkbox" type="checkbox" checked="checked" onchange="applyFilter()" /> <label id="succeeded_checkbox_label" for="passed_checkbox">Succeeded</label>
<input id="failed_checkbox" name="failed_checkbox" type="checkbox" checked="checked" onchange="applyFilter()" /> <label id="failed_checkbox_label" for="failed_checkbox">Failed</label>
<input id="canceled_checkbox" name="canceled_checkbox" type="checkbox" checked="checked" onchange="applyFilter()" /> <label id="canceled_checkbox_label" for="canceled_checkbox">Canceled</label>
<input id="ignored_checkbox" name="ignored_checkbox" type="checkbox" checked="checked" onchange="applyFilter()" /> <label id="ignored_checkbox_label" for="ignored_checkbox">Ignored</label>
<input id="pending_checkbox" name="pending_checkbox" type="checkbox" checked="checked" onchange="applyFilter()" /> <label id="pending_checkbox_label" for="pending_checkbox">Pending</label>
</div>
private def header(completeMessageFun: => String, completeInMessageFun: String => String, duration: Option[Long], summary: Summary) =
<div id="scalatest-header" class={ getHeaderStatusColor(summary) }>
<div id="title">
ScalaTest Results
</div>
<div id="summary">
<p id="duration">{ getDuration(completeMessageFun, completeInMessageFun, duration) }</p>
<p id="totalTests">{ getTotalTests(summary) }</p>
<p id="suiteSummary">{ getSuiteSummary(summary) }</p>
<p id="testSummary">{ getTestSummary(summary) }</p>
</div>
</div>
private def generateElementId = UUID.randomUUID.toString
private def setBit(stack: collection.mutable.Stack[String], tagMap: collection.mutable.HashMap[String, Int], bit: Int): Unit = {
stack.foreach { scopeElementId =>
val currentBits = tagMap(scopeElementId)
tagMap.put(scopeElementId, currentBits | bit)
}
}
val tagMap = collection.mutable.HashMap[String, Int]()
private def suiteResults =
<table class="sortable">
<tr>
<td>Suite</td>
<td>Duration (ms.)</td>
<td>Succeeded</td>
<td>Failed</td>
<td>Canceled</td>
<td>Ignored</td>
<td>Pending</td>
<td>Total</td>
</tr>
{
val sortedSuiteList = results.suiteList.sortWith { (a, b) =>
if (a.testsFailedCount == b.testsFailedCount) {
if (a.testsCanceledCount == b.testsCanceledCount) {
if (a.testsIgnoredCount == b.testsIgnoredCount) {
if (a.testsPendingCount == b.testsPendingCount)
a.startEvent.suiteName < b.startEvent.suiteName
else
a.testsPendingCount > b.testsPendingCount
}
else
a.testsIgnoredCount > b.testsIgnoredCount
}
else
a.testsCanceledCount > b.testsCanceledCount
}
else
a.testsFailedCount > b.testsFailedCount
}.toArray
sortedSuiteList map { r =>
val elementId = generateElementId
import r._
val suiteAborted = endEvent.isInstanceOf[SuiteAborted]
val totalTestsCount =
testsSucceededCount + testsFailedCount + testsIgnoredCount +
testsPendingCount + testsCanceledCount
val bits =
(if ((testsSucceededCount > 0) ||
((totalTestsCount == 0) && !suiteAborted))
SUCCEEDED_BIT else 0) +
(if ((testsFailedCount > 0) || (suiteAborted)) FAILED_BIT else 0) +
(if (testsIgnoredCount > 0) IGNORED_BIT else 0) +
(if (testsPendingCount > 0) PENDING_BIT else 0) +
(if (testsCanceledCount > 0) CANCELED_BIT else 0)
tagMap.put(elementId, bits)
suiteSummary(elementId, getSuiteFileName(r), r)
}
}
</table>
private def countStyle(prefix: String, count: Int) =
if (count == 0)
prefix + "_zero"
else
prefix
private def durationDisplay(duration: Option[Long]) =
duration.getOrElse("-")
private def suiteSummary(elementId: String, suiteFileName: String, suiteResult: SuiteResult) = {
import suiteResult._
<tr id={ elementId }>
<td class={ appendCombinedStatus("suite_name", suiteResult) }><a href={ "javascript: showDetails('" + suiteFileName + "')" }>{ suiteName }</a></td>
<td class={ appendCombinedStatus("duration", suiteResult) }>{ durationDisplay(duration) }</td>
<td class={ countStyle("succeeded", testsSucceededCount) }>{ testsSucceededCount }</td>
<td class={ countStyle("failed", testsFailedCount) }>{ testsFailedCount }</td>
<td class={ countStyle("canceled", testsCanceledCount) }>{ testsCanceledCount }</td>
<td class={ countStyle("ignored", testsIgnoredCount) }>{ testsIgnoredCount }</td>
<td class={ countStyle("pending", testsPendingCount) }>{ testsPendingCount }</td>
<td class={ appendCombinedStatus("total", suiteResult) }>{ testsSucceededCount + testsFailedCount + testsIgnoredCount + testsPendingCount + testsCanceledCount }</td>
</tr>
}
private def twoLess(indentLevel: Int): Int =
indentLevel - 2 match {
case lev if lev < 0 => 0
case lev => lev
}
private def oneLess(indentLevel: Int): Int =
indentLevel - 1 match {
case lev if lev < 0 => 0
case lev => lev
}
private def scope(elementId: String, message: String, indentLevel: Int) =
<div id={ elementId } class="scope" style={ "margin-left: " + (specIndent * oneLess(indentLevel)) + "px;" }>
{ message }
</div>
private def test(elementId: String, lines: List[String], indentLevel: Int, styleName: String) =
<div id={ elementId } class={ styleName } style={ "margin-left: " + (specIndent * twoLess(indentLevel)) + "px;" }>
<dl>
{
lines.map { line =>
<dt>{ line }</dt>
}
}
</dl>
</div>
private def testWithDetails(elementId: String, lines: List[String], message: String, throwable: Option[Throwable], indentLevel: Int, styleName: String) = {
def getHTMLForStackTrace(stackTraceList: List[StackTraceElement]) =
stackTraceList.map((ste: StackTraceElement) => <div>{ ste.toString }</div>)
def displayErrorMessage(errorMessage: String) = {
// scala automatically change <br /> to <br></br>, which will cause 2 line breaks, use unparsedXml("<br />") to solve it.
val messageLines = errorMessage.split("\n")
if (messageLines.size > 1)
messageLines.map(line => <span>{ xmlContent(line) }{ unparsedXml("<br />") }</span>)
else
<span>{ message }</span>
}
def getHTMLForCause(throwable: Throwable): NodeBuffer = {
val cause = throwable.getCause
if (cause != null) {
<table>
<tr valign="top">
<td align="right"><span class="label">{ Resources.DetailsCause + ":" }</span></td>
<td align="left">{ cause.getClass.getName }</td>
</tr>
<tr valign="top">
<td align="right"><span class="label">{ Resources.DetailsMessage + ":" }</span></td>
<td align="left">
{
if (cause.getMessage != null)
displayErrorMessage(cause.getMessage)
else
<span>{ Resources.None }</span>
}
</td>
</tr>
</table>
<table>
<tr valign="top">
<td align="left" colspan="2">{ getHTMLForStackTrace(cause.getStackTrace.toList) }</td>
</tr>
</table> &+ getHTMLForCause(cause)
}
else new scala.xml.NodeBuffer
}
val (grayStackTraceElements, blackStackTraceElements) =
throwable match {
case Some(throwable) =>
val stackTraceElements = throwable.getStackTrace.toList
throwable match {
case sde: exceptions.StackDepthException =>
(stackTraceElements.take(sde.failedCodeStackDepth), stackTraceElements.drop(sde.failedCodeStackDepth))
case _ => (List(), stackTraceElements)
}
case None => (List(), List())
}
val throwableTitle = throwable.map(_.getClass.getName)
val fileAndLineOption: Option[String] =
throwable match {
case Some(throwable) =>
throwable match {
case stackDepth: StackDepth =>
stackDepth.failedCodeFileNameAndLineNumberString
case _ => None
}
case None => None
}
val linkId = UUID.randomUUID.toString
val contentId = UUID.randomUUID.toString
<div id={ elementId } class={ styleName } style={ "margin-left: " + (specIndent * twoLess(indentLevel)) + "px;" }>
<dl>
{
lines.map { line =>
<dt>{ line }</dt>
}
}
</dl>
<div class="detailstoggle">
<a id={ linkId } href={ "javascript:toggleDetails('" + contentId + "', '" + linkId + "');" }>(Show Details)</a>
</div>
<div id={ contentId } style="display: none">
<table>
{
<tr valign="top">
<td align="left"><span class="label">{ Resources.DetailsMessage + ":" }</span></td>
<td align="left">{ displayErrorMessage(message) }</td>
</tr>
}
{
fileAndLineOption match {
case Some(fileAndLine) =>
<tr valign="top"><td align="left"><span class="label">{ Resources.LineNumber + ":" }</span></td><td align="left"><span>{ "(" + fileAndLine + ")" }</span></td></tr>
case None =>
}
}
{
throwableTitle match {
case Some(title) =>
<tr valign="top"><td align="right"><span class="label">{ Resources.DetailsThrowable + ":" }</span></td><td align="left">{ title }</td></tr>
case None => new scala.xml.NodeBuffer
}
}
</table>
<table>
<tr valign="top"><td align="left" colspan="2">
{ grayStackTraceElements.map((ste: StackTraceElement) => <div class="gray">{ ste.toString }</div>) }
{ blackStackTraceElements.map((ste: StackTraceElement) => <div>{ ste.toString }</div>) }
</td>
</tr>
</table>
{
throwable match {
case Some(t) => getHTMLForCause(t)
case None =>
}
}
</div>
</div>
}
// Chee Seng, I changed oneLess to twoLess here, because markup should indent the same as info.
// I added the call to convertSingleParaToDefinition, so simple one-liner markup looks the same as an info.
// TODO: probably actually show the exception in the HTML report rather than blowing up the reporter, because that means
// the whole suite doesn't get recorded. May want to do this more generally though.
private def markup(elementId: String, text: String, indentLevel: Int, styleName: String) = {
val htmlString = convertAmpersand(convertSingleParaToDefinition(markdownToHtml(text)))
<div id={ elementId } class={ styleName } style={ "margin-left: " + (specIndent * twoLess(indentLevel)) + "px;" }>
{
try XML.loadString(htmlString)
catch {
// I really want to catch a org.xml.sax.SAXParseException, but don't want to depend on the implementation of XML.loadString,
// which may change. If the exception isn't exactly actually a the parse exception, then retrying will likely fail with
// the same exception.
case e: Exception =>
XML.loadString("<div>" + htmlString + "</div>")
}
}
</div>
}
private def tagMapScript =
"tagMap = { \n" +
tagMap.map { case (elementId, bitSet) => "\"" + elementId + "\": " + bitSet }.mkString(", \n") +
"};\n" +
"applyFilter();"
private var eventList = new ListBuffer[Event]()
private var runEndEvent: Option[Event] = None
def apply(event: Event): Unit = {
event match {
case _: DiscoveryStarting =>
case _: DiscoveryCompleted =>
case RunStarting(ordinal, testCount, configMap, formatter, location, payload, threadName, timeStamp) =>
case RunCompleted(ordinal, duration, summary, formatter, location, payload, threadName, timeStamp) =>
runEndEvent = Some(event)
case RunStopped(ordinal, duration, summary, formatter, location, payload, threadName, timeStamp) =>
runEndEvent = Some(event)
case RunAborted(ordinal, message, throwable, duration, summary, formatter, location, payload, threadName, timeStamp) =>
runEndEvent = Some(event)
case SuiteCompleted(ordinal, suiteName, suiteId, suiteClassName, duration, formatter, location, rerunner, payload, threadName, timeStamp) =>
val (suiteEvents, otherEvents) = extractSuiteEvents(suiteId)
eventList = otherEvents
val sortedSuiteEvents = suiteEvents.sorted
if (sortedSuiteEvents.isEmpty)
throw new IllegalStateException("Expected SuiteStarting for completion event: " + event + " in the head of suite events, but we got no suite event at all")
sortedSuiteEvents.head match {
case suiteStarting: SuiteStarting =>
val suiteResult = sortedSuiteEvents.foldLeft(SuiteResult(suiteId, suiteName, suiteClassName, duration, suiteStarting, event, Vector.empty ++ sortedSuiteEvents.tail, 0, 0, 0, 0, 0, 0, true)) { case (r, e) =>
e match {
case testSucceeded: TestSucceeded => r.copy(testsSucceededCount = r.testsSucceededCount + 1)
case testFailed: TestFailed => r.copy(testsFailedCount = r.testsFailedCount + 1)
case testIgnored: TestIgnored => r.copy(testsIgnoredCount = r.testsIgnoredCount + 1)
case testPending: TestPending => r.copy(testsPendingCount = r.testsPendingCount + 1)
case testCanceled: TestCanceled => r.copy(testsCanceledCount = r.testsCanceledCount + 1)
case scopePending: ScopePending => r.copy(scopesPendingCount = r.scopesPendingCount + 1)
case _ => r
}
}
val suiteStartingEvent = sortedSuiteEvents.head.asInstanceOf[SuiteStarting]
if (suiteStartingEvent.formatter != Some(MotionToSuppress)) {
results += suiteResult
makeSuiteFile(suiteResult)
}
case other =>
throw new IllegalStateException("Expected SuiteStarting for completion event: " + event + " in the head of suite events, but we got: " + other)
}
case SuiteAborted(ordinal, message, suiteName, suiteId, suiteClassName, throwable, duration, formatter, location, rerunner, payload, threadName, timeStamp) =>
val (suiteEvents, otherEvents) = extractSuiteEvents(suiteId)
eventList = otherEvents
val sortedSuiteEvents = suiteEvents.sorted
if (sortedSuiteEvents.isEmpty)
throw new IllegalStateException("Expected SuiteStarting for completion event: " + event + " in the head of suite events, but we got no suite event at all")
sortedSuiteEvents.head match {
case suiteStarting: SuiteStarting =>
val suiteResult = sortedSuiteEvents.foldLeft(SuiteResult(suiteId, suiteName, suiteClassName, duration, suiteStarting, event, Vector.empty ++ sortedSuiteEvents.tail, 0, 0, 0, 0, 0, 0, false)) { case (r, e) =>
e match {
case testSucceeded: TestSucceeded => r.copy(testsSucceededCount = r.testsSucceededCount + 1)
case testFailed: TestFailed => r.copy(testsFailedCount = r.testsFailedCount + 1)
case testIgnored: TestIgnored => r.copy(testsIgnoredCount = r.testsIgnoredCount + 1)
case testPending: TestPending => r.copy(testsPendingCount = r.testsPendingCount + 1)
case testCanceled: TestCanceled => r.copy(testsCanceledCount = r.testsCanceledCount + 1)
case scopePending: ScopePending => r.copy(scopesPendingCount = r.scopesPendingCount + 1)
case _ => r