forked from hpsa/hpe-application-automation-tools-plugin
/
RunResultRecorder.java
1640 lines (1431 loc) · 65.1 KB
/
RunResultRecorder.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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Certain versions of software accessible here may contain branding from Hewlett-Packard Company (now HP Inc.) and Hewlett Packard Enterprise Company.
* This software was acquired by Micro Focus on September 1, 2017, and is now offered by OpenText.
* Any reference to the HP and Hewlett Packard Enterprise/HPE marks is historical in nature, and the HP and Hewlett Packard Enterprise/HPE marks are the property of their respective owners.
* __________________________________________________________________
* MIT License
*
* Copyright 2012-2023 Open Text
*
* The only warranties for products and services of Open Text and
* its affiliates and licensors ("Open Text") are as may be set forth
* in the express warranty statements accompanying such products and services.
* Nothing herein should be construed as constituting an additional warranty.
* Open Text shall not be liable for technical or editorial errors or
* omissions contained herein. The information contained herein is subject
* to change without notice.
*
* Except as specifically indicated otherwise, this document contains
* confidential information and a valid license is required for possession,
* use or copying. If this work is provided to the U.S. Government,
* consistent with FAR 12.211 and 12.212, Commercial Computer Software,
* Computer Software Documentation, and Technical Data for Commercial Items are
* licensed to the U.S. Government under vendor's standard commercial license.
*
* 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.
* ___________________________________________________________________
*/
package com.microfocus.application.automation.tools.results;
import com.microfocus.application.automation.tools.JenkinsUtils;
import com.microfocus.application.automation.tools.common.RuntimeUtils;
import com.microfocus.application.automation.tools.model.EnumDescription;
import com.microfocus.application.automation.tools.model.ResultsPublisherModel;
import com.microfocus.application.automation.tools.results.projectparser.performance.*;
import com.microfocus.application.automation.tools.run.PcBuilder;
import com.microfocus.application.automation.tools.run.RunFromAlmBuilder;
import com.microfocus.application.automation.tools.run.RunFromFileBuilder;
import com.microfocus.application.automation.tools.run.SseBuilder;
import com.microfocus.application.automation.tools.uft.utils.UftToolUtils;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.matrix.MatrixAggregatable;
import hudson.matrix.MatrixAggregator;
import hudson.matrix.MatrixBuild;
import hudson.model.*;
import hudson.remoting.VirtualChannel;
import hudson.tasks.*;
import hudson.tasks.junit.*;
import hudson.tasks.test.TestResultAggregator;
import jenkins.model.Jenkins;
import jenkins.tasks.SimpleBuildStep;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.AgeFileFilter;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.kohsuke.stapler.DataBoundConstructor;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.annotation.Nonnull;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.*;
import static com.microfocus.application.automation.tools.results.projectparser.performance.XmlParserUtil.getNode;
import static com.microfocus.application.automation.tools.results.projectparser.performance.XmlParserUtil.getNodeAttr;
/**
* using {@link JUnitResultArchiver};
*
* @author Thomas Maurel
*/
public class RunResultRecorder extends Recorder implements Serializable, MatrixAggregatable, SimpleBuildStep {
public static final String REPORT_NAME_FIELD = "report";
public static final int SECS_IN_DAY = 86400;
public static final int SECS_IN_HOUR = 3600;
public static final int SECS_IN_MINUTE = 60;
public static final String SLA_ULL_NAME = "FullName";
public static final String ARCHIVING_TEST_REPORTS_FAILED_DUE_TO_XML_PARSING_ERROR =
"Archiving test reports failed due to xml parsing error: ";
private static final long serialVersionUID = 1L;
private static final String PERFORMANCE_REPORT_FOLDER = "PerformanceReport";
private static final String IE_REPORT_FOLDER = "IE";
private static final String HTML_REPORT_FOLDER = "HTML";
private static final String LRA_FOLDER = "LRA";
private static final String INDEX_HTML_NAME = "index.html";
private static final String REPORT_INDEX_NAME = "report.index";
private static final String TRANSACTION_SUMMARY_FOLDER = "TransactionSummary";
private static final String RICH_REPORT_FOLDER = "RichReport";
private static final String TRANSACTION_REPORT_NAME = "TransactionReport";
private static final String SLA_ACTUAL_VALUE_LABEL = "ActualValue";
private static final String SLA_GOAL_VALUE_LABEL = "GoalValue";
private static final String NO_RICH_REPORTS_ERROR = "Template contains no rich reports.";
private static final String NO_TRANSACTION_SUMMARY_REPORT_ERROR = "Template contains no transaction summary " +
"report.";
private static final String PARALLEL_RESULT_FILE = "parallelrun_results.html";
private static final String REPORT_ARCHIVE_SUFFIX = "_Report.zip";
private static final String RUN_RESULTS_XML = "run_results.xml";
private static final String RESULT = "Result";
private final ResultsPublisherModel _resultsPublisherModel;
private List<FilePath> runReportList;
/**
* Instantiates a new Run result recorder.
*
* @param archiveTestResultsMode the archive test results mode
*/
@DataBoundConstructor
public RunResultRecorder(String archiveTestResultsMode) {
_resultsPublisherModel = new ResultsPublisherModel(archiveTestResultsMode);
}
private static void addTimeRanges(TimeRangeResult transactionTimeRange, Element slaRuleElement) {
Node timeRangeNode;
Element timeRangeElement;
NodeList timeRanges = slaRuleElement.getElementsByTagName("TimeRangeInfo");
if (timeRanges == null || timeRanges.getLength() == 0) {
return;
}
// Taking the goal per transaction -
double generalGoalValue = Double.parseDouble(((Element) timeRanges.item(0)).getAttribute(SLA_GOAL_VALUE_LABEL));
transactionTimeRange.setGoalValue(generalGoalValue);
for (int k = 0; k < timeRanges.getLength(); k++) {
timeRangeNode = timeRanges.item(k);
timeRangeElement = (Element) timeRangeNode;
double actualValue = Double.parseDouble(timeRangeElement.getAttribute(SLA_ACTUAL_VALUE_LABEL));
double goalValue = Double.parseDouble(timeRangeElement.getAttribute(SLA_GOAL_VALUE_LABEL));
int loadValue = Integer.parseInt(timeRangeElement.getAttribute("LoadValue"));
double startTime = Double.parseDouble(timeRangeElement.getAttribute("StartTime"));
double endTIme = Double.parseDouble(timeRangeElement.getAttribute("EndTime"));
transactionTimeRange.incActualValue(actualValue);
LrTest.SLA_STATUS slaStatus = LrTest.SLA_STATUS
.checkStatus(timeRangeElement.getFirstChild().getTextContent());
TimeRange timeRange = new TimeRange(actualValue, goalValue, slaStatus, loadValue, startTime, endTIme);
transactionTimeRange.getTimeRanges().add(timeRange);
}
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
/**
* Pipeline perform.
*
* @param build the build
* @param workspace the workspace
* @param launcher the launcher
* @param listener the listener
* @param builderResultNames the builder result names
* @throws IOException the io exception
* @throws InterruptedException the interrupted exception
*/
// temporary solution to deal with lack of support in builder list when Project
// is replaced by job type in pipeline.
// Should be dealt with general refactoring - making this a job property or
// change folder structure to scan instead
// of passing file name from builder.
@SuppressWarnings("squid:S1160")
public void pipelinePerform(@Nonnull Run<?, ?> build, @Nonnull FilePath workspace, @Nonnull Launcher launcher,
@Nonnull TaskListener listener, @Nonnull Map<String, String> builderResultNames)
throws IOException, InterruptedException {
final List<String> mergedResultNames = new ArrayList<String>();
runReportList = new ArrayList<FilePath>();
final List<String> fileSystemResultNames = new ArrayList<String>();
fileSystemResultNames.add(builderResultNames.get(RunFromFileBuilder.class.getName()));
mergedResultNames.addAll(builderResultNames.values());
if (mergedResultNames.isEmpty()) {
listener.getLogger().println("RunResultRecorder: no results xml File provided");
return;
}
recordRunResults(build, workspace, launcher, listener, mergedResultNames, fileSystemResultNames);
return;
}
/**
* Records LR test results copied in JUnit format
*
* @param build
* @param workspace
* @param launcher
* @param listener
* @param mergedResultNames
* @param fileSystemResultNames
* @throws InterruptedException
* @throws IOException
*/
private void recordRunResults(@Nonnull Run<?, ?> build, @Nonnull FilePath workspace, @Nonnull Launcher launcher,
@Nonnull TaskListener listener, List<String> mergedResultNames, List<String> fileSystemResultNames)
throws InterruptedException, IOException {
for (String resultFile : mergedResultNames) {
JUnitResultArchiver jUnitResultArchiver = new JUnitResultArchiver(resultFile);
jUnitResultArchiver.setKeepLongStdio(true);
jUnitResultArchiver.setAllowEmptyResults(true);
jUnitResultArchiver.setSkipMarkingBuildUnstable(true);
jUnitResultArchiver.perform(build, workspace, launcher, listener);
}
final TestResultAction tempAction = build.getAction(TestResultAction.class);
if (tempAction == null || tempAction.getResult() == null) {
listener.getLogger().println("RunResultRecorder: didn't find any test results to record");
return;
}
TestResult result = tempAction.getResult();
try {
archiveTestsReport(build, listener, fileSystemResultNames, result, workspace);
} catch (ParserConfigurationException | SAXException e) {
listener.error(ARCHIVING_TEST_REPORTS_FAILED_DUE_TO_XML_PARSING_ERROR + e);
}
if ((runReportList != null) && !(runReportList.isEmpty())) {
LrJobResults jobDataSet = null;
try {
jobDataSet = buildJobDataset(listener);
} catch (ParserConfigurationException | SAXException e) {
listener.error(ARCHIVING_TEST_REPORTS_FAILED_DUE_TO_XML_PARSING_ERROR + e);
}
if ((jobDataSet != null && !jobDataSet.getLrScenarioResults().isEmpty())) {
PerformanceJobReportAction performanceJobReportAction = build
.getAction(PerformanceJobReportAction.class);
if (performanceJobReportAction != null) {
performanceJobReportAction.mergeResults(jobDataSet);
} else {
performanceJobReportAction = new PerformanceJobReportAction(build, jobDataSet);
}
build.replaceAction(performanceJobReportAction);
}
}
publishLrReports(build);
}
/**
* Adds the html reports actions to the left side menu.
*
* @param build
*/
private void publishLrReports(@Nonnull Run<?, ?> build) throws IOException {
File reportDirectory = new File(build.getRootDir(), PERFORMANCE_REPORT_FOLDER);
if (reportDirectory.exists()) {
File htmlIndexFile = new File(reportDirectory, INDEX_HTML_NAME);
if (htmlIndexFile.exists()) {
build.replaceAction(new PerformanceReportAction(build));
}
}
File summaryDirectory = new File(build.getRootDir(), TRANSACTION_SUMMARY_FOLDER);
if (summaryDirectory.exists()) {
File htmlIndexFile = new File(summaryDirectory, INDEX_HTML_NAME);
if (htmlIndexFile.exists()) {
build.replaceAction(new TransactionSummaryAction(build));
}
}
File richDirectory = new File(build.getRootDir(), RICH_REPORT_FOLDER);
if (richDirectory.exists()) {
File htmlIndexFile = new File(richDirectory, INDEX_HTML_NAME);
if (htmlIndexFile.exists()) {
build.replaceAction(new RichReportAction(build));
}
}
}
/**
* checks if the given report path is a parallel runner report
*
* @param reportPath the path containing the report files
* @throws IOException
* @throws InterruptedException
*/
private boolean isParallelRunnerReportPath(FilePath reportPath) throws IOException, InterruptedException {
FilePath parallelRunnerResultsFile = new FilePath(reportPath, PARALLEL_RESULT_FILE);
return parallelRunnerResultsFile.exists();
}
/**
* copies, archives and creates the Test reports of LR and UFT runs.
*
* @param build
* @param listener
* @param resultFiles
* @param testResult
* @param runWorkspace
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
* @throws InterruptedException
*/
@SuppressWarnings({ "squid:S134", "squid:S135" })
private void archiveTestsReport(Run<?, ?> build, TaskListener listener, List<String> resultFiles,
TestResult testResult, FilePath runWorkspace)
throws ParserConfigurationException, SAXException, IOException, InterruptedException {
if ((resultFiles == null) || (resultFiles.isEmpty())) { return; }
ArrayList<String> zipFileNames = new ArrayList<String>();
ArrayList<FilePath> reportFolders = new ArrayList<FilePath>();
List<String> reportNames = new ArrayList<String>();
listener.getLogger()
.println("Report archiving mode is set to: " + _resultsPublisherModel.getArchiveTestResultsMode());
// if user specified not to archive report
if (_resultsPublisherModel.getArchiveTestResultsMode()
.equals(ResultsPublisherModel.dontArchiveResults.getValue()))
return;
FilePath projectWS = runWorkspace;
// get the artifacts directory where we will upload the zipped report
// folder
File artifactsDir = new File(build.getRootDir(), "archive");
artifactsDir.mkdirs();
// read each result.xml
/*
* The structure of the result file is: <testsuites> <testsuite>
* <testcase.........report="path-to-report"/>
* <testcase.........report="path-to-report"/>
* <testcase.........report="path-to-report"/>
* <testcase.........report="path-to-report"/> </testsuite> </testsuites>
*/
// add previous report names for aggregation when using pipelines.
PerformanceJobReportAction performanceJobReportAction = build.getAction(PerformanceJobReportAction.class);
if (performanceJobReportAction != null) {
reportNames.addAll(performanceJobReportAction.getLrResultBuildDataset().getLrScenarioResults().keySet());
}
EnvVars env = build.getEnvironment(listener);
hudson.model.Node node = Jenkins.get().getNode(env.get("NODE_NAME"));
VirtualChannel channel;
String nodeName = "";
if (node != null) {
channel = node.getChannel();
nodeName = node.getNodeName();
} else {
channel = projectWS.getChannel();
try {
node = JenkinsUtils.getCurrentNode(runWorkspace);
nodeName = node != null ? node.getNodeName() : "";
listener.getLogger().println("Node name = " + nodeName);
} catch (Exception e) {
listener.getLogger().println("Failed to get the current Node: " + e.getMessage());
}
}
for (String resultsFilePath : resultFiles) {
FilePath resultsFile = projectWS.child(resultsFilePath);
List<ReportMetaData> ReportInfoToCollect = new ArrayList<ReportMetaData>();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(resultsFile.read());
doc.getDocumentElement().normalize();
Node testSuiteNode = doc.getElementsByTagName("testsuite").item(0);
Element testSuiteElement = (Element) testSuiteNode;
if (testSuiteElement.hasAttribute("name") && testSuiteElement.getAttribute("name").endsWith(".lrs")) { // LR
// test
NodeList testSuiteNodes = doc.getElementsByTagName("testsuite");
for (int i = 0; i < testSuiteNodes.getLength(); i++) {
testSuiteNode = testSuiteNodes.item(i);
testSuiteElement = (Element) testSuiteNode;
if (!testSuiteElement.hasAttribute("name")) {
continue;
}
String testFolderPath = testSuiteElement.getAttribute("name");
int testPathArr = testFolderPath.lastIndexOf('\\');
String testName = testFolderPath.substring(testPathArr + 1);
reportNames.add(testName);
String testStatus = ("0".equals(testSuiteElement.getAttribute("failures"))) ? "pass" : "fail";
Node testCaseNode = testSuiteElement.getElementsByTagName("testcase").item(0);
if (testCaseNode == null) {
listener.getLogger().println("No report folder was found in results");
return;
}
if (testCaseNode.getNodeType() == Node.ELEMENT_NODE) {
Element testCaseElement = (Element) testCaseNode;
if (!testCaseElement.hasAttribute(REPORT_NAME_FIELD)) {
continue;
}
String reportFolderPath = testCaseElement.getAttribute(REPORT_NAME_FIELD);
FilePath reportFolder = new FilePath(projectWS.getChannel(), reportFolderPath);
reportFolders.add(reportFolder);
FilePath testFolder = new FilePath(projectWS.getChannel(), testFolderPath);
String zipFileName = getUniqueZipFileNameInFolder(zipFileNames, testFolder.getName(), "LR");
FilePath archivedFile = new FilePath(new FilePath(artifactsDir), zipFileName);
if (archiveFolder(reportFolder, testStatus, archivedFile, listener)) {
zipFileNames.add(zipFileName);
}
createRichReports(reportFolder, testFolderPath, artifactsDir, reportNames, testResult,
listener);
createHtmlReport(reportFolder, testFolderPath, artifactsDir, reportNames, testResult);
createTransactionSummary(reportFolder, testFolderPath, artifactsDir, reportNames, testResult);
try {
FilePath testSla = copyRunReport(reportFolder, build.getRootDir(), testFolder.getName());
if (testSla == null) {
listener.getLogger().println("no RunReport.xml file was created");
} else {
runReportList.add(testSla);
}
} catch (IOException | InterruptedException e) {
listener.getLogger().println(e);
}
}
}
} else { // UFT Test
boolean isHtmlReport = false;
NodeList testCasesNodes = ((Element) testSuiteNode).getElementsByTagName("testcase");
// to keep counting how many times this TestName have appeared, used for counting the correct count of appearance
Map<String, Integer> fileNameCount = new HashMap<>();
// to keep counting how many times this TestPath have appeared, used for accessing the correct Report dir
Map<String, Integer> filePathCount = new HashMap<>();
for (int i = 0; i < testCasesNodes.getLength(); i++) {
Node nNode = testCasesNodes.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
if (!eElement.hasAttribute(REPORT_NAME_FIELD)) {
continue;
}
String reportFolderPath = eElement.getAttribute(REPORT_NAME_FIELD); // e.g. "C:\UFTTest\GuiTest1\Report"
String testFolderPath = eElement.getAttribute("name"); // e.g. "C:\UFTTest\GuiTest1"
String testStatus = eElement.getAttribute("status"); // e.g. "pass"
Node nodeSystemInfo = eElement.getElementsByTagName("system-out").item(0);
String sysInfo = nodeSystemInfo.getFirstChild().getNodeValue();
String testDateTime = sysInfo.substring(0, 19);
FilePath testFileFullName = new FilePath(channel, testFolderPath);
if(!testFileFullName.exists()){
break;
}
String testName = testFileFullName.getName();
int nameCount = 1;
if (fileNameCount.containsKey(testName)) {
nameCount = fileNameCount.get(testName) + 1;
}
// update the count for this file
fileNameCount.put(testName, nameCount);
testName += "[" + nameCount + "]";
String testPath = testFileFullName.getRemote();
int pathCount = 1;
if (filePathCount.containsKey(testPath)) {
pathCount = filePathCount.get(testPath) + 1;
}
// update the count for this path
filePathCount.put(testPath, pathCount);
String reportIndex = "";
if (filePathCount.get(testPath) != null) {
reportIndex = Integer.toString(filePathCount.get(testPath));
} else {
reportIndex = "1";
}
FilePath reportFolder = new FilePath(channel, reportFolderPath + reportIndex);
if (!reportFolder.exists()) {
reportFolder = new FilePath(channel, reportFolderPath);
}
if(!reportFolder.exists()){
listener.getLogger().println("Report folder does not exist.");
}
boolean isParallelRunnerReport = isParallelRunnerReportPath(reportFolder);
reportFolders.add(reportFolder);
String archiveTestResultMode = _resultsPublisherModel.getArchiveTestResultsMode();
boolean archiveTestResult;
// check for the new html report
FilePath htmlReport = new FilePath(reportFolder,
isParallelRunnerReport ? PARALLEL_RESULT_FILE : "run_results.html");
ReportMetaData reportMetaData = new ReportMetaData();
if (htmlReport.exists()) {
isHtmlReport = true;
String htmlReportDir = reportFolder.getRemote();
reportMetaData.setFolderPath(htmlReportDir);
reportMetaData.setIsHtmlReport(true);
reportMetaData.setDateTime(testDateTime);
reportMetaData.setStatus(testStatus);
reportMetaData.setIsParallelRunnerReport(isParallelRunnerReport); // we need to handle
// the type for this report
String resourceUrl = "artifact/UFTReport/" + (StringUtils.isBlank(nodeName) ? "" : nodeName + "/") + testName + "/Result";
reportMetaData.setResourceURL(resourceUrl);
reportMetaData.setDisPlayName(testName); // use the name, not the full path
reportMetaData.computeStResFolders(new FilePath(reportFolder, RUN_RESULTS_XML), listener);
// don't know reportMetaData's URL path yet, we will generate it later.
ReportInfoToCollect.add(reportMetaData);
}
archiveTestResult = isArchiveTestResult(testStatus, archiveTestResultMode);
if (archiveTestResult) {
if (reportFolder.exists()) {
FilePath testFolder = new FilePath(channel, testFolderPath);
String zipFileName = getUniqueZipFileNameInFolder(zipFileNames, (StringUtils.isBlank(nodeName) ? "" : nodeName + "_") + testFolder.getName(), "UFT");
zipFileNames.add(zipFileName);
try (ByteArrayOutputStream outStr = new ByteArrayOutputStream()) {
// don't use FileFilter for zip, or it will cause bug when files are on slave
reportFolder.zip(outStr);
/*
* I did't use copyRecursiveTo or copyFrom due to bug in
* jekins:https://issues.jenkins-ci.org/browse /JENKINS-9189 //(which is
* cleaimed to have been fixed, but not. So I zip the folder to stream and copy
* it to the master.
*/
try (InputStream instr = new ByteArrayInputStream(outStr.toByteArray())) {
FilePath archivedFile = new FilePath(new FilePath(artifactsDir), zipFileName);
archivedFile.copyFrom(instr);
}
}
// add to Report list
String zipFileUrlName = "artifact/" + zipFileName;
reportMetaData.setArchiveUrl(zipFileUrlName);
} else {
listener.getLogger().println("No report folder was found in: " + reportFolderPath);
}
}
}
}
if (isHtmlReport && !ReportInfoToCollect.isEmpty()) {
collectAndPrepareHtmlReports(build, listener, ReportInfoToCollect, runWorkspace, nodeName);
}
if (!ReportInfoToCollect.isEmpty()) {
int index = 1;
String reportName = "report_metadata" + "_" + index + ".xml";
// serialize report metadata
synchronized (HtmlBuildReportAction.class) {
while (new File(artifactsDir.getParent(), reportName).exists()) {
index++;
reportName = "report_metadata" + "_" + index + ".xml";
}
File reportMetaDataXmlFile = new File(artifactsDir.getParent(), reportName);
String reportMetaDataXml = reportMetaDataXmlFile.getAbsolutePath();
writeReportMetaData2XML(ReportInfoToCollect, reportMetaDataXml, listener);
// Add UFT report action
try {
listener.getLogger().println("Adding a report action to the current build.");
HtmlBuildReportAction reportAction = new HtmlBuildReportAction(build, reportName, index);
build.addAction(reportAction);
} catch (IOException | SAXException | ParserConfigurationException ex) {
listener.getLogger().println("a problem adding action: " + ex);
}
}
}
}
}
}
private void writeReportMetaData2XML(List<ReportMetaData> htmlReportsInfo, String xmlFile, TaskListener _logger) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
_logger.error("Failed creating xml doc report: " + e);
return;
}
Document doc = builder.newDocument();
Element root = doc.createElement("reports_data");
doc.appendChild(root);
int currentReport = 1;
for (ReportMetaData htmlReportInfo : htmlReportsInfo) {
String disPlayName = htmlReportInfo.getDisPlayName();
String urlName = htmlReportInfo.getUrlName();
String resourceURL = htmlReportInfo.getResourceURL();
String dateTime = htmlReportInfo.getDateTime();
String status = htmlReportInfo.getStatus();
String isHtmlReport = htmlReportInfo.getIsHtmlReport() ? "true" : "false";
String isParallelRunnerReport = htmlReportInfo.getIsParallelRunnerReport() ? "true" : "false";
String archiveUrl = htmlReportInfo.getArchiveUrl();
Element elmReport = doc.createElement(REPORT_NAME_FIELD);
elmReport.setAttribute("disPlayName", disPlayName);
elmReport.setAttribute("urlName", urlName);
elmReport.setAttribute("resourceURL", resourceURL);
elmReport.setAttribute("dateTime", dateTime);
elmReport.setAttribute("status", status);
elmReport.setAttribute("isHtmlreport", isHtmlReport);
elmReport.setAttribute("isParallelRunnerReport", isParallelRunnerReport);
elmReport.setAttribute("archiveUrl", archiveUrl);
root.appendChild(elmReport);
currentReport++;
}
try {
write2XML(doc, xmlFile);
} catch (TransformerException e) {
_logger.error("Failed transforming xml file: " + e);
_logger.getLogger().println("Failed transforming xml file: " + e);
} catch (FileNotFoundException e) {
_logger.error("Failed to find " + xmlFile + ": " + e);
_logger.getLogger().println("Failed to find " + xmlFile + ": " + e);
}
}
private void write2XML(Document document, String filename)
throws TransformerException, FileNotFoundException {
document.normalize();
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(document);
PrintWriter pw = new PrintWriter(new FileOutputStream(filename));
StreamResult result = new StreamResult(pw);
transformer.transform(source, result);
}
private void renamePath(FilePath src, FilePath dest, TaskListener listener, int idxOfRetry) {
try {
if (idxOfRetry > 5) {
listener.getLogger().println("Failed to rename report path [" + src.getRemote() + "] as [" + dest.getRemote() + "] after 5 retries.");
return;
}
Thread.sleep(1500);
src.renameTo(dest);
if (idxOfRetry > 0) {
String msg = String.format("Successfully renamed report path as [%s] after %d %s.", dest.getRemote(), idxOfRetry, (idxOfRetry == 1 ? "retry" : "retries"));
listener.getLogger().println(msg);
}
} catch(Exception e) {
renamePath(src, dest, listener, ++idxOfRetry);
}
}
private Boolean collectAndPrepareHtmlReports(Run build, TaskListener listener, List<ReportMetaData> htmlReportsInfo, FilePath runWorkspace, String nodeName) {
File reportMainDir = new File(new File(build.getRootDir(), "archive"), "UFTReport");
if (StringUtils.isNotBlank(nodeName)) {
reportMainDir = new File(reportMainDir, nodeName);
}
try {
for (ReportMetaData htmlReportInfo : htmlReportsInfo) {
// make sure it's a html report
if (!htmlReportInfo.getIsHtmlReport()) {
continue;
}
String testName = htmlReportInfo.getDisPlayName(); // like "GuiTest1"
File reportDir = new File(reportMainDir, testName);
String htmlReportDir = htmlReportInfo.getFolderPath(); // C:\UFTTest\GuiTest1\Report
try {
for (String subdir : htmlReportInfo.getStResFolders()) {
File dir = new File(htmlReportDir);
String testFolderPath = dir.getPath().substring(0, dir.getPath().lastIndexOf('\\'));
String stResPath = new File(testFolderPath, subdir).getAbsolutePath();
if (UftToolUtils.getFilePath(nodeName, stResPath).exists()) {
archiveAndCopyReportFolder(runWorkspace, reportDir, stResPath);
}
}
} catch (Exception e){
listener.getLogger().println("Path to test folder not found");
}
//for example: C:\Program Files (x86)\Jenkins\workspace\job_name
// archive and copy to the subdirs of master
archiveAndCopyReportFolder(runWorkspace, reportDir, htmlReportDir);
// zip copy and unzip
// now,all the files are in the C:\Program Files (x86)\Jenkins\jobs\testAction\builds\35\archive\UFTReport\Report**
// we need to rename the above path to targetPath.
// So at last we got files in C:\Program Files (x86)\Jenkins\jobs\testAction\builds\35\archive\UFTReport\GuiTest\Result
String unzippedFileName = FilenameUtils.getName(htmlReportDir);
FilePath rootTarget = new FilePath(reportDir);
FilePath targetPath = new FilePath(rootTarget, RESULT);
if(targetPath.exists()){
continue;
}
// C:\Program Files (x86)\Jenkins\jobs\testAction\builds\35\archive\UFTReport\GuiTest1"
FilePath unzippedFolderPath = new FilePath(rootTarget, unzippedFileName);
// C:\Program Files\(x86)\Jenkins\jobs\testAction\builds\35\archive\UFTReport\Report
// rename unzippedFolderPath to targetPath
renamePath(unzippedFolderPath, targetPath, listener, 0);
// fill in the urlName of this report. we need a network path not a FS path
String resourceUrl = htmlReportInfo.getResourceURL();
//parallel runner
FilePath source = new FilePath(runWorkspace, htmlReportDir);
// if it's a parallel runner report path, we must change the resFileName
boolean isParallelRunner = isParallelRunnerReportPath(source);
String resFileName = isParallelRunner ? "/parallelrun_results.html" : "/run_results.html";
String urlName = resourceUrl + resFileName; // like artifact/UFTReport/GuiTest1/run_results.html
// or for Parallel runner /GuiTest1[1]/parallelrun_results.html
htmlReportInfo.setUrlName(urlName);
}
} catch (Exception ex) {
listener.getLogger().println("catch exception in collectAndPrepareHtmlReports: " + ex);
listener.getLogger().println(ex.getMessage());
listener.getLogger().println(ex.getCause());
listener.getLogger().println(ex.getStackTrace());
}
return true;
}
private void archiveAndCopyReportFolder(FilePath runWorkspace, File reportDir, String htmlReportDir) throws IOException, InterruptedException {
FilePath rootTarget = new FilePath(reportDir);
FilePath source = new FilePath(runWorkspace, htmlReportDir);
String zipFileName = "UFT_Report_HTML_tmp.zip";
FilePath archivedFile = new FilePath(rootTarget, zipFileName);
try (ByteArrayOutputStream outStr = new ByteArrayOutputStream()) {
source.zip(outStr);
try (ByteArrayInputStream inStr = new ByteArrayInputStream(outStr.toByteArray())) {
//copy from slave to master
archivedFile.copyFrom(inStr);
}
// end zip copy and unzip
archivedFile.unzip(rootTarget);
//delete temporary archive UFT_Report_HTML_tmp.zip
archivedFile.delete();
}
}
/**
* Copies the run report from the executing node to the Jenkins master for
* processing.
*
* @param reportFolder
* @param buildDir
* @param scenarioName
* @return
* @throws IOException
* @throws InterruptedException
*/
private FilePath copyRunReport(FilePath reportFolder, File buildDir, String scenarioName)
throws IOException, InterruptedException {
FilePath slaReportFilePath = new FilePath(reportFolder, "RunReport.xml");
if (slaReportFilePath.exists()) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
slaReportFilePath.zip(baos);
File slaDirectory = new File(buildDir, "RunReport");
if (!slaDirectory.exists()) {
slaDirectory.mkdir();
}
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
FilePath slaDirectoryFilePath = new FilePath(slaDirectory);
FilePath tmpZipFile = new FilePath(slaDirectoryFilePath, "runReport.zip");
tmpZipFile.copyFrom(bais);
bais.close();
baos.close();
tmpZipFile.unzip(slaDirectoryFilePath);
FilePath slaFile = new FilePath(slaDirectoryFilePath, "RunReport.xml");
slaFile.getBaseName();
slaFile.renameTo(new FilePath(slaDirectoryFilePath, scenarioName + ".xml"));
slaFile = new FilePath(slaDirectoryFilePath, scenarioName + ".xml");
return slaFile;
}
return null;
}
private boolean archiveFolder(FilePath reportFolder, String testStatus, FilePath archivedFile,
TaskListener listener) throws IOException, InterruptedException {
String archiveTestResultMode = _resultsPublisherModel.getArchiveTestResultsMode();
boolean archiveTestResult;
archiveTestResult = isArchiveTestResult(testStatus, archiveTestResultMode);
if (archiveTestResult) {
if (reportFolder.exists()) {
listener.getLogger().println("Zipping report folder: " + reportFolder);
ByteArrayOutputStream outstr = new ByteArrayOutputStream();
reportFolder.zip(outstr);
/*
* I did't use copyRecursiveTo or copyFrom due to bug in
* jekins:https://issues.jenkins-ci.org/browse /JENKINS-9189 //(which is
* cleaimed to have been fixed, but not. So I zip the folder to stream and copy
* it to the master.
*/
ByteArrayInputStream instr = new ByteArrayInputStream(outstr.toByteArray());
archivedFile.copyFrom(instr);
outstr.close();
instr.close();
return true;
} else {
listener.getLogger().println("No report folder was found in: " + reportFolder);
}
}
return false;
}
private boolean isArchiveTestResult(String testStatus, String archiveTestResultMode) {
if (archiveTestResultMode.equals(ResultsPublisherModel.alwaysArchiveResults.getValue())
|| archiveTestResultMode.equals(ResultsPublisherModel.CreateHtmlReportResults.getValue())) {
return true;
} else if (archiveTestResultMode.equals(ResultsPublisherModel.ArchiveFailedTestsResults.getValue())) {
if ("fail".equals(testStatus)) {
return true;
} else if (archiveTestResultMode.equals(ResultsPublisherModel.dontArchiveResults.getValue())) {
return false;
}
}
return false;
}
/**
* Copy Summary Html reports created by LoadRunner
*
* @param reportFolder
* @param testFolderPath
* @param artifactsDir
* @param reportNames
* @param testResult
* @throws IOException
* @throws InterruptedException
*/
@SuppressWarnings("squid:S134")
private void createHtmlReport(FilePath reportFolder, String testFolderPath, File artifactsDir,
List<String> reportNames, TestResult testResult) throws IOException, InterruptedException {
String archiveTestResultMode = _resultsPublisherModel.getArchiveTestResultsMode();
boolean createReport = archiveTestResultMode.equals(ResultsPublisherModel.CreateHtmlReportResults.getValue());
if (createReport) {
File testFolderPathFile = new File(testFolderPath);
FilePath srcDirectoryFilePath = new FilePath(reportFolder, HTML_REPORT_FOLDER);
if (srcDirectoryFilePath.exists()) {
FilePath srcFilePath = new FilePath(srcDirectoryFilePath, IE_REPORT_FOLDER);
if (srcFilePath.exists()) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
srcFilePath.zip(baos);
File reportDirectory = new File(artifactsDir.getParent(), PERFORMANCE_REPORT_FOLDER);
if (!reportDirectory.exists()) {
reportDirectory.mkdir();
}
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
FilePath reportDirectoryFilePath = new FilePath(reportDirectory);
FilePath tmpZipFile = new FilePath(reportDirectoryFilePath, "tmp.zip");
tmpZipFile.copyFrom(bais);
bais.close();
baos.close();
tmpZipFile.unzip(reportDirectoryFilePath);
String newFolderName = org.apache.commons.io.FilenameUtils.getName(testFolderPathFile.getPath());
FileUtils.moveDirectory(new File(reportDirectory, IE_REPORT_FOLDER),
new File(reportDirectory, newFolderName));
tmpZipFile.delete();
outputReportFiles(reportNames, reportDirectory, testResult, "Performance Report",
HTML_REPORT_FOLDER);
}
}
}
}
/**
* Create a new directory RichReport/scenario_name on master and copy the .pdf
* files from slave LRA folder
*/
private void createRichReports(FilePath reportFolder, String testFolderPath, File artifactsDir,
List<String> reportNames, TestResult testResult, TaskListener listener) {
try {
File testFolderPathFile = new File(testFolderPath);
FilePath htmlReportPath = new FilePath(reportFolder, LRA_FOLDER);
if (htmlReportPath.exists()) {
File reportDirectory = new File(artifactsDir.getParent(), RICH_REPORT_FOLDER);
if (!reportDirectory.exists()) {
reportDirectory.mkdir();
}
String newFolderName = org.apache.commons.io.FilenameUtils.getName(testFolderPathFile.getPath());
File testDirectory = new File(reportDirectory, newFolderName);
if (!testDirectory.exists()) {
testDirectory.mkdir();
}
FilePath dstReportPath = new FilePath(testDirectory);
FileFilter reportFileFilter = new WildcardFileFilter("*.pdf");
List<FilePath> reportFiles = htmlReportPath.list(reportFileFilter);
List<String> richReportNames = new ArrayList<String>();
for (FilePath fileToCopy : reportFiles) {
FilePath dstFilePath = new FilePath(dstReportPath, fileToCopy.getName());
fileToCopy.copyTo(dstFilePath);
richReportNames.add(dstFilePath.getName());
}
outputReportFiles(reportNames, reportDirectory, testResult, "Rich Reports", INDEX_HTML_NAME);
createRichReportHtml(testDirectory, richReportNames);
}
} catch (IOException | InterruptedException ex) {
listener.getLogger().println("Exception caught while creating rich reports: " + ex);
}
}
private void createErrorHtml(File htmlDirectory, String error) throws IOException {
String htmlFileContents = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<HTML><HEAD>"
+ "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">"
+ "<TITLE>Rich Report</TITLE>" + "</HEAD>" + "<BODY>" + error + "</BODY>";
writeToFile(htmlDirectory, htmlFileContents);
}
private void createRichReportHtml(File reportDirectory, List<String> richReportNames) throws IOException {
String htmlFileContents = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<HTML><HEAD>"
+ "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">"
+ "<TITLE>Rich Report</TITLE>" + "</HEAD>" + "<BODY>";
if (richReportNames.size() == 0) {
htmlFileContents += NO_RICH_REPORTS_ERROR;
} else {
for (String richReportName : richReportNames) {
htmlFileContents += "<iframe src=\"./" + richReportName + "\" width=\"100%%\" height=\"800px\" "
+ "frameBorder=\"0\"></iframe>";
}
}
htmlFileContents += "</BODY>";
File richReportsHtml = new File(reportDirectory, HTML_REPORT_FOLDER + ".html");
writeToFile(richReportsHtml, htmlFileContents);
}
private void writeToFile(File file, String contents) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(contents);