-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathGoogleTestBootstrap.cs
458 lines (368 loc) · 15.9 KB
/
GoogleTestBootstrap.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;
[ExcludeFromCodeCoverage]
public class UnitSuiteInfo
{
public String SuiteName;
/// <summary>
/// Gets list of supported suites (classes with test methods)
/// </summary>
virtual public IEnumerable<UnitSuiteInfo> GetSuites()
{
return Enumerable.Empty<UnitSuiteInfo>();
}
/// <summary>
/// Queries list of specific unit tests in specific suite (test methods in one class)
/// </summary>
/// <returns></returns>
virtual public IEnumerable<UnitTestInfo> GetUnitTests()
{
return Enumerable.Empty<UnitTestInfo>();
}
}
[ExcludeFromCodeCoverage]
public class UnitTestInfo
{
public String UnitTestName;
/// <summary>
/// Source code location, full path
/// </summary>
public String sourceCodePath = null;
/// <summary>
/// Source code line number
/// </summary>
public int line = 1;
/// <summary>
/// True if test will not be executed ([Ignore] attribute on), false - executed
/// </summary>
public bool ignored = false;
/// <summary>
/// Exception type which method is allowed to throw, null if exceptions are not allowed
/// </summary>
public Type ExceptionType = null;
/// <summary>
/// This method is must throw exception if test fails.
/// </summary>
/// <param name="isLastMethod">true if given method is last invoked, and api must clean up / release test class resources</param>
/// <exception cref="OperationCanceledException">Can be thrown to cancel ongoing tests</exception>
virtual public void InvokeTest(bool isLastMethod, TestResults localTestResults)
{
}
}
[ExcludeFromCodeCoverage]
public class GoogleTestBootstrap
{
//
// https://stackoverflow.com/questions/3469368/how-to-handle-accessviolationexception
//
// We want to catch all exceptions here, even process corrupted exceptions.
//
[HandleProcessCorruptedStateExceptions]
/// <summary>
/// Starts google test console main function, which in a turn either lists available tests or executes tests
/// </summary>
/// <param name="runTests">true if run tests by default, false if not</param>
/// <param name="args">command line arguments</param>
/// <param name="suits">test suites to use for test discovery and execution</param>
/// <returns>return true if command arguments were handled, false if not (application can continue)</returns>
public static bool TestMain(bool runTests, string[] args, params UnitSuiteInfo[] suits)
{
var asm = Assembly.GetExecutingAssembly();
String exeName = Path.GetFileName(asm.Location);
bool bListTests = false;
Dictionary<String, List<String>> filterClassMethodsToRun = null;
XDocument testsuites = new XDocument( new XDeclaration("1.0", "utf-8", ""), new XElement("testsuites"));
String slash = "[-/]+"; // "-tests", "--tests" or "/tests"
// Google unit testing uses --gtest_output=xml:<file>, can be shorten to "-out:<file>"
Regex reOutput = new Regex(slash + "(gtest_)?out(put=)?(xml)?:(.*)$");
// Google unit testing uses --gtest_list_tests, can be shorten to "-tests"
Regex reTests = new Regex(slash + "(gtest_list_)?tests");
// Google unit testing uses --gtest_filter=, can be shorten to "-filter=<class name>.<method name>" or "-filter:..."
Regex reFilter = new Regex(slash + "(gtest_)?filter.(.*)");
// Additional command line argument to run testing - "-test" or "-t"
Regex reDoTest = new Regex(slash + "t(est)?$");
bool printGoogleUnitTestFormat = false;
String xmlFilePath = null;
StringBuilder errorMessageHeadline = new StringBuilder();
StringBuilder errorMessage = new StringBuilder();
Regex reStackFrame = new Regex("^ *at +(.*?) in +(.*):line ([0-9]+)$");
foreach (var arg in args)
{
if (reDoTest.Match(arg).Success)
{
runTests = true;
continue;
}
if (reTests.Match(arg).Success)
{
bListTests = true;
runTests = false;
printGoogleUnitTestFormat = true;
continue;
}
var filtMatch = reFilter.Match(arg);
if (filtMatch.Success)
{
runTests = true;
printGoogleUnitTestFormat = true;
filterClassMethodsToRun = new Dictionary<string, List<string>>();
foreach (String classMethod in filtMatch.Groups[2].ToString().Split(':'))
{
var items = classMethod.Split('.').ToArray();
if (items.Length < 2)
continue;
String className = items[0];
if (!filterClassMethodsToRun.ContainsKey(className))
filterClassMethodsToRun.Add(className, new List<string>());
filterClassMethodsToRun[className].Add(items[1]);
}
continue;
}
var match = reOutput.Match(arg);
if (match.Success)
{
runTests = true;
printGoogleUnitTestFormat = true;
xmlFilePath = Path.GetFullPath(match.Groups[4].ToString());
}
}
if (!runTests && !bListTests)
return false;
if (runTests && !printGoogleUnitTestFormat)
Console.Write("Testing ");
Stopwatch timer = new Stopwatch();
TestResults totalTestResults = new TestResults();
bool allowContinueTesting = true;
Stopwatch totalTestTimer = new Stopwatch();
totalTestTimer.Start();
List<UnitSuiteInfo> testSuites = new List<UnitSuiteInfo>();
foreach (var suiteLister in suits)
testSuites.AddRange(suiteLister.GetSuites());
// Sort alphabetically so would be executed in same order as in Test Explorer
testSuites.Sort((a, b) => a.SuiteName.CompareTo(b.SuiteName));
foreach (UnitSuiteInfo testSuite in testSuites)
{
String suiteName = testSuite.SuiteName;
List<String> filterMethods = null;
XElement testsuite = null;
TestResults localTestResults = null;
// Filter classes to execute
if (filterClassMethodsToRun != null)
{
if (!filterClassMethodsToRun.ContainsKey(suiteName))
continue;
filterMethods = filterClassMethodsToRun[suiteName];
}
if(printGoogleUnitTestFormat)
Console.WriteLine(suiteName);
List<UnitTestInfo> unitTests = testSuite.GetUnitTests().ToList();
for (int i = 0; i < unitTests.Count; i++)
{
UnitTestInfo testinfo = unitTests[i];
bool isLastMethod = i == unitTests.Count - 1;
if (!isLastMethod)
isLastMethod = unitTests.Skip(i + 1).Take(unitTests.Count - i - 1).Select(x => x.ignored).Contains(false);
if (bListTests)
Console.WriteLine(" <loc>" + testinfo.sourceCodePath + "(" + testinfo.line + ")");
String unitTestName = testinfo.UnitTestName;
String displayUnitTestName = unitTestName;
if (unitTestName.Contains('.'))
{
displayUnitTestName = Path.GetFileNameWithoutExtension(unitTestName) + " # GetParam() = " + Path.GetExtension(unitTestName);
unitTestName = Path.GetFileNameWithoutExtension(unitTestName);
}
if (filterMethods != null)
{
if (!filterMethods.Contains(unitTestName) && !filterMethods.Contains("*"))
continue;
}
// Info about current class in xml report
if (localTestResults == null)
{
localTestResults = new TestResults();
testsuite = new XElement("testsuite");
testsuite.Add(new XAttribute("name", suiteName));
testsuites.Root.Add(testsuite);
}
if (bListTests)
{
Console.WriteLine(" " + displayUnitTestName);
localTestResults.tests++;
continue;
}
if (testinfo.ignored)
{
localTestResults.disabled++;
if (printGoogleUnitTestFormat)
Console.WriteLine("[ SKIPPED ] " + suiteName + "." + unitTestName + " (0 ms)");
XElement skippedMethod = new XElement("testcase");
skippedMethod.Add(new XAttribute("name", unitTestName));
skippedMethod.Add(new XAttribute("status", "notrun"));
skippedMethod.Add(new XAttribute("time", 0));
skippedMethod.Add(new XAttribute("classname", suiteName));
testsuite.Add(skippedMethod);
continue;
}
if (printGoogleUnitTestFormat)
Console.WriteLine("[ RUN ] " + suiteName + "." + unitTestName);
try
{
timer.Restart();
try
{
localTestResults.tests++;
errorMessageHeadline.Clear();
errorMessage.Clear();
testinfo.InvokeTest(isLastMethod, localTestResults);
}
finally
{
timer.Stop();
}
}
catch (Exception _ex)
{
Exception ex = _ex;
if (_ex.InnerException != null)
ex = _ex.InnerException;
bool isFailure = true;
if (testinfo.ExceptionType == ex.GetType())
isFailure = false;
if (ex.GetType() == typeof(OperationCanceledException))
allowContinueTesting = false;
if (isFailure)
{
localTestResults.failures++;
String errorMsgShort = ex.Message;
errorMessage.AppendLine("Test method " + suiteName + "." + unitTestName + " threw exception: ");
errorMessage.AppendLine(ex.GetType().FullName + ": " + ex.Message);
errorMessage.AppendLine("Call stack:");
foreach (String frameEntry in ex.StackTrace.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries))
{
var fmatch = reStackFrame.Match(frameEntry);
if (fmatch.Success)
errorMessage.AppendLine(fmatch.Groups[2] + "(" + fmatch.Groups[3] + "): " + fmatch.Groups[1]);
}
errorMessageHeadline.Append(errorMsgShort);
}
}
long elapsedTime = timer.ElapsedMilliseconds;
XElement methodTestInfo = new XElement("testcase");
methodTestInfo.Add(new XAttribute("name", unitTestName));
methodTestInfo.Add(new XAttribute("status", "run"));
methodTestInfo.Add(new XAttribute("time", elapsedTime / 1000.0));
methodTestInfo.Add(new XAttribute("classname", suiteName));
String testState = "[ OK ]";
if (errorMessageHeadline.Length != 0)
{
String msg = errorMessage.ToString();
String errorMessageOneLiner = errorMessageHeadline.ToString().Replace("\n", "").Replace("\r", "");
XElement failure = new XElement("failure", new XCData(msg));
failure.Add(new XAttribute("message", errorMessageOneLiner));
methodTestInfo.Add(failure);
// Needs to be printed to console window as well, otherwise not seen by visual studio
Console.WriteLine(msg);
//MessageBox.Show(
// "errorMessageOneLiner: " + errorMessageOneLiner + "\r\n\r\n" +
// "msg: " + msg
//);
testState = "[ FAILED ]";
}
if (printGoogleUnitTestFormat)
{
Console.WriteLine(testState + " " + suiteName + "." + unitTestName + " (" + elapsedTime.ToString() + " ms)");
Console.Out.Flush();
}
else
{
Console.Write(".");
}
testsuite.Add(methodTestInfo);
if (!allowContinueTesting)
break;
}
// class scan complete, fetch results if necessary
if (testsuite != null)
{
FetchTestResults(testsuite, localTestResults);
totalTestResults.Add(localTestResults);
}
if (!allowContinueTesting)
break;
}
totalTestTimer.Stop();
// Save test results if requivested.
if (xmlFilePath != null)
{
try
{
String dir = Path.GetDirectoryName(xmlFilePath);
if (dir != "" && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
FetchTestResults(testsuites.Root, totalTestResults);
testsuites.Save(xmlFilePath);
}
catch (Exception ex)
{
Console.WriteLine("Error: Could not save '" + xmlFilePath + ": " + ex.Message);
}
}
if (runTests)
{
if (!printGoogleUnitTestFormat)
{
Console.WriteLine(" ok.");
String summaryLine = (totalTestResults.tests - totalTestResults.failures) + " tests passed";
if( totalTestResults.files != 0 )
summaryLine += " (" + totalTestResults.files + " files verified)";
if (totalTestResults.failures != 0 )
summaryLine += ", " + totalTestResults.failures + " FAILED";
if (totalTestResults.disabled != 0)
summaryLine += ", " + totalTestResults.disabled + " skipped";
Console.WriteLine(summaryLine);
Console.WriteLine();
}
TimeSpan elapsedtime = totalTestTimer.Elapsed;
String elapsed = "";
if (elapsedtime.Minutes != 0)
elapsed += elapsedtime.Minutes + " min ";
elapsed += elapsedtime.ToString(@"ss\.ff") + " sec";
Console.WriteLine("Test time: " + elapsed);
}
return true;
}
static void FetchTestResults(XElement node, TestResults tr)
{
foreach (var f in tr.GetType().GetFields())
{
String v = f.GetValue(tr).ToString();
node.Add(new XAttribute(f.Name, v));
}
}
}
[ExcludeFromCodeCoverage]
public class TestResults
{
public int tests = 0;
public int files = 0;
public int failures = 0;
public int disabled = 0;
public int errors = 0;
public void Add(TestResults local)
{
tests += local.tests;
files += local.files;
failures += local.failures;
disabled += local.disabled;
errors += local.errors;
}
};