-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathConsoleRunner.cs
528 lines (418 loc) · 20.2 KB
/
ConsoleRunner.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
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using NUnit.ConsoleRunner.Utilities;
using NUnit.ConsoleRunner.Options;
using NUnit.Engine;
using NUnit.Engine.Extensibility;
using NUnit.Extensibility;
using NUnit.TextDisplay;
using System.Runtime.InteropServices;
using System.Text;
namespace NUnit.ConsoleRunner
{
/// <summary>
/// ConsoleRunner provides the nunit4-console text-based
/// user interface, running the tests and reporting the results.
/// </summary>
public class ConsoleRunner
{
// Some operating systems truncate the return code to 8 bits, which
// only allows us a maximum of 127 in the positive range. We limit
// ourselves so as to stay in that range.
private const int MAXIMUM_RETURN_CODE_ALLOWED = 100; // In case we are running on Unix
private const string EVENT_LISTENER_EXTENSION_PATH = "/NUnit/Engine/TypeExtensions/ITestEventListener";
private const string TEAMCITY_EVENT_LISTENER = "NUnit.Engine.Listeners.TeamCityEventListener";
private const string INDENT4 = " ";
private const string INDENT6 = " ";
private const string INDENT8 = " ";
public static readonly int OK = 0;
public static readonly int INVALID_ARG = -1;
public static readonly int INVALID_ASSEMBLY = -2;
//public static readonly int FIXTURE_NOT_FOUND = -3; //No longer in use
public static readonly int INVALID_TEST_FIXTURE = -4;
//public static readonly int UNLOAD_ERROR = -5; //No longer in use
public static readonly int UNEXPECTED_ERROR = -100;
private readonly ITestEngine _engine;
private readonly ConsoleOptions _options;
private readonly IResultService _resultService;
private readonly ITestFilterService _filterService;
private readonly IExtensionService _extensionService;
private readonly ExtendedTextWriter _outWriter;
private readonly string _workDirectory;
public ConsoleRunner(ITestEngine engine, ConsoleOptions options, ExtendedTextWriter writer)
{
_engine = engine;
_options = options;
_outWriter = writer;
_workDirectory = options.WorkDirectory ?? Directory.GetCurrentDirectory();
if (!Directory.Exists(_workDirectory))
Directory.CreateDirectory(_workDirectory);
_resultService = _engine.Services.GetService<IResultService>();
_filterService = _engine.Services.GetService<ITestFilterService>();
_extensionService = _engine.Services.GetService<IExtensionService>();
// TODO: Exit with error if any of the services are not found
if (_options.TeamCity)
{
bool teamcityInstalled = false;
foreach (var node in _extensionService.GetExtensionNodes(EVENT_LISTENER_EXTENSION_PATH))
if (teamcityInstalled = node.TypeName == TEAMCITY_EVENT_LISTENER)
break;
if (!teamcityInstalled) throw new NUnitEngineException("Option --teamcity specified but the extension is not installed.");
}
// Enable TeamCityEventListener immediately, before the console is redirected
_extensionService.EnableExtension("NUnit.Engine.Listeners.TeamCityEventListener", _options.TeamCity);
}
/// <summary>
/// Executes tests according to the provided command-line options.
/// </summary>
/// <returns></returns>
public int Execute()
{
if (!VerifyEngineSupport(_options))
return INVALID_ARG;
DisplayRuntimeEnvironment(_outWriter);
if (_options.ListExtensions)
DisplayExtensionList();
if (_options.InputFiles.Count == 0)
{
if (!_options.ListExtensions)
using (new ColorConsole(ColorStyle.Error))
Console.Error.WriteLine("Error: no inputs specified");
return ConsoleRunner.OK;
}
DisplayTestFiles();
TestPackage package = MakeTestPackage(_options);
// We display the filters at this point so that any exception message
// thrown by CreateTestFilter will be understandable.
DisplayTestFilters();
TestFilter filter = CreateTestFilter(_options);
if (_options.Explore)
return ExploreTests(package, filter);
else
return RunTests(package, filter);
}
private void DisplayTestFiles()
{
_outWriter.WriteLine(ColorStyle.SectionHeader, "Test Files");
foreach (string file in _options.InputFiles)
_outWriter.WriteLine(ColorStyle.Default, INDENT4 + file);
_outWriter.WriteLine();
}
private int ExploreTests(TestPackage package, TestFilter filter)
{
XmlNode result;
using (var runner = _engine.GetRunner(package))
result = runner.Explore(filter);
if (_options.ExploreOutputSpecifications.Count == 0)
{
_resultService.GetResultWriter("cases", null).WriteResultFile(result, Console.Out);
}
else
{
foreach (OutputSpecification spec in _options.ExploreOutputSpecifications)
{
_resultService.GetResultWriter(spec.Format, spec.Transform).WriteResultFile(result, spec.OutputPath);
_outWriter.WriteLine("Results ({0}) saved as {1}", spec.Format, spec.OutputPath);
}
}
return ConsoleRunner.OK;
}
private int RunTests(TestPackage package, TestFilter filter)
{
var writer = new ColorConsoleWriter(!_options.NoColor);
foreach (var spec in _options.ResultOutputSpecifications)
{
var outputPath = Path.Combine(_workDirectory, spec.OutputPath);
IResultWriter resultWriter;
try
{
resultWriter = GetResultWriter(spec);
}
catch (Exception ex)
{
throw new NUnitEngineException($"Error encountered in resolving output specification: {spec}", ex);
}
try
{
var outputDirectory = Path.GetDirectoryName(outputPath)!;
Directory.CreateDirectory(outputDirectory);
}
catch (Exception ex)
{
writer.WriteLine(ColorStyle.Error, String.Format(
"The directory in --result {0} could not be created",
spec.OutputPath));
writer.WriteLine(ColorStyle.Error, ExceptionHelper.BuildMessage(ex));
return ConsoleRunner.UNEXPECTED_ERROR;
}
try
{
resultWriter.CheckWritability(outputPath);
}
catch (Exception ex)
{
throw new NUnitEngineException(
String.Format(
"The path specified in --result {0} could not be written to",
spec.OutputPath), ex);
}
}
var labels = _options.DisplayTestLabels != null
? _options.DisplayTestLabels.ToUpperInvariant()
: "ON";
XmlNode? result = null;
NUnitEngineUnloadException? unloadException = null;
NUnitEngineException? engineException = null;
try
{
using (new SaveConsoleOutput())
using (ITestRunner runner = _engine.GetRunner(package))
using (var output = CreateOutputWriter())
{
var eventHandler = new TestEventHandler(output, labels);
result = runner.Run(eventHandler, filter);
}
}
catch (NUnitEngineUnloadException ex)
{
unloadException = ex;
}
catch (NUnitEngineException ex)
{
engineException = ex;
}
if (result != null)
{
var reporter = new ResultReporter(result, writer, _options);
reporter.ReportResults();
foreach (var spec in _options.ResultOutputSpecifications)
{
var outputPath = Path.Combine(_workDirectory, spec.OutputPath);
GetResultWriter(spec).WriteResultFile(result, outputPath);
writer.WriteLine("Results ({0}) saved as {1}", spec.Format, spec.OutputPath);
}
if (engineException != null)
{
writer.WriteLine(ColorStyle.Error, Environment.NewLine + ExceptionHelper.BuildMessage(engineException));
return ConsoleRunner.UNEXPECTED_ERROR;
}
if (unloadException != null)
{
writer.WriteLine(ColorStyle.Warning, Environment.NewLine + ExceptionHelper.BuildMessage(unloadException));
}
if (reporter.Summary.UnexpectedError)
return ConsoleRunner.UNEXPECTED_ERROR;
if (reporter.Summary.InvalidAssemblies > 0)
return ConsoleRunner.INVALID_ASSEMBLY;
if (reporter.Summary.InvalidTestFixtures > 0)
return ConsoleRunner.INVALID_TEST_FIXTURE;
var failureCount = reporter.Summary.FailureCount + reporter.Summary.ErrorCount + reporter.Summary.InvalidCount;
return Math.Min(failureCount, MAXIMUM_RETURN_CODE_ALLOWED);
}
// If we got here, it's because we had an exception, but check anyway
if (engineException != null)
{
writer.WriteLine(ColorStyle.Error, ExceptionHelper.BuildMessage(engineException));
writer.WriteLine();
writer.WriteLine(ColorStyle.Error, ExceptionHelper.BuildMessageAndStackTrace(engineException));
}
return ConsoleRunner.UNEXPECTED_ERROR;
}
private void DisplayRuntimeEnvironment(ExtendedTextWriter OutWriter)
{
OutWriter.WriteLine(ColorStyle.SectionHeader, "Runtime Environment");
OutWriter.WriteLabelLine(INDENT4 + "OS Version: ", GetOSVersion());
#if NETFRAMEWORK
OutWriter.WriteLabelLine(INDENT4 + "Runtime: ", ".NET Framework CLR v" + Environment.Version.ToString());
#else
OutWriter.WriteLabelLine(INDENT4 + "Runtime: ", RuntimeInformation.FrameworkDescription);
#endif
OutWriter.WriteLine();
}
private static string GetOSVersion()
{
#if NETFRAMEWORK
OperatingSystem os = Environment.OSVersion;
string osString = os.ToString();
if (os.Platform == PlatformID.Unix)
{
IntPtr buf = Marshal.AllocHGlobal(8192);
if (uname(buf) == 0)
{
var unixVariant = Marshal.PtrToStringAnsi(buf);
if (string.Equals(unixVariant, "Darwin"))
unixVariant = "MacOSX";
osString = string.Format("{0} {1} {2}", unixVariant, os.Version, os.ServicePack);
}
Marshal.FreeHGlobal(buf);
}
return osString;
#else
return RuntimeInformation.OSDescription;
#endif
}
[DllImport("libc")]
static extern int uname(IntPtr buf);
private void DisplayExtensionList()
{
_outWriter.WriteLine(ColorStyle.SectionHeader, "Installed Extensions");
foreach (var ep in _extensionService?.ExtensionPoints ?? new IExtensionPoint[0])
{
_outWriter.WriteLabelLine(INDENT4 + "Extension Point: ", ep.Path);
foreach (var node in ep.Extensions)
{
_outWriter.Write(INDENT6 + "Extension: ");
_outWriter.Write(ColorStyle.Value, $"{node.TypeName}");
_outWriter.WriteLine(node.Enabled ? "" : " (Disabled)");
_outWriter.Write(INDENT8 + "Version: ");
_outWriter.WriteLine(ColorStyle.Value, node.AssemblyVersion.ToString());
_outWriter.Write(INDENT8 + "Path: ");
_outWriter.WriteLine(ColorStyle.Value, node.AssemblyPath);
foreach (var prop in node.PropertyNames)
{
_outWriter.Write(INDENT8 + prop + ":");
foreach (var val in node.GetValues(prop))
_outWriter.Write(ColorStyle.Value, " " + val);
_outWriter.WriteLine();
}
}
}
_outWriter.WriteLine();
}
private void DisplayTestFilters()
{
if (_options.TestList.Count > 0 || _options.WhereClauseSpecified)
{
_outWriter.WriteLine(ColorStyle.SectionHeader, "Test Filters");
if (_options.TestList.Count > 0)
foreach (string testName in _options.TestList)
_outWriter.WriteLabelLine(INDENT4 + "Test: ", testName);
if (_options.WhereClauseSpecified)
_outWriter.WriteLabelLine(INDENT4 + "Where: ", _options.WhereClause.Trim());
_outWriter.WriteLine();
}
}
private ExtendedTextWriter CreateOutputWriter()
{
if (_options.OutFileSpecified)
{
var outStreamWriter = new StreamWriter(Path.Combine(_workDirectory, _options.OutFile));
outStreamWriter.AutoFlush = true;
return new ExtendedTextWrapper(outStreamWriter);
}
return _outWriter;
}
private IResultWriter GetResultWriter(OutputSpecification spec)
{
return _resultService.GetResultWriter(spec.Format, spec.Transform);
}
// This is public static for ease of testing
public static TestPackage MakeTestPackage(ConsoleOptions options)
{
TestPackage package = new TestPackage(options.InputFiles);
if (options.RuntimeFrameworkSpecified)
package.AddSetting(EnginePackageSettings.RequestedRuntimeFramework, options.RuntimeFramework);
if (options.RunAsX86)
package.AddSetting(EnginePackageSettings.RunAsX86, true);
// Console runner always sets DisposeRunners
//if (options.DisposeRunners)
package.AddSetting(EnginePackageSettings.DisposeRunners, true);
if (options.ShadowCopyFiles)
package.AddSetting(EnginePackageSettings.ShadowCopyFiles, true);
if (options.LoadUserProfile)
package.AddSetting(EnginePackageSettings.LoadUserProfile, true);
if (options.SkipNonTestAssemblies)
package.AddSetting(EnginePackageSettings.SkipNonTestAssemblies, true);
if (options.DefaultTestCaseTimeout >= 0)
package.AddSetting(FrameworkPackageSettings.DefaultTimeout, options.DefaultTestCaseTimeout);
if (options.InternalTraceLevelSpecified)
package.AddSetting(FrameworkPackageSettings.InternalTraceLevel, options.InternalTraceLevel);
if (options.ActiveConfigSpecified)
package.AddSetting(EnginePackageSettings.ActiveConfig, options.ActiveConfig);
// Always add work directory, in case current directory is changed
var workDirectory = options.WorkDirectory ?? Directory.GetCurrentDirectory();
package.AddSetting(FrameworkPackageSettings.WorkDirectory, workDirectory);
if (options.StopOnError)
package.AddSetting(FrameworkPackageSettings.StopOnError, true);
if (options.MaxAgentsSpecified)
package.AddSetting(EnginePackageSettings.MaxAgents, options.MaxAgents);
if (options.NumberOfTestWorkersSpecified)
package.AddSetting(FrameworkPackageSettings.NumberOfTestWorkers, options.NumberOfTestWorkers);
if (options.RandomSeedSpecified)
package.AddSetting(FrameworkPackageSettings.RandomSeed, options.RandomSeed);
if (options.DebugTests)
{
package.AddSetting(FrameworkPackageSettings.DebugTests, true);
if (!options.NumberOfTestWorkersSpecified)
package.AddSetting(FrameworkPackageSettings.NumberOfTestWorkers, 0);
}
if (options.PauseBeforeRun)
package.AddSetting(FrameworkPackageSettings.PauseBeforeRun, true);
if (options.PrincipalPolicy != null)
package.AddSetting(EnginePackageSettings.PrincipalPolicy, options.PrincipalPolicy);
#if DEBUG
if (options.DebugAgent)
package.AddSetting(EnginePackageSettings.DebugAgent, true);
//foreach (KeyValuePair<string, object> entry in package.Settings)
// if (!(entry.Value is string || entry.Value is int || entry.Value is bool))
// throw new Exception(string.Format("Package setting {0} is not a valid type", entry.Key));
#endif
if (options.DefaultTestNamePattern != null)
package.AddSetting(FrameworkPackageSettings.DefaultTestNamePattern, options.DefaultTestNamePattern);
if (options.TestParameters.Count != 0)
AddTestParametersSetting(package, options.TestParameters);
if (options.ConfigurationFile != null)
package.AddSetting(EnginePackageSettings.ConfigurationFile, options.ConfigurationFile);
return package;
}
/// <summary>
/// Sets test parameters, handling backwards compatibility.
/// </summary>
private static void AddTestParametersSetting(TestPackage testPackage, IDictionary<string, string> testParameters)
{
testPackage.AddSetting(FrameworkPackageSettings.TestParametersDictionary, testParameters);
if (testParameters.Count != 0)
{
// This cannot be changed without breaking backwards compatibility with old frameworks.
// Reserializes the way old frameworks understand, even if this runner's parsing is changed.
var oldFrameworkSerializedParameters = new StringBuilder();
foreach (var parameter in testParameters)
oldFrameworkSerializedParameters.Append(parameter.Key).Append('=').Append(parameter.Value).Append(';');
testPackage.AddSetting(FrameworkPackageSettings.TestParameters, oldFrameworkSerializedParameters.ToString(0, oldFrameworkSerializedParameters.Length - 1));
}
}
private TestFilter CreateTestFilter(ConsoleOptions options)
{
ITestFilterBuilder builder = _filterService.GetTestFilterBuilder();
foreach (string testName in options.TestList)
builder.AddTest(testName);
if (options.WhereClauseSpecified)
builder.SelectWhere(options.WhereClause);
return builder.GetFilter();
}
private bool VerifyEngineSupport(ConsoleOptions options)
{
foreach (var spec in options.ResultOutputSpecifications)
{
bool available = false;
foreach (var format in _resultService.Formats)
{
if (spec.Format == format)
{
available = true;
break;
}
}
if (!available)
{
Console.WriteLine("Unknown result format: {0}", spec.Format);
return false;
}
}
return true;
}
}
}