1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.surefire.junitplatform;
20
21 import java.io.PrintWriter;
22 import java.io.StringWriter;
23 import java.util.Objects;
24
25 import org.apache.maven.surefire.api.report.SafeThrowable;
26 import org.apache.maven.surefire.api.report.StackTraceWriter;
27 import org.apache.maven.surefire.api.util.internal.StringUtils;
28 import org.apache.maven.surefire.report.SmartStackTraceParser;
29
30
31
32
33
34
35 public class DefaultStackTraceWriter implements StackTraceWriter {
36 private final Throwable t;
37
38 private final String testClass;
39
40 private final String testMethod;
41
42 public DefaultStackTraceWriter(String testClass, String testMethod, Throwable t) {
43 this.testClass = testClass;
44 this.testMethod = testMethod;
45 this.t = t;
46 }
47
48 @Override
49 public String writeTraceToString() {
50 if (t != null) {
51 StringWriter w = new StringWriter();
52 try (PrintWriter stackTrace = new PrintWriter(w)) {
53 t.printStackTrace(stackTrace);
54 }
55 StringBuffer builder = w.getBuffer();
56 if (isMultiLineExceptionMessage(t)) {
57
58 String exc = t.getClass().getName() + ": ";
59 if (StringUtils.startsWith(builder, exc)) {
60 builder.insert(exc.length(), '\n');
61 }
62 }
63 return builder.toString();
64 }
65 return "";
66 }
67
68 @Override
69 public String smartTrimmedStackTrace() {
70 return t == null ? "" : new SmartStackTraceParser(testClass, t, testMethod).getString();
71 }
72
73 @Override
74 public String writeTrimmedTraceToString() {
75 return t == null ? "" : SmartStackTraceParser.stackTraceWithFocusOnClassAsString(t, testClass);
76 }
77
78 @Override
79 public SafeThrowable getThrowable() {
80 return t == null ? null : new SafeThrowable(t);
81 }
82
83 private static boolean isMultiLineExceptionMessage(Throwable t) {
84 String msg = t.getLocalizedMessage();
85 if (msg != null) {
86 int countNewLines = 0;
87 for (int i = 0, length = msg.length(); i < length; i++) {
88 if (msg.charAt(i) == '\n') {
89 if (++countNewLines == 2) {
90 break;
91 }
92 }
93 }
94 return countNewLines > 1 || countNewLines == 1 && !msg.trim().endsWith("\n");
95 }
96 return false;
97 }
98
99 @Override
100 public boolean equals(Object o) {
101 if (this == o) {
102 return true;
103 }
104 if (o == null || getClass() != o.getClass()) {
105 return false;
106 }
107 DefaultStackTraceWriter that = (DefaultStackTraceWriter) o;
108 return Objects.equals(t, that.t)
109 && Objects.equals(testClass, that.testClass)
110 && Objects.equals(testMethod, that.testMethod);
111 }
112
113 @Override
114 public int hashCode() {
115 return Objects.hash(t, testClass, testMethod);
116 }
117 }