/
TestResult.java
639 lines (554 loc) · 20.2 KB
/
TestResult.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
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
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Daniel Dyer, id:cactusman, Tom Huybrechts, Yahoo!, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.tasks.junit;
import hudson.AbortException;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.Run;
import hudson.tasks.test.AbstractTestResultAction;
import hudson.tasks.test.MetaTabulatedResult;
import hudson.tasks.test.TestObject;
import hudson.util.IOException2;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.tools.ant.DirectoryScanner;
import org.dom4j.DocumentException;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
/**
* Root of all the test results for one build.
*
* @author Kohsuke Kawaguchi
*/
public final class TestResult extends MetaTabulatedResult {
/**
* List of all {@link SuiteResult}s in this test.
* This is the core data structure to be persisted in the disk.
*/
private final List<SuiteResult> suites = new ArrayList<SuiteResult>();
/**
* {@link #suites} keyed by their names for faster lookup.
*/
private transient Map<String,SuiteResult> suitesByName;
/**
* Results tabulated by package.
*/
private transient Map<String,PackageResult> byPackages;
// set during the freeze phase
private transient AbstractTestResultAction parentAction;
private transient TestObject parent;
/**
* Number of all tests.
*/
private transient int totalTests;
private transient int skippedTests;
private float duration;
/**
* Number of failed/error tests.
*/
private transient List<CaseResult> failedTests;
private final boolean keepLongStdio;
/**
* Creates an empty result.
*/
public TestResult() {
this(false);
}
/**
* @since 1.522
*/
public TestResult(boolean keepLongStdio) {
this.keepLongStdio = keepLongStdio;
}
@Deprecated
public TestResult(long buildTime, DirectoryScanner results) throws IOException {
this(buildTime, results, false);
}
/**
* Collect reports from the given {@link DirectoryScanner}, while
* filtering out all files that were created before the given time.
* @param keepLongStdio if true, retain a suite's complete stdout/stderr even if this is huge and the suite passed
* @since 1.358
*/
public TestResult(long buildTime, DirectoryScanner results, boolean keepLongStdio) throws IOException {
this.keepLongStdio = keepLongStdio;
parse(buildTime, results);
}
public TestObject getParent() {
return parent;
}
@Override
public void setParent(TestObject parent) {
this.parent = parent;
}
@Override
public TestResult getTestResult() {
return this;
}
/**
* Collect reports from the given {@link DirectoryScanner}, while
* filtering out all files that were created before the given time.
*/
public void parse(long buildTime, DirectoryScanner results) throws IOException {
String[] includedFiles = results.getIncludedFiles();
File baseDir = results.getBasedir();
parse(buildTime,baseDir,includedFiles);
}
/**
* Collect reports from the given report files, while
* filtering out all files that were created before the given time.
*
* @since 1.426
*/
public void parse(long buildTime, File baseDir, String[] reportFiles) throws IOException {
boolean parsed=false;
for (String value : reportFiles) {
File reportFile = new File(baseDir, value);
// only count files that were actually updated during this build
if ( (buildTime-3000/*error margin*/ <= reportFile.lastModified())) {
parsePossiblyEmpty(reportFile);
parsed = true;
}
}
if(!parsed) {
long localTime = System.currentTimeMillis();
if(localTime < buildTime-1000) /*margin*/
// build time is in the the future. clock on this slave must be running behind
throw new AbortException(
"Clock on this slave is out of sync with the master, and therefore \n" +
"I can't figure out what test results are new and what are old.\n" +
"Please keep the slave clock in sync with the master.");
File f = new File(baseDir,reportFiles[0]);
throw new AbortException(
String.format(
"Test reports were found but none of them are new. Did tests run? %n"+
"For example, %s is %s old%n", f,
Util.getTimeSpanString(buildTime-f.lastModified())));
}
}
/**
* Collect reports from the given report files
*
* @since 1.500
*/
public void parse(long buildTime, Iterable<File> reportFiles) throws IOException {
boolean parsed=false;
for (File reportFile : reportFiles) {
// only count files that were actually updated during this build
if ( (buildTime-3000/*error margin*/ <= reportFile.lastModified())) {
parsePossiblyEmpty(reportFile);
parsed = true;
}
}
if(!parsed) {
long localTime = System.currentTimeMillis();
if(localTime < buildTime-1000) /*margin*/
// build time is in the the future. clock on this slave must be running behind
throw new AbortException(
"Clock on this slave is out of sync with the master, and therefore \n" +
"I can't figure out what test results are new and what are old.\n" +
"Please keep the slave clock in sync with the master.");
File f = reportFiles.iterator().next();
throw new AbortException(
String.format(
"Test reports were found but none of them are new. Did tests run? %n"+
"For example, %s is %s old%n", f,
Util.getTimeSpanString(buildTime-f.lastModified())));
}
}
private void parsePossiblyEmpty(File reportFile) throws IOException {
if(reportFile.length()==0) {
// this is a typical problem when JVM quits abnormally, like OutOfMemoryError during a test.
SuiteResult sr = new SuiteResult(reportFile.getName(), "", "");
sr.addCase(new CaseResult(sr,"<init>","Test report file "+reportFile.getAbsolutePath()+" was length 0"));
add(sr);
} else {
parse(reportFile);
}
}
private void add(SuiteResult sr) {
for (SuiteResult s : suites) {
// JENKINS-12457: If a testsuite is distributed over multiple files, merge it into a single SuiteResult:
if(s.getName().equals(sr.getName()) && nullSafeEq(s.getId(),sr.getId())) {
// However, a common problem is that people parse TEST-*.xml as well as TESTS-TestSuite.xml.
// In that case consider the result file as a duplicate and discard it.
// see http://jenkins.361315.n4.nabble.com/Problem-with-duplicate-build-execution-td371616.html for discussion.
if(strictEq(s.getTimestamp(),sr.getTimestamp())) {
return;
}
for (CaseResult cr: sr.getCases()) {
s.addCase(cr);
cr.replaceParent(s);
}
duration += sr.getDuration();
return;
}
}
suites.add(sr);
duration += sr.getDuration();
}
private boolean strictEq(Object lhs, Object rhs) {
return lhs != null && rhs != null && lhs.equals(rhs);
}
private boolean nullSafeEq(Object lhs, Object rhs) {
if (lhs == null) {
return rhs == null;
}
return lhs.equals(rhs);
}
/**
* Parses an additional report file.
*/
public void parse(File reportFile) throws IOException {
try {
for (SuiteResult suiteResult : SuiteResult.parse(reportFile, keepLongStdio))
add(suiteResult);
} catch (InterruptedException e) {
throw new IOException2("Failed to read "+reportFile,e);
} catch (RuntimeException e) {
throw new IOException2("Failed to read "+reportFile,e);
} catch (DocumentException e) {
if (!reportFile.getPath().endsWith(".xml")) {
throw new IOException2("Failed to read "+reportFile+"\n"+
"Is this really a JUnit report file? Your configuration must be matching too many files",e);
} else {
SuiteResult sr = new SuiteResult(reportFile.getName(), "", "");
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
String error = "Failed to read test report file "+reportFile.getAbsolutePath()+"\n"+writer.toString();
sr.addCase(new CaseResult(sr,"<init>",error));
add(sr);
throw new IOException2("Failed to read "+reportFile,e);
}
}
}
public String getDisplayName() {
return Messages.TestResult_getDisplayName();
}
@Override
public AbstractBuild<?,?> getOwner() {
return (parentAction == null? null: parentAction.owner);
}
@Override
public hudson.tasks.test.TestResult findCorrespondingResult(String id) {
if (getId().equals(id) || (id == null)) {
return this;
}
String firstElement = null;
String subId = null;
int sepIndex = id.indexOf('/');
if (sepIndex < 0) {
firstElement = id;
subId = null;
} else {
firstElement = id.substring(0, sepIndex);
subId = id.substring(sepIndex + 1);
if (subId.length() == 0) {
subId = null;
}
}
String packageName = null;
if (firstElement.equals(getId())) {
sepIndex = subId.indexOf('/');
if (sepIndex < 0) {
packageName = subId;
subId = null;
} else {
packageName = subId.substring(0, sepIndex);
subId = subId.substring(sepIndex + 1);
}
} else {
packageName = firstElement;
subId = null;
}
PackageResult child = byPackage(packageName);
if (child != null) {
if (subId != null) {
return child.findCorrespondingResult(subId);
} else {
return child;
}
} else {
return null;
}
}
@Override
public String getTitle() {
return Messages.TestResult_getTitle();
}
@Override
public String getChildTitle() {
return Messages.TestResult_getChildTitle();
}
@Exported(visibility=999)
@Override
public float getDuration() {
return duration;
}
@Exported(visibility=999)
@Override
public int getPassCount() {
return totalTests-getFailCount()-getSkipCount();
}
@Exported(visibility=999)
@Override
public int getFailCount() {
if(failedTests==null)
return 0;
else
return failedTests.size();
}
@Exported(visibility=999)
@Override
public int getSkipCount() {
return skippedTests;
}
@Override
public List<CaseResult> getFailedTests() {
return failedTests;
}
/**
* Gets the "children" of this test result that passed
*
* @return the children of this test result, if any, or an empty collection
*/
@Override
public Collection<? extends hudson.tasks.test.TestResult> getPassedTests() {
throw new UnsupportedOperationException(); // TODO: implement!(FIXME: generated)
}
/**
* Gets the "children" of this test result that were skipped
*
* @return the children of this test result, if any, or an empty list
*/
@Override
public Collection<? extends hudson.tasks.test.TestResult> getSkippedTests() {
throw new UnsupportedOperationException(); // TODO: implement!(FIXME: generated)
}
/**
* If this test failed, then return the build number
* when this test started failing.
*/
@Override
public int getFailedSince() {
throw new UnsupportedOperationException(); // TODO: implement!(FIXME: generated)
}
/**
* If this test failed, then return the run
* when this test started failing.
*/
@Override
public Run<?, ?> getFailedSinceRun() {
throw new UnsupportedOperationException(); // TODO: implement!(FIXME: generated)
}
/**
* The stdout of this test.
* <p/>
* <p/>
* Depending on the tool that produced the XML report, this method works somewhat inconsistently.
* With some tools (such as Maven surefire plugin), you get the accurate information, that is
* the stdout from this test case. With some other tools (such as the JUnit task in Ant), this
* method returns the stdout produced by the entire test suite.
* <p/>
* <p/>
* If you need to know which is the case, compare this output from {@link SuiteResult#getStdout()}.
*
* @since 1.294
*/
@Override
public String getStdout() {
StringBuilder sb = new StringBuilder();
for (SuiteResult suite: suites) {
sb.append("Standard Out (stdout) for Suite: " + suite.getName());
sb.append(suite.getStdout());
}
return sb.toString();
}
/**
* The stderr of this test.
*
* @see #getStdout()
* @since 1.294
*/
@Override
public String getStderr() {
StringBuilder sb = new StringBuilder();
for (SuiteResult suite: suites) {
sb.append("Standard Error (stderr) for Suite: " + suite.getName());
sb.append(suite.getStderr());
}
return sb.toString();
}
/**
* If there was an error or a failure, this is the stack trace, or otherwise null.
*/
@Override
public String getErrorStackTrace() {
return "No error stack traces available at this level. Drill down to individual tests to find stack traces.";
}
/**
* If there was an error or a failure, this is the text from the message.
*/
@Override
public String getErrorDetails() {
return "No error details available at this level. Drill down to individual tests to find details.";
}
/**
* @return true if the test was not skipped and did not fail, false otherwise.
*/
@Override
public boolean isPassed() {
return (getFailCount() == 0);
}
@Override
public Collection<PackageResult> getChildren() {
return byPackages.values();
}
/**
* Whether this test result has children.
*/
@Override
public boolean hasChildren() {
return !suites.isEmpty();
}
@Exported(inline=true,visibility=9)
public Collection<SuiteResult> getSuites() {
return suites;
}
@Override
public String getName() {
return "junit";
}
@Override
public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
if (token.equals(getId())) {
return this;
}
PackageResult result = byPackage(token);
if (result != null) {
return result;
} else {
return super.getDynamic(token, req, rsp);
}
}
public PackageResult byPackage(String packageName) {
return byPackages.get(packageName);
}
public SuiteResult getSuite(String name) {
return suitesByName.get(name);
}
@Override
public void setParentAction(AbstractTestResultAction action) {
this.parentAction = action;
tally(); // I want to be sure to inform our children when we get an action.
}
@Override
public AbstractTestResultAction getParentAction() {
return this.parentAction;
}
/**
* Recount my children.
*/
@Override
public void tally() {
/// Empty out data structures
// TODO: free children? memmory leak?
suitesByName = new HashMap<String,SuiteResult>();
failedTests = new ArrayList<CaseResult>();
byPackages = new TreeMap<String,PackageResult>();
totalTests = 0;
skippedTests = 0;
// Ask all of our children to tally themselves
for (SuiteResult s : suites) {
s.setParent(this); // kluge to prevent double-counting the results
suitesByName.put(s.getName(),s);
List<CaseResult> cases = s.getCases();
for (CaseResult cr: cases) {
cr.setParentAction(this.parentAction);
cr.setParentSuiteResult(s);
cr.tally();
String pkg = cr.getPackageName(), spkg = safe(pkg);
PackageResult pr = byPackage(spkg);
if(pr==null)
byPackages.put(spkg,pr=new PackageResult(this,pkg));
pr.add(cr);
}
}
for (PackageResult pr : byPackages.values()) {
pr.tally();
skippedTests += pr.getSkipCount();
failedTests.addAll(pr.getFailedTests());
totalTests += pr.getTotalCount();
}
}
/**
* Builds up the transient part of the data structure
* from results {@link #parse(File) parsed} so far.
*
* <p>
* After the data is frozen, more files can be parsed
* and then freeze can be called again.
*/
public void freeze(TestResultAction parent) {
this.parentAction = parent;
if(suitesByName==null) {
// freeze for the first time
suitesByName = new HashMap<String,SuiteResult>();
totalTests = 0;
failedTests = new ArrayList<CaseResult>();
byPackages = new TreeMap<String,PackageResult>();
}
for (SuiteResult s : suites) {
if(!s.freeze(this)) // this is disturbing: has-a-parent is conflated with has-been-counted
continue;
suitesByName.put(s.getName(),s);
totalTests += s.getCases().size();
for(CaseResult cr : s.getCases()) {
if(cr.isSkipped())
skippedTests++;
else if(!cr.isPassed())
failedTests.add(cr);
String pkg = cr.getPackageName(), spkg = safe(pkg);
PackageResult pr = byPackage(spkg);
if(pr==null)
byPackages.put(spkg,pr=new PackageResult(this,pkg));
pr.add(cr);
}
}
Collections.sort(failedTests,CaseResult.BY_AGE);
for (PackageResult pr : byPackages.values())
pr.freeze();
}
private static final long serialVersionUID = 1L;
}