-
Notifications
You must be signed in to change notification settings - Fork 531
/
RunListenerAdapter.java
487 lines (434 loc) · 20.9 KB
/
RunListenerAdapter.java
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
package org.apache.maven.surefire.junitplatform;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import static java.util.Collections.emptyMap;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import static org.apache.maven.surefire.api.util.internal.ObjectUtils.systemProps;
import static org.apache.maven.surefire.shared.lang3.StringUtils.isNotBlank;
import static org.junit.platform.engine.TestExecutionResult.Status.FAILED;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.apache.maven.surefire.api.report.OutputReportEntry;
import org.apache.maven.surefire.api.report.RunMode;
import org.apache.maven.surefire.api.report.TestOutputReceiver;
import org.apache.maven.surefire.api.report.TestOutputReportEntry;
import org.apache.maven.surefire.report.ClassMethodIndexer;
import org.apache.maven.surefire.api.report.TestReportListener;
import org.apache.maven.surefire.report.PojoStackTraceWriter;
import org.apache.maven.surefire.report.RunModeSetter;
import org.apache.maven.surefire.api.report.SafeThrowable;
import org.apache.maven.surefire.api.report.SimpleReportEntry;
import org.apache.maven.surefire.api.report.StackTraceWriter;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.TestSource;
import org.junit.platform.engine.support.descriptor.ClassSource;
import org.junit.platform.engine.support.descriptor.MethodSource;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.TestPlan;
/**
* @since 2.22.0
*/
final class RunListenerAdapter
implements TestExecutionListener, TestOutputReceiver<OutputReportEntry>, RunModeSetter
{
private static final Pattern COMMA_PATTERN = Pattern.compile( "," );
private final ClassMethodIndexer classMethodIndexer = new ClassMethodIndexer();
private final ConcurrentMap<TestIdentifier, Long> testStartTime = new ConcurrentHashMap<>();
private final ConcurrentMap<TestIdentifier, TestExecutionResult> failures = new ConcurrentHashMap<>();
private final ConcurrentMap<String, TestIdentifier> runningTestIdentifiersByUniqueId = new ConcurrentHashMap<>();
private final TestReportListener<TestOutputReportEntry> runListener;
private volatile TestPlan testPlan;
private volatile RunMode runMode;
RunListenerAdapter( TestReportListener<TestOutputReportEntry> runListener )
{
this.runListener = runListener;
}
@Override
public void setRunMode( RunMode runMode )
{
this.runMode = runMode;
}
@Override
public void testPlanExecutionStarted( TestPlan testPlan )
{
this.testPlan = testPlan;
}
@Override
public void testPlanExecutionFinished( TestPlan testPlan )
{
this.testPlan = null;
testStartTime.clear();
}
@Override
public void executionStarted( TestIdentifier testIdentifier )
{
runningTestIdentifiersByUniqueId.put( testIdentifier.getUniqueId(), testIdentifier );
if ( testIdentifier.isContainer()
&& testIdentifier.getSource().filter( ClassSource.class::isInstance ).isPresent() )
{
testStartTime.put( testIdentifier, System.currentTimeMillis() );
runListener.testSetStarting( createReportEntry( testIdentifier ) );
}
else if ( testIdentifier.isTest() )
{
testStartTime.put( testIdentifier, System.currentTimeMillis() );
runListener.testStarting( createReportEntry( testIdentifier ) );
}
}
@Override
public void executionFinished( TestIdentifier testIdentifier, TestExecutionResult testExecutionResult )
{
boolean isClass = testIdentifier.isContainer()
&& testIdentifier.getSource().filter( ClassSource.class::isInstance ).isPresent();
boolean isTest = testIdentifier.isTest();
boolean failed = testExecutionResult.getStatus() == FAILED;
boolean isAssertionError = testExecutionResult.getThrowable()
.filter( AssertionError.class::isInstance ).isPresent();
boolean isRootContainer = testIdentifier.isContainer() && !testIdentifier.getParentId().isPresent();
if ( failed || isClass || isTest )
{
Integer elapsed = computeElapsedTime( testIdentifier );
switch ( testExecutionResult.getStatus() )
{
case ABORTED:
if ( isTest )
{
runListener.testAssumptionFailure(
createReportEntry( testIdentifier, testExecutionResult, elapsed ) );
}
else
{
runListener.testSetCompleted( createReportEntry( testIdentifier, testExecutionResult,
systemProps(), null, elapsed ) );
}
break;
case FAILED:
String reason = safeGetMessage( testExecutionResult.getThrowable().orElse( null ) );
SimpleReportEntry reportEntry = createReportEntry( testIdentifier, testExecutionResult,
reason, elapsed );
if ( isAssertionError )
{
runListener.testFailed( reportEntry );
}
else
{
runListener.testError( reportEntry );
}
if ( isClass || isRootContainer )
{
runListener.testSetCompleted( createReportEntry( testIdentifier, null,
systemProps(), null, elapsed ) );
}
failures.put( testIdentifier, testExecutionResult );
break;
default:
if ( isTest )
{
runListener.testSucceeded( createReportEntry( testIdentifier, null, elapsed ) );
}
else
{
runListener.testSetCompleted(
createReportEntry( testIdentifier, null, systemProps(), null, elapsed ) );
}
}
}
runningTestIdentifiersByUniqueId.remove( testIdentifier.getUniqueId() );
}
private Integer computeElapsedTime( TestIdentifier testIdentifier )
{
Long startTime = testStartTime.remove( testIdentifier );
long endTime = System.currentTimeMillis();
return startTime == null ? null : (int) ( endTime - startTime );
}
private Stream<TestIdentifier> collectAllTestIdentifiersInHierarchy( TestIdentifier testIdentifier )
{
return testIdentifier.getParentId()
.map( runningTestIdentifiersByUniqueId::get )
.map( parentTestIdentifier ->
Stream.concat( Stream.of( parentTestIdentifier ),
collectAllTestIdentifiersInHierarchy( parentTestIdentifier ) ) )
.orElseGet( Stream::empty );
}
private String safeGetMessage( Throwable throwable )
{
try
{
SafeThrowable t = throwable == null ? null : new SafeThrowable( throwable );
return t == null ? null : t.getMessage();
}
catch ( Throwable t )
{
return t.getMessage();
}
}
@Override
public void executionSkipped( TestIdentifier testIdentifier, String reason )
{
boolean isClass = testIdentifier.isContainer()
&& testIdentifier.getSource().filter( ClassSource.class::isInstance ).isPresent();
testStartTime.remove( testIdentifier );
if ( isClass )
{
SimpleReportEntry report = createReportEntry( testIdentifier );
runListener.testSetStarting( report );
for ( TestIdentifier child : testPlan.getChildren( testIdentifier ) )
{
runListener.testSkipped( createReportEntry( child, null, emptyMap(), reason, null ) );
}
runListener.testSetCompleted( report );
}
else
{
runListener.testSkipped( createReportEntry( testIdentifier, null, emptyMap(), reason, null ) );
}
}
private SimpleReportEntry createReportEntry( TestIdentifier testIdentifier,
TestExecutionResult testExecutionResult,
Map<String, String> systemProperties,
String reason,
Integer elapsedTime )
{
String[] classMethodName = toClassMethodName( testIdentifier );
String className = classMethodName[0];
String classText = classMethodName[1];
if ( Objects.equals( className, classText ) )
{
classText = null;
}
boolean failed = testExecutionResult == null || testExecutionResult.getStatus() == FAILED;
String methodName = failed || testIdentifier.isTest() ? classMethodName[2] : null;
String methodText = failed || testIdentifier.isTest() ? classMethodName[3] : null;
if ( Objects.equals( methodName, methodText ) )
{
methodText = null;
}
String methodNameForSTW = methodName;
if ( methodNameForSTW != null && methodNameForSTW.contains( ")[" ) )
{
// don't pass suffix of templated-tests ("[1] ...") on to STW, as it's not part of the method signature
methodNameForSTW = methodNameForSTW.substring( 0, methodNameForSTW.indexOf( ")[" ) + 1 );
}
StackTraceWriter stw = testExecutionResult == null ? null
: toStackTraceWriter( className, methodNameForSTW, testExecutionResult );
return new SimpleReportEntry( runMode, classMethodIndexer.indexClassMethod( className, methodName ), className,
classText, methodName, methodText, stw, elapsedTime, reason, systemProperties );
}
private SimpleReportEntry createReportEntry( TestIdentifier testIdentifier )
{
return createReportEntry( testIdentifier, null, null );
}
private SimpleReportEntry createReportEntry( TestIdentifier testIdentifier,
TestExecutionResult testExecutionResult, Integer elapsedTime )
{
return createReportEntry( testIdentifier, testExecutionResult, emptyMap(), null, elapsedTime );
}
private SimpleReportEntry createReportEntry( TestIdentifier testIdentifier,
TestExecutionResult testExecutionResult, String reason, Integer elapsedTime )
{
return createReportEntry( testIdentifier, testExecutionResult, emptyMap(), reason, elapsedTime );
}
private StackTraceWriter toStackTraceWriter( String realClassName, String realMethodName,
TestExecutionResult testExecutionResult )
{
switch ( testExecutionResult.getStatus() )
{
case ABORTED:
case FAILED:
// Failed tests must have a StackTraceWriter, otherwise Surefire will fail
Throwable exception = testExecutionResult.getThrowable().orElse( null );
return toStackTraceWriter( realClassName, realMethodName, exception );
default:
return testExecutionResult.getThrowable()
.map( t -> toStackTraceWriter( realClassName, realMethodName, t ) )
.orElse( null );
}
}
private StackTraceWriter toStackTraceWriter( String realClassName, String realMethodName, Throwable throwable )
{
return new PojoStackTraceWriter( realClassName, realMethodName, throwable );
}
/**
* <ul>
* <li>[0] class name - used in stacktrace parser</li>
* <li>[1] class display name</li>
* <li>[2] method signature - used in stacktrace parser</li>
* <li>[3] method display name</li>
* </ul>
*
* @param testIdentifier a class or method
* @return 4 elements string array
*/
private String[] toClassMethodName( TestIdentifier testIdentifier )
{
Optional<TestSource> testSource = testIdentifier.getSource();
String display = testIdentifier.getDisplayName();
if ( testSource.filter( MethodSource.class::isInstance ).isPresent() )
{
MethodSource methodSource = testSource.map( MethodSource.class::cast ).get();
String realClassName = methodSource.getClassName();
String[] source = collectAllTestIdentifiersInHierarchy( testIdentifier )
.filter( i -> i.getSource().map( ClassSource.class::isInstance ).orElse( false ) )
.findFirst()
.map( this::toClassMethodName )
.map( s -> new String[] { s[0], s[1] } )
.orElse( new String[] { realClassName, realClassName } );
String parentDisplay =
collectAllTestIdentifiersInHierarchy( testIdentifier )
.filter( identifier -> identifier.getSource().filter( MethodSource.class::isInstance ).isPresent() )
.map( TestIdentifier::getDisplayName )
.collect( joining( " " ) );
boolean needsSpaceSeparator = isNotBlank( parentDisplay ) && !display.startsWith( "[" );
String methodDisplay = parentDisplay + ( needsSpaceSeparator ? " " : "" ) + display;
boolean hasParameterizedParent =
collectAllTestIdentifiersInHierarchy( testIdentifier )
.filter( identifier -> !identifier.getSource().isPresent() )
.map( TestIdentifier::getLegacyReportingName )
.anyMatch( legacyReportingName -> legacyReportingName.matches( "^\\[.+]$" ) );
boolean parameterized = isNotBlank( methodSource.getMethodParameterTypes() ) || hasParameterizedParent;
String methodName = methodSource.getMethodName();
String description = testIdentifier.getLegacyReportingName();
boolean equalDescriptions = methodDisplay.equals( description );
boolean hasLegacyDescription = description.startsWith( methodName + '(' );
boolean hasDisplayName = !equalDescriptions || !hasLegacyDescription;
String methodDesc = parameterized ? description : methodName;
String methodDisp = hasDisplayName ? methodDisplay : methodDesc;
// The behavior of methods getLegacyReportingName() and getDisplayName().
// junit4 || legacy | display
// ==============||==========|==========
// normal || m | m
// param || m[0] | m[0]
// param+displ || m[displ] | m[displ]
// junit5 || legacy | display
// ==============||==========|==========
// normal || m() | m()
// normal+displ || m() | displ
// param || m()[1] | [1] <param>
// param+displ || m()[1] | displ
// Override resulting methodDesc/methodDisp values again, for invocations of
// JUnit5 templated-tests (such as @ParameterizedTest/@RepeatedTest)
// => Include the display-name of the actual invocation as well in the methodDesc of
// each invocation (also according to the 'name=' values of such tests), to have
// more context of what failed also e.g. from output of console reporter
Integer templatedTestInvocationId = extractTemplatedInvocationId( testIdentifier );
if ( templatedTestInvocationId != null )
{
String simpleClassNames = COMMA_PATTERN.splitAsStream( methodSource.getMethodParameterTypes() )
.map( s -> s.substring( 1 + s.lastIndexOf( '.' ) ).trim() )
.collect( joining( ", " ) );
String methodSignature = methodName + '(' + simpleClassNames + ')';
String invocationIdStr = "[" + templatedTestInvocationId + "]";
String displayForDesc = display;
if ( displayForDesc.startsWith( invocationIdStr ) )
{
// a bit hacky, try to prevent including ID multiple times in most default cases
// "foo()[1][1] abc def" -> "foo()[1] abc def"
displayForDesc = displayForDesc.substring( invocationIdStr.length() );
}
methodDesc = methodSignature + invocationIdStr + displayForDesc;
methodDisp = parentDisplay + display;
}
return new String[] {source[0], source[1], methodDesc, methodDisp};
}
else if ( testSource.filter( ClassSource.class::isInstance ).isPresent() )
{
List<String> parentClassDisplays =
collectAllTestIdentifiersInHierarchy( testIdentifier )
.filter( identifier -> identifier.getSource().filter( ClassSource.class::isInstance ).isPresent() )
.map( TestIdentifier::getDisplayName )
.collect( toList() );
Collections.reverse( parentClassDisplays );
String classDisplay = Stream.concat( parentClassDisplays.stream(), Stream.of( display ) )
.collect( joining( " " ) );
ClassSource classSource = testSource.map( ClassSource.class::cast ).get();
String className = classSource.getClassName();
String simpleClassName = className.substring( 1 + className.lastIndexOf( '.' ) );
String source = classDisplay.replace( ' ', '$' ).equals( simpleClassName ) ? className : classDisplay;
return new String[] {className, source, null, null};
}
else
{
String source = testPlan.getParent( testIdentifier )
.map( TestIdentifier::getDisplayName ).orElse( display );
return new String[] {source, source, display, display};
}
}
private static final Pattern TEST_TEMPLATE_INVOCATION_MATCHER =
Pattern.compile( "\\[test-template-invocation:#([1-9][0-9]*)]" );
/**
* If the given test-id defines an invocation of a templated-test (such as a specific
* instance of a @ParameterizedTest or @RepeatedTest), returns the invocation-id of
* that instance (1, 2, ...)
*
* <p>Returns null if the given test-id doesn't seem to be a templated-test invocation,
* or if no invocation-id could be extracted.
*/
private Integer extractTemplatedInvocationId( TestIdentifier testId )
{
/*
Note: with JUnit 5.8+, we could make this nicer using testId.getUniqueIdObject()
# Segment lastSegment = testId.getUniqueIdObject().getLastSegment();
# if (lastSegment.getType().equals(TestTemplateInvocationTestDescriptor.SEGMENT_TYPE)) {
# String invocationIdStr = lastSegment.getValue(); // #1, #2, ...
# if (invocationIdStr.startsWith("#")) { // assuming always true
# return Integer.valueOf(invocationIdStr.substring(1));
# }
# }
*/
Matcher m = TEST_TEMPLATE_INVOCATION_MATCHER.matcher( testId.getUniqueId() );
if ( m.find() )
{
String group = m.group( 1 );
return Integer.valueOf( group );
}
return null;
}
/**
* @return Map of tests that failed.
*/
Map<TestIdentifier, TestExecutionResult> getFailures()
{
return failures;
}
boolean hasFailingTests()
{
return !getFailures().isEmpty();
}
void reset()
{
getFailures().clear();
testPlan = null;
}
@Override
public void writeTestOutput( OutputReportEntry reportEntry )
{
Long testRunId = classMethodIndexer.getLocalIndex();
runListener.writeTestOutput( new TestOutputReportEntry( reportEntry, runMode, testRunId ) );
}
}