1 package org.apache.maven.surefire.common.junit4;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import org.apache.maven.surefire.report.SafeThrowable;
23 import org.apache.maven.surefire.report.SmartStackTraceParser;
24 import org.apache.maven.surefire.report.StackTraceWriter;
25 import org.junit.runner.notification.Failure;
26
27 import static org.apache.maven.surefire.util.internal.TestClassMethodNameUtils.extractClassName;
28 import static org.apache.maven.surefire.util.internal.TestClassMethodNameUtils.extractMethodName;
29 import static org.apache.maven.surefire.report.SmartStackTraceParser.stackTraceWithFocusOnClassAsString;
30
31
32
33
34
35
36
37 public class JUnit4StackTraceWriter
38 implements StackTraceWriter
39 {
40
41 protected final Failure junitFailure;
42
43
44
45
46
47
48 public JUnit4StackTraceWriter( Failure junitFailure )
49 {
50 this.junitFailure = junitFailure;
51 }
52
53
54
55
56
57
58 public String writeTraceToString()
59 {
60 Throwable t = junitFailure.getException();
61 if ( t != null )
62 {
63 String originalTrace = junitFailure.getTrace();
64 if ( isMultiLineExceptionMessage( t ) )
65 {
66
67 StringBuilder builder = new StringBuilder( originalTrace );
68 String exc = t.getClass().getName() + ": ";
69 if ( originalTrace.startsWith( exc ) )
70 {
71 builder.insert( exc.length(), '\n' );
72 }
73 return builder.toString();
74 }
75 return originalTrace;
76 }
77 return "";
78 }
79
80 protected String getTestClassName()
81 {
82 return extractClassName( junitFailure.getDescription().getDisplayName() );
83 }
84
85 protected String getTestMethodName()
86 {
87 return extractMethodName( junitFailure.getDescription().getDisplayName() );
88 }
89
90 @SuppressWarnings( "ThrowableResultOfMethodCallIgnored" )
91 public String smartTrimmedStackTrace()
92 {
93 Throwable exception = junitFailure.getException();
94 return exception == null
95 ? junitFailure.getMessage()
96 : new SmartStackTraceParser( getTestClassName(), exception, getTestMethodName() ).getString();
97 }
98
99
100
101
102
103
104 public String writeTrimmedTraceToString()
105 {
106 String testClass = getTestClassName();
107 try
108 {
109 Throwable e = junitFailure.getException();
110 return stackTraceWithFocusOnClassAsString( e, testClass );
111 }
112 catch ( Throwable t )
113 {
114 return stackTraceWithFocusOnClassAsString( t, testClass );
115 }
116 }
117
118
119
120
121
122
123 public SafeThrowable getThrowable()
124 {
125 return new SafeThrowable( junitFailure.getException() );
126 }
127
128 private static boolean isMultiLineExceptionMessage( Throwable t )
129 {
130 String msg = t.getLocalizedMessage();
131 if ( msg != null )
132 {
133 int countNewLines = 0;
134 for ( int i = 0, length = msg.length(); i < length; i++ )
135 {
136 if ( msg.charAt( i ) == '\n' )
137 {
138 if ( ++countNewLines == 2 )
139 {
140 break;
141 }
142 }
143 }
144 return countNewLines > 1 || countNewLines == 1 && !msg.trim().endsWith( "\n" );
145 }
146 return false;
147 }
148
149 }