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.apache.maven.surefire.util.internal.ClassMethod;
26 import org.junit.runner.notification.Failure;
27
28 import static org.apache.maven.surefire.common.junit4.JUnit4ProviderUtil.toClassMethod;
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 private final Failure junitFailure;
41
42
43
44
45
46
47 public JUnit4StackTraceWriter( Failure junitFailure )
48 {
49 this.junitFailure = junitFailure;
50 }
51
52
53
54
55
56
57 @Override
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 @Override
81 public String smartTrimmedStackTrace()
82 {
83 Throwable exception = junitFailure.getException();
84 ClassMethod classMethod = toClassMethod( junitFailure.getDescription() );
85 return exception == null
86 ? junitFailure.getMessage()
87 : new SmartStackTraceParser( classMethod.getClazz(), exception, classMethod.getMethod() ).getString();
88 }
89
90
91
92
93
94
95 @Override
96 public String writeTrimmedTraceToString()
97 {
98 String testClass = toClassMethod( junitFailure.getDescription() ).getClazz();
99 try
100 {
101 Throwable e = junitFailure.getException();
102 return stackTraceWithFocusOnClassAsString( e, testClass );
103 }
104 catch ( Throwable t )
105 {
106 return stackTraceWithFocusOnClassAsString( t, testClass );
107 }
108 }
109
110
111
112
113
114
115 @Override
116 public SafeThrowable getThrowable()
117 {
118 return new SafeThrowable( junitFailure.getException() );
119 }
120
121 private static boolean isMultiLineExceptionMessage( Throwable t )
122 {
123 String msg = t.getLocalizedMessage();
124 if ( msg != null )
125 {
126 int countNewLines = 0;
127 for ( int i = 0, length = msg.length(); i < length; i++ )
128 {
129 if ( msg.charAt( i ) == '\n' )
130 {
131 if ( ++countNewLines == 2 )
132 {
133 break;
134 }
135 }
136 }
137 return countNewLines > 1 || countNewLines == 1 && !msg.trim().endsWith( "\n" );
138 }
139 return false;
140 }
141
142 }