forked from hpsa/hpe-application-automation-tools-plugin
-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathLauncher.cs
1016 lines (892 loc) · 45.5 KB
/
Launcher.cs
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-2024 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.
* ___________________________________________________________________
*/
using HpToolsLauncher.Properties;
using HpToolsLauncher.RTS;
using HpToolsLauncher.TestRunners;
using HpToolsLauncher.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace HpToolsLauncher
{
public enum CiName
{
Hudson,
Jenkins,
TFS,
CCNET
}
public class Launcher
{
private IAssetRunner _runner;
private IXmlBuilder _xmlBuilder;
private bool _ciRun = false;
private readonly JavaProperties _ciParams = new JavaProperties();
private TestStorageType _runType;
private static ExitCodeEnum _exitCode = ExitCodeEnum.Passed;
private const string _dateFormat = "dd'/'MM'/'yyyy HH':'mm':'ss";
private string _encoding;
private const string PASSWORD = "Password";
private const string RERUN_ALL_TESTS = "Rerun the entire set of tests";
private const string RERUN_SPECIFIC_TESTS = "Rerun specific tests in the build";
private const string RERUN_FAILED_TESTS = "Rerun only failed tests";
private const string ONE = "1";
private const string CLEANUP_TEST = "CleanupTest";
public const string ClassName = "HPToolsFileSystemRunner";
public static string DateFormat
{
get { return _dateFormat; }
}
/// <summary>
/// if running an alm job theses strings are mandatory:
/// </summary>
private readonly string[] requiredParamsForQcRun = { "almServerUrl",
"almUsername",
"almPassword",
"almDomain",
"almProject",
"almRunMode",
"almTimeout",
"almRunHost"};
private readonly char[] _colon_semicolon = ",;".ToCharArray();
/// <summary>
/// a place to save the unique timestamp which shows up in properties/results/abort file names
/// this timestamp per job run.
/// </summary>
public static string UniqueTimeStamp { get; set; }
/// <summary>
/// saves the exit code in case we want to run all tests but fail at the end since a file wasn't found
/// </summary>
public static ExitCodeEnum ExitCode
{
get { return _exitCode; }
set { _exitCode = value; }
}
public enum ExitCodeEnum
{
Passed = 0,
Failed = -1,
Unstable = -2,
Aborted = -3
}
/// <summary>
/// constructor
/// </summary>
/// <param name="paramFileName"></param>
/// <param name="runType"></param>
public Launcher(string paramFileName, TestStorageType runType, string encoding = "UTF-8")
{
_runType = runType;
if (paramFileName != null)
_ciParams.Load(paramFileName);
_encoding = encoding;
}
/// <summary>
/// writes to console using the ConsolWriter class
/// </summary>
/// <param name="message"></param>
private static void WriteToConsole(string message)
{
ConsoleWriter.WriteLine(message);
}
public void SafelyCancel()
{
if (_runner != null)
{
_runner.SafelyCancel();
}
}
/// <summary>
/// analyzes and runs the tests given in the param file.
/// </summary>
public void Run()
{
_ciRun = true;
if (_runType == TestStorageType.Unknown)
Enum.TryParse(_ciParams["runType"], true, out _runType);
if (_runType == TestStorageType.Unknown)
{
WriteToConsole(Resources.LauncherNoRuntype);
return;
}
if (!_ciParams.ContainsKey("resultsFilename"))
{
WriteToConsole(Resources.LauncherNoResFilenameFound);
return;
}
string resultsFilename = _ciParams["resultsFilename"];
UniqueTimeStamp = _ciParams.GetOrDefault("uniqueTimeStamp", resultsFilename.ToLower().Replace("results", string.Empty).Replace(".xml", string.Empty));
//run the entire set of test once
//create the runner according to type
_runner = CreateRunner(true);
//runner instantiation failed (no tests to run or other problem)
if (_runner == null)
{
ConsoleWriter.WriteLine("empty runner;");
Environment.Exit((int)ExitCodeEnum.Failed);
return;
}
TestSuiteRunResults results = _runner.Run();
string onCheckFailedTests = _ciParams.GetOrDefault("onCheckFailedTest");
bool rerunTestsOnFailure = !string.IsNullOrEmpty(onCheckFailedTests) && Convert.ToBoolean(onCheckFailedTests.ToLower());
if (_runType != TestStorageType.MBT)
{
RunSummary(resultsFilename, results);
}
if (_runType == TestStorageType.FileSystem)
{
//the "On failure" option is selected and the run build contains failed tests
// we need to check if there were any failed tests
bool thereAreFailedTests = _exitCode == ExitCodeEnum.Failed || results.NumFailures > 0;
if (rerunTestsOnFailure && thereAreFailedTests)
{
ConsoleWriter.WriteLine("There are failed tests.");
string fsTestType = _ciParams.GetOrDefault("testType");
//rerun the selected tests (either the entire set, just the selected tests or only the failed tests)
List<TestRunResults> runResults = results.TestRuns;
List<TestInfo> reruntests = new List<TestInfo>();
int index = 0;
foreach (var item in runResults)
{
if ((fsTestType == RERUN_ALL_TESTS) ||
(fsTestType == RERUN_FAILED_TESTS && (item.TestState == TestState.Failed || item.TestState == TestState.Error)))
{
index++;
reruntests.Add(new TestInfo(string.Format("FailedTest{0}", index), item.TestInfo));
}
}
if (fsTestType == RERUN_SPECIFIC_TESTS)
{
var specificTests = GetValidTests("FailedTest", Resources.LauncherNoFailedTestsFound, Resources.LauncherNoValidFailedTests, fsTestType);
reruntests = FileSystemTestsRunner.GetListOfTestInfo(specificTests);
}
//create the runner according to type
_runner = CreateRunner(false, reruntests, (RunnerBase)_runner);
//runner instantiation failed (no tests to run or other problem)
if (_runner == null)
{
Environment.Exit((int)ExitCodeEnum.Failed);
return;
}
TestSuiteRunResults rerunResults = _runner.Run();
RunSummary(resultsFilename, results, rerunResults);
}
}
Environment.Exit((int)_exitCode);
}
/// <summary>
/// creates the correct runner according to the given type
/// </summary>
/// <param name="isFirstRun"></param>
private IAssetRunner CreateRunner(bool isFirstRun, List<TestInfo> reruntests = null, RunnerBase initialRunnerBase = null)
{
IAssetRunner runner = null;
switch (_runType)
{
case TestStorageType.AlmLabManagement:
case TestStorageType.Alm:
{
//check that all required parameters exist
foreach (string param1 in requiredParamsForQcRun)
{
if (!_ciParams.ContainsKey(param1))
{
ConsoleWriter.WriteLine(string.Format(Resources.LauncherParamRequired, param1));
return null;
}
}
//parse params that need parsing
double dblQcTimeout;
if (!double.TryParse(_ciParams["almTimeout"], out dblQcTimeout))
{
ConsoleWriter.WriteLine(Resources.LauncherTimeoutNotNumeric);
dblQcTimeout = int.MaxValue;
}
ConsoleWriter.WriteLine(string.Format(Resources.LuancherDisplayTimout, dblQcTimeout));
QcRunMode enmQcRunMode;
if (!Enum.TryParse(_ciParams["almRunMode"], true, out enmQcRunMode))
{
ConsoleWriter.WriteLine(Resources.LauncherIncorrectRunmode);
enmQcRunMode = QcRunMode.RUN_LOCAL;
}
ConsoleWriter.WriteLine(string.Format(Resources.LauncherDisplayRunmode, enmQcRunMode.ToString()));
//go over test sets in the parameters, and collect them
List<string> sets = GetParamsWithPrefix("TestSet", true);
if (sets.Count == 0)
{
ConsoleWriter.WriteLine(Resources.LauncherNoTests);
return null;
}
List<TestParameter> @params = GetValidParams();
//check if filterTests flag is selected; if yes apply filters on the list
bool isFilterSelected;
string filter = _ciParams.GetOrDefault("FilterTests");
isFilterSelected = !string.IsNullOrEmpty(filter) && Convert.ToBoolean(filter.ToLower());
string filterByName = _ciParams.GetOrDefault("FilterByName");
string statuses = _ciParams.GetOrDefault("FilterByStatus");
List<string> filterByStatuses = new List<string>();
if (statuses != string.Empty)
{
if (statuses.Contains(","))
{
filterByStatuses = statuses.Split(',').ToList();
}
else
{
filterByStatuses.Add(statuses);
}
}
bool isSSOEnabled = _ciParams.ContainsKey("SSOEnabled") ? Convert.ToBoolean(_ciParams["SSOEnabled"]) : false;
string clientID = _ciParams.GetOrDefault("almClientID");
string apiKey = _ciParams.ContainsKey("almApiKeySecret") ? Encrypter.Decrypt(_ciParams["almApiKeySecret"]) : string.Empty;
string almRunHost = _ciParams.GetOrDefault("almRunHost");
//create an Alm runner
runner = new AlmTestSetsRunner(_ciParams["almServerUrl"],
_ciParams["almUsername"],
Encrypter.Decrypt(_ciParams["almPassword"]),
_ciParams["almDomain"],
_ciParams["almProject"],
dblQcTimeout,
enmQcRunMode,
almRunHost,
sets,
@params,
isFilterSelected,
filterByName,
filterByStatuses,
isFirstRun,
_runType,
isSSOEnabled,
clientID, apiKey);
break;
}
case TestStorageType.FileSystem:
{
bool displayController = _ciParams.GetOrDefault("displayController") == ONE;
string analysisTemplate = _ciParams.GetOrDefault("analysisTemplate");
bool printInputParams = _ciParams.GetOrDefault("printTestParams", ONE) == ONE;
IEnumerable<string> jenkinsEnvVarsWithCommas = GetParamsWithPrefix("JenkinsEnv");
Dictionary<string, string> jenkinsEnvVars = new Dictionary<string, string>();
foreach (string var in jenkinsEnvVarsWithCommas)
{
string[] nameVal = var.Split(_colon_semicolon);
jenkinsEnvVars.Add(nameVal[0], nameVal[1]);
}
//add build tests and cleanup tests in correct order
List<TestData> validTests = new List<TestData>();
List<TestInfo> cleanupAndRerunTests = new List<TestInfo>();
if (isFirstRun)
{
ConsoleWriter.WriteLine("Run build tests");
List<TestData> validBuildTests = GetValidTests("Test", Resources.LauncherNoTestsFound, Resources.LauncherNoValidTests, string.Empty);
if (validBuildTests.Count == 0)
{
Environment.Exit((int)ExitCodeEnum.Failed);
}
//run only the build tests
foreach (var item in validBuildTests)
{
validTests.Add(item);
}
}
else
{ //add also cleanup tests
string fsTestType = _ciParams.GetOrDefault("testType");
List<TestData> validCleanupTests = GetValidTests(CLEANUP_TEST, Resources.LauncherNoCleanupTestsFound, Resources.LauncherNoValidCleanupTests, fsTestType);
List<string> reruns = GetParamsWithPrefix("Reruns");
List<int> numberOfReruns = new List<int>();
foreach (var item in reruns)
{
numberOfReruns.Add(int.Parse(item));
}
bool noRerunsSet = CheckListOfRerunValues(numberOfReruns);
if (noRerunsSet)
{
ConsoleWriter.WriteLine("In order to rerun the tests the number of reruns should be greater than zero.");
}
else
{
switch (fsTestType)
{
case RERUN_ALL_TESTS: ConsoleWriter.WriteLine("The entire test set will run again."); break;
case RERUN_SPECIFIC_TESTS: ConsoleWriter.WriteLine("Only the selected tests will run again."); break;
case RERUN_FAILED_TESTS: ConsoleWriter.WriteLine("Only the failed tests will run again."); break;
}
for (int i = 0; i < numberOfReruns.Count; i++)
{
var currentRerun = numberOfReruns[i];
if (fsTestType == RERUN_ALL_TESTS || fsTestType == RERUN_FAILED_TESTS)
{
while (currentRerun > 0)
{
if (validCleanupTests.Count > 0)
{
var cleanupTest = FileSystemTestsRunner.GetFirstTestInfo(validCleanupTests[i], jenkinsEnvVars);
if (cleanupTest != null)
cleanupAndRerunTests.Add(cleanupTest);
}
if (reruntests.Count > 0)
{
cleanupAndRerunTests.AddRange(reruntests);
}
else
{
Console.WriteLine(fsTestType == RERUN_ALL_TESTS ? "There are no tests to rerun." : "There are no failed tests to rerun.");
break;
}
currentRerun--;
}
}
else if (fsTestType == RERUN_SPECIFIC_TESTS)
{
while (currentRerun > 0)
{
if (validCleanupTests.Count > 0)
{
var cleanupTest = FileSystemTestsRunner.GetFirstTestInfo(validCleanupTests[i], jenkinsEnvVars);
if (cleanupTest != null)
cleanupAndRerunTests.Add(cleanupTest);
}
if (reruntests != null && reruntests.Count > i)
cleanupAndRerunTests.Add(reruntests[i]);
else
{
Console.WriteLine(string.Format("There is no specific test with index = {0}", i + 1));
break;
}
currentRerun--;
}
}
}
}
}
//parse the timeout into a TimeSpan
TimeSpan timeout = TimeSpan.MaxValue;
if (_ciParams.ContainsKey("fsTimeout"))
{
string strTimeoutInSeconds = _ciParams["fsTimeout"];
if (strTimeoutInSeconds.Trim() != "-1")
{
int intTimeoutInSeconds;
int.TryParse(strTimeoutInSeconds, out intTimeoutInSeconds);
timeout = TimeSpan.FromSeconds(intTimeoutInSeconds);
}
}
ConsoleWriter.WriteLine("Launcher timeout is " + timeout.ToString(@"dd\:\:hh\:mm\:ss"));
//LR specific values:
//default values are set by JAVA code, in com.hpe.application.automation.tools.model.RunFromFileSystemModel.java
int pollingInterval = 30;
if (_ciParams.ContainsKey("controllerPollingInterval"))
pollingInterval = int.Parse(_ciParams["controllerPollingInterval"]);
ConsoleWriter.WriteLine("Controller Polling Interval: " + pollingInterval + " seconds");
TimeSpan perScenarioTimeOutMinutes = TimeSpan.MaxValue;
if (_ciParams.ContainsKey("PerScenarioTimeOut"))
{
string strTimeoutInMinutes = _ciParams["PerScenarioTimeOut"];
int intTimoutInMinutes;
if (strTimeoutInMinutes.Trim() != "-1" && int.TryParse(strTimeoutInMinutes, out intTimoutInMinutes))
perScenarioTimeOutMinutes = TimeSpan.FromMinutes(intTimoutInMinutes);
}
ConsoleWriter.WriteLine("PerScenarioTimeout: " + perScenarioTimeOutMinutes.ToString(@"dd\:\:hh\:mm\:ss") + " minutes");
char[] delimiter = { '\n' };
List<string> ignoreErrorStrings = new List<string>();
if (_ciParams.ContainsKey("ignoreErrorStrings"))
{
ignoreErrorStrings.AddRange(Array.ConvertAll(_ciParams["ignoreErrorStrings"].Split(delimiter, StringSplitOptions.RemoveEmptyEntries), ignoreError => ignoreError.Trim()));
}
//If a file path was provided and it doesn't exist stop the analysis launcher
if (!string.IsNullOrWhiteSpace(analysisTemplate) && !Helper.FileExists(analysisTemplate))
{
return null;
}
//--MC connection info
McConnectionInfo mcConnectionInfo = null;
try
{
mcConnectionInfo = new McConnectionInfo(_ciParams);
}
catch(NoMcConnectionException)
{
// no action, the Test will use the default UFT One settings
}
catch (Exception ex)
{
ConsoleWriter.WriteErrLine(ex.Message);
Environment.Exit((int)ExitCodeEnum.Failed);
}
// other mobile info
string mobileinfo = string.Empty;
if (_ciParams.ContainsKey("mobileinfo"))
{
mobileinfo = _ciParams["mobileinfo"];
}
CloudBrowser cloudBrowser = null;
string strCloudBrowser = _ciParams.GetOrDefault("cloudBrowser").Trim();
if (!strCloudBrowser.IsNullOrEmpty())
{
CloudBrowser.TryParse(strCloudBrowser, out cloudBrowser);
}
var parallelRunnerEnvironments = new Dictionary<string, List<string>>();
// retrieve the parallel runner environment for each test
if (_ciParams.ContainsKey("parallelRunnerMode"))
{
foreach (var test in validTests)
{
string envKey = "Parallel" + test.Id + "Env";
List<string> testEnvironments = GetParamsWithPrefix(envKey);
// add the environments for all the valid tests
parallelRunnerEnvironments.Add(test.Id, testEnvironments);
}
}
// users can provide a custom report path
string reportPath = null;
if (_ciParams.ContainsKey("fsReportPath"))
{
if (Directory.Exists(_ciParams["fsReportPath"]))
{ //path is not parameterized
reportPath = _ciParams["fsReportPath"];
}
else
{ //path is parameterized
string fsReportPath = _ciParams["fsReportPath"];
//get parameter name
fsReportPath = fsReportPath.Trim(new char[] { ' ', '$', '{', '}' });
//get parameter value
fsReportPath = fsReportPath.Trim(new char[] { ' ', '\t' });
try
{
reportPath = jenkinsEnvVars[fsReportPath];
}
catch (KeyNotFoundException)
{
Console.WriteLine("============================================================================");
Console.WriteLine("The provided results folder path {0} does not exist.", fsReportPath);
Console.WriteLine("============================================================================");
Environment.Exit((int)ExitCodeEnum.Failed);
}
}
}
RunAsUser uftRunAsUser = null;
string username = _ciParams.GetOrDefault("uftRunAsUserName");
if (!string.IsNullOrEmpty(username))
{
string encryptedAndEncodedPwd = _ciParams.GetOrDefault("uftRunAsUserEncodedPassword");
string encryptedPwd = _ciParams.GetOrDefault("uftRunAsUserPassword");
if (!string.IsNullOrEmpty(encryptedAndEncodedPwd))
{
string encodedPwd = Encrypter.Decrypt(encryptedAndEncodedPwd);
uftRunAsUser = new RunAsUser(username, encodedPwd);
}
else if (!string.IsNullOrEmpty(encryptedPwd))
{
string plainTextPwd = Encrypter.Decrypt(encryptedPwd);
uftRunAsUser = new RunAsUser(username, plainTextPwd.ToSecureString());
}
}
SummaryDataLogger summaryDataLogger = GetSummaryDataLogger();
List<ScriptRTSModel> scriptRTSSet = GetScriptRtsSet();
string resultsFilename = _ciParams["resultsFilename"];
string uftRunMode = _ciParams.GetOrDefault("fsUftRunMode", "Fast");
if (validTests.Count > 0)
{
runner = new FileSystemTestsRunner(validTests, GetValidParams(), printInputParams, timeout, uftRunMode, pollingInterval, perScenarioTimeOutMinutes, ignoreErrorStrings, jenkinsEnvVars, new DigitalLab(mcConnectionInfo, mobileinfo, cloudBrowser), parallelRunnerEnvironments, displayController, analysisTemplate, summaryDataLogger, scriptRTSSet, reportPath, resultsFilename, _encoding, uftRunAsUser);
}
else if (cleanupAndRerunTests.Count > 0)
{
runner = new FileSystemTestsRunner(cleanupAndRerunTests, printInputParams, timeout, uftRunMode, pollingInterval, perScenarioTimeOutMinutes, ignoreErrorStrings, jenkinsEnvVars, new DigitalLab(mcConnectionInfo, mobileinfo, cloudBrowser), parallelRunnerEnvironments, displayController, analysisTemplate, summaryDataLogger, scriptRTSSet, reportPath, resultsFilename, _encoding, uftRunAsUser);
}
else
{
ConsoleWriter.WriteLine(Resources.FsRunnerNoValidTests);
Environment.Exit((int)ExitCodeEnum.Failed);
}
break;
}
case TestStorageType.MBT:
string parentFolder = _ciParams["parentFolder"];
string repoFolder = _ciParams["repoFolder"];
int counter = 1;
string testProp = "test" + counter;
List<MBTTest> tests = new List<MBTTest>();
while (_ciParams.ContainsKey(testProp))
{
MBTTest test = new MBTTest();
tests.Add(test);
test.Name = _ciParams[testProp];
test.Script = _ciParams.GetOrDefault("script" + counter);
test.UnitIds = _ciParams.GetOrDefault("unitIds" + counter);
test.UnderlyingTests = new List<string>(_ciParams.GetOrDefault("underlyingTests" + counter).Split(';'));
test.PackageName = _ciParams.GetOrDefault("package" + counter);
test.DatableParams = _ciParams.GetOrDefault("datableParams" + counter);
test.PackageName = _ciParams.GetOrDefault("package" + counter, "");
test.DatableParams = _ciParams.GetOrDefault("datableParams" + counter, "");
testProp = "test" + (++counter);
}
runner = new MBTRunner(parentFolder, repoFolder, tests);
break;
default:
runner = null;
break;
}
if (runner != null && !isFirstRun)
{
RunnerBase rbase = (RunnerBase)runner;
rbase.XmlBuilder = initialRunnerBase.XmlBuilder; // reuse the populated initialXmlBuilder because it contains testcases already created, in order to speed up the report building
rbase.IndexOfRptDirsByTestPath = initialRunnerBase.IndexOfRptDirsByTestPath;
}
return runner;
}
private List<string> GetParamsWithPrefix(string prefix, bool skipEmptyEntries = false)
{
int idx = 1;
List<string> parameters = new List<string>();
while (_ciParams.ContainsKey(prefix + idx))
{
string set = _ciParams[prefix + idx];
if (set.StartsWith("Root\\"))
set = set.Substring(5);
set = set.TrimEnd(" \\".ToCharArray());
if (!(skipEmptyEntries && string.IsNullOrWhiteSpace(set)))
{
parameters.Add(set);
}
++idx;
}
return parameters;
}
private Dictionary<string, string> GetKeyValuesWithPrefix(string prefix)
{
int idx = 1;
Dictionary<string, string> dict = new Dictionary<string, string>();
while (_ciParams.ContainsKey(prefix + idx))
{
string set = _ciParams[prefix + idx];
if (set.StartsWith("Root\\"))
set = set.Substring(5);
set = set.TrimEnd(" \\".ToCharArray());
string key = prefix + idx;
dict[key] = set;
++idx;
}
return dict;
}
/// <summary>
/// used by the run fuction to run the tests
/// </summary>
/// <param name="resultsFile"></param>
///
private void RunSummary(string resultsFile, TestSuiteRunResults results, TestSuiteRunResults rerunResults = null)
{
try
{
if (results == null)
{
Environment.Exit((int)ExitCodeEnum.Failed);
return;
}
if (_runType != TestStorageType.FileSystem) // for FileSystem the report is already generated inside FileSystemTestsRunner.Run()
{
if (_ciRun)
{
_xmlBuilder = new JunitXmlBuilder();
_xmlBuilder.XmlName = resultsFile;
}
_xmlBuilder.CreateXmlFromRunResults(results);
}
var allTestRuns = new List<TestRunResults>(results.TestRuns);
if (allTestRuns.Count == 0)
{
ConsoleWriter.WriteLine(Resources.GeneralDoubleSeperator);
ConsoleWriter.WriteLine("No tests were run");
_exitCode = ExitCodeEnum.Failed;
Environment.Exit((int)_exitCode);
}
bool is4Rerun = rerunResults != null && rerunResults.TestRuns.Count > 0;
int failures, successes, errors, warnings;
if (is4Rerun)
{
UpdateExitCode(rerunResults, out successes, out failures, out errors, out warnings);
failures += results.NumFailures;
successes += allTestRuns.Count(t => t.TestState == TestState.Passed);
errors += results.NumErrors;
warnings += results.NumWarnings;
allTestRuns.AddRange(rerunResults.TestRuns);
}
else
{
UpdateExitCode(results, out successes, out failures, out errors, out warnings);
}
//this is the total run summary
ConsoleWriter.ActiveTestRun = null;
string runStatus = string.Empty;
switch (_exitCode)
{
case ExitCodeEnum.Passed:
runStatus = "Job succeeded";
break;
case ExitCodeEnum.Unstable:
{
if (failures > 0 && warnings > 0)
{
runStatus = "Job unstable (Passed with failed tests and generated warnings)";
}
else if (failures > 0)
{
runStatus = "Job unstable (Passed with failed tests)";
}
else if (warnings > 0)
{
runStatus = "Job unstable (Generated warnings)";
}
break;
}
case ExitCodeEnum.Aborted:
runStatus = "Job failed due to being Aborted";
break;
case ExitCodeEnum.Failed:
runStatus = "Job failed";
break;
default:
runStatus = "Error: Job status is Undefined";
break;
}
ConsoleWriter.WriteLine(Resources.LauncherDoubleSeparator);
ConsoleWriter.WriteLine(string.Format(Resources.LauncherDisplayStatistics, runStatus, allTestRuns.Count, successes, failures, errors, warnings));
int testIndex = 1;
if (!_runner.RunWasCancelled)
{
allTestRuns.ForEach(tr => { ConsoleWriter.WriteLine(((tr.HasWarnings) ? "Warning".PadLeft(7) : tr.TestState.ToString().PadRight(7)) + ": " + tr.TestPath + "[" + testIndex + "]"); testIndex++; });
ConsoleWriter.WriteLine(Resources.LauncherDoubleSeparator);
if (ConsoleWriter.ErrorSummaryLines != null && ConsoleWriter.ErrorSummaryLines.Count > 0)
{
ConsoleWriter.WriteLine("Job Errors summary:");
ConsoleWriter.ErrorSummaryLines.ForEach(line => ConsoleWriter.WriteLine(line));
}
}
}
finally
{
try
{
_runner.Dispose();
}
catch (Exception ex)
{
ConsoleWriter.WriteLine(string.Format(Resources.LauncherRunnerDisposeError, ex.Message));
}
}
}
private void UpdateExitCode(TestSuiteRunResults results, out int successes, out int failures, out int errors, out int warnings)
{
failures = results.NumFailures;
successes = results.TestRuns.Count(t => t.TestState == TestState.Passed);
errors = results.NumErrors;
warnings = results.NumWarnings;
if (_exitCode != ExitCodeEnum.Aborted)
{
if (errors > 0)
{
_exitCode = ExitCodeEnum.Failed;
}
else if (failures > 0 && successes > 0)
{
_exitCode = ExitCodeEnum.Unstable;
}
else if (failures > 0)
{
_exitCode = ExitCodeEnum.Failed;
}
else if (warnings > 0)
{
_exitCode = ExitCodeEnum.Unstable;
}
else if (successes > 0)
{
_exitCode = ExitCodeEnum.Passed;
}
foreach (var testRun in results.TestRuns)
{
if (testRun.FatalErrors > 0 && !string.IsNullOrWhiteSpace(testRun.TestPath))
{
_exitCode = ExitCodeEnum.Failed;
break;
}
}
}
}
private SummaryDataLogger GetSummaryDataLogger()
{
SummaryDataLogger summaryDataLogger;
if (_ciParams.ContainsKey("SummaryDataLog"))
{
string[] summaryDataLogFlags = _ciParams["SummaryDataLog"].Split(";".ToCharArray());
if (summaryDataLogFlags.Length == 4)
{
//If the polling interval is not a valid number, set it to default (10 seconds)
int summaryDataLoggerPollingInterval;
if (!int.TryParse(summaryDataLogFlags[3], out summaryDataLoggerPollingInterval))
{
summaryDataLoggerPollingInterval = 10;
}
summaryDataLogger = new SummaryDataLogger(
summaryDataLogFlags[0] == ONE,
summaryDataLogFlags[1] == ONE,
summaryDataLogFlags[2] == ONE,
summaryDataLoggerPollingInterval
);
}
else
{
summaryDataLogger = new SummaryDataLogger();
}
}
else
{
summaryDataLogger = new SummaryDataLogger();
}
return summaryDataLogger;
}
private List<ScriptRTSModel> GetScriptRtsSet()
{
List<ScriptRTSModel> scriptRtsSet = new List<ScriptRTSModel>();
IEnumerable<string> scriptNames = GetParamsWithPrefix("ScriptRTS");
foreach (string scriptName in scriptNames)
{
ScriptRTSModel scriptRts = new ScriptRTSModel(scriptName);
IEnumerable<string> additionalAttributes = GetParamsWithPrefix("AdditionalAttribute");
foreach (string additionalAttribute in additionalAttributes)
{
//Each additional attribute contains: script name, aditional attribute name, value and description
string[] additionalAttributeArguments = additionalAttribute.Split(";".ToCharArray());
if (additionalAttributeArguments.Length == 4 && additionalAttributeArguments[0].Equals(scriptName))
{
scriptRts.AddAdditionalAttribute(new AdditionalAttributeModel(
additionalAttributeArguments[1],
additionalAttributeArguments[2],
additionalAttributeArguments[3])
);
}
}
scriptRtsSet.Add(scriptRts);
}
return scriptRtsSet;
}
/// <summary>
/// Retrieve the list of valid test to run
/// </summary>
/// <param name="propPrefix"></param>
/// <param name="errorNoTestsFound"></param>
/// <param name="errorNoValidTests"></param>
/// <returns>a list of tests</returns>
private List<TestData> GetValidTests(string propPrefix, string errorNoTestsFound, string errorNoValidTests, string fsTestType)
{
if (fsTestType != RERUN_FAILED_TESTS || propPrefix == CLEANUP_TEST)
{
List<TestData> tests = new List<TestData>();
Dictionary<string, string> testsKeyValue = GetKeyValuesWithPrefix(propPrefix);
if (propPrefix == CLEANUP_TEST && testsKeyValue.Count == 0)
{
return tests;
}
foreach (var item in testsKeyValue)
{
tests.Add(new TestData(item.Value, item.Key));
}
if (tests.Count == 0)
{
WriteToConsole(errorNoTestsFound);
}
else
{
List<TestData> validTests = Helper.ValidateFiles(tests);
if (validTests.Count > 0) return validTests;
//no valid tests found
ConsoleWriter.WriteLine(errorNoValidTests);
}
}
return new List<TestData>();
}
/// <summary>
/// Returns all the valid parameters from the props file (CI args).
/// </summary>
/// <returns></returns>
private List<TestParameter> GetValidParams()
{
List<TestParameter> parameters = new List<TestParameter>();
int initialNumOfTests = _ciParams.ContainsKey("numOfTests") ? int.Parse(_ciParams["numOfTests"]) : 0;
for (int i = 1; i <= initialNumOfTests; ++i)
{
int j = 1;
while (_ciParams.ContainsKey(string.Format("Param{0}_Name_{1}", i, j)))
{
string name = _ciParams[string.Format("Param{0}_Name_{1}", i, j)].Trim();
if (string.IsNullOrWhiteSpace(name))
{
ConsoleWriter.WriteLine(string.Format("Found no name associated with parameter with index {0} for test {1}.", j, i));
continue;
}
string val = _ciParams[string.Format("Param{0}_Value_{1}", i, j)].Trim();
string type = _ciParams[string.Format("Param{0}_Type_{1}", i, j)];
if (string.IsNullOrWhiteSpace(type))
{
ConsoleWriter.WriteLine(string.Format("Found no type associated with parameter {0}.", name));
continue;
}
else if (type == PASSWORD && !string.IsNullOrWhiteSpace(val))
{
val = Encrypter.Decrypt(val);
}
parameters.Add(new TestParameter(i, name, val, type.ToLower()));
++j;
}
}
return parameters;
}
/// <summary>
/// Check if at least one test needs to run again
/// </summary>