-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
test_runner.cpp
643 lines (567 loc) · 20.5 KB
/
test_runner.cpp
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
/***
* Copyright (C) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
*
* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
**/
// TestRunner.cpp : Defines the entry point for the console application.
//
#include <algorithm>
#include <iostream>
#include <map>
#include <regex>
#include <vector>
#ifdef _WIN32
#include <conio.h>
#include <Windows.h>
#else
#include <unistd.h>
#ifdef __APPLE__
#include <dirent.h>
#else
#include <boost/filesystem.hpp>
#endif
#endif
#include "../UnitTestpp/src/GlobalSettings.h"
#include "../UnitTestpp/src/TestReporterStdout.h"
#include "../UnitTestpp/src/TimeHelpers.h"
#include "test_module_loader.h"
static void print_help()
{
std::cout
<< "Usage: testrunner.exe <test_binaries> [/list] [/listproperties] [/noignore] [/breakonerror] [/detectleaks]"
<< std::endl;
std::cout << " [/name:<test_name>] [/select:@key=value] [/loop:<num_times>]" << std::endl;
std::cout << std::endl;
std::cout << " /list List all the names of the test_binaries and their" << std::endl;
std::cout << " test cases." << std::endl;
std::cout << std::endl;
std::cout << " /listproperties List all the names of the test binaries, test cases, and" << std::endl;
std::cout << " test properties." << std::endl;
std::cout << std::endl;
std::cout << " /breakonerror Break into the debugger when a failure is encountered." << std::endl;
std::cout << " /detectleaks Turns CRT leak detection and prints any leaks, Windows only." << std::endl;
std::cout << std::endl;
std::cout << " /name:<test_name> Run only test cases with matching name. Can contain the" << std::endl;
std::cout << " wildcard '*' character." << std::endl;
std::cout << std::endl;
std::cout << " /noignore Include tests even if they have the 'Ignore' property set" << std::endl;
std::cout << std::endl;
std::cout << " /select:@key=value Filter by the value of a particular test property." << std::endl;
std::cout << std::endl;
std::cout << " /loop:<num_times> Run test cases a specified number of times." << std::endl;
std::cout << std::endl;
std::cout << "Can also specify general global settings with the following:" << std::endl;
std::cout << " /global_key:global_value OR /global_key" << std::endl << std::endl;
}
static std::string to_lower(const std::string& str)
{
std::string lower;
for (auto iter = str.begin(); iter != str.end(); ++iter)
{
lower.push_back((char)tolower(*iter));
}
return lower;
}
static std::vector<std::string> get_files_in_directory()
{
std::vector<std::string> files;
#ifdef _WIN32
char exe_directory_buffer[MAX_PATH];
GetModuleFileNameA(NULL, exe_directory_buffer, MAX_PATH);
std::string exe_directory = to_lower(exe_directory_buffer);
auto location = exe_directory.rfind("\\");
if (location != std::string::npos)
{
exe_directory.erase(location + 1);
}
else
{
std::cout << "Could not determine execution directory" << std::endl;
exit(-1);
}
exe_directory.append("*");
WIN32_FIND_DATAA findFileData;
HANDLE hFind = FindFirstFileA(exe_directory.c_str(), &findFileData);
if (hFind != INVALID_HANDLE_VALUE && !(findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
files.push_back(findFileData.cFileName);
}
while (FindNextFileA(hFind, &findFileData) != 0)
{
if (!(findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
files.push_back(findFileData.cFileName);
}
}
FindClose(hFind);
#elif defined(__APPLE__)
auto exe_directory = getcwd(nullptr, 0);
DIR* dir = opendir(exe_directory);
free(exe_directory);
if (dir != nullptr)
{
struct dirent* ent = readdir(dir);
while (ent != nullptr)
{
if (ent->d_type == DT_REG)
{
files.push_back(ent->d_name);
}
ent = readdir(dir);
}
closedir(dir);
}
#else
using namespace boost::filesystem;
auto exe_directory = initial_path().string();
for (auto it = directory_iterator(path(exe_directory)); it != directory_iterator(); ++it)
{
if (is_regular_file(*it))
{
files.push_back(it->path().filename().string());
}
}
#endif
return files;
}
static std::string replace_wildcard_for_regex(const std::string& str)
{
std::string result;
for (auto iter = str.begin(); iter != str.end(); ++iter)
{
if (*iter == '*')
{
result.push_back('.');
}
result.push_back(*iter);
}
return result;
}
static std::vector<std::string> get_matching_binaries(const std::string& dllName)
{
std::vector<std::string> matchingFiles;
// If starts with .\ remove it.
std::string expandedDllName(dllName);
if (expandedDllName.size() > 2 && expandedDllName[0] == '.' && expandedDllName[1] == '\\')
{
expandedDllName = expandedDllName.substr(2);
}
// Escape any '.'
size_t oldLocation = 0;
size_t location = expandedDllName.find(".", oldLocation);
while (location != std::string::npos)
{
expandedDllName.insert(expandedDllName.find(".", oldLocation), "\\");
oldLocation = location + 2;
location = expandedDllName.find(".", oldLocation);
}
// Replace all '*' in dllName with '.*'
expandedDllName = replace_wildcard_for_regex(expandedDllName);
std::vector<std::string> allFiles = get_files_in_directory();
// Filter out any files that don't match.
std::regex dllRegex(expandedDllName, std::regex_constants::icase);
for (auto iter = allFiles.begin(); iter != allFiles.end(); ++iter)
{
if (std::regex_match(*iter, dllRegex))
{
matchingFiles.push_back(*iter);
}
}
return matchingFiles;
}
static std::multimap<std::string, std::string> g_properties;
static std::vector<std::string> g_test_binaries;
static int g_individual_test_timeout = 60000 * 3;
static int parse_command_line(int argc, char** argv)
{
for (int i = 1; i < argc; ++i)
{
std::string arg(argv[i]);
arg = to_lower(arg);
if (arg.compare("/?") == 0)
{
print_help();
return -1;
}
else if (arg.find("/") == 0)
{
if (arg.find("/select:@") == 0)
{
std::string prop_asgn = std::string(argv[i]).substr(std::string("/select:@").size());
auto eqsgn = prop_asgn.find('=');
if (eqsgn < prop_asgn.size())
{
auto key = prop_asgn.substr(0, eqsgn);
auto value = prop_asgn.substr(eqsgn + 1);
g_properties.insert(std::make_pair(key, value));
}
else
{
g_properties.insert(std::make_pair(prop_asgn, "*"));
}
}
else if (arg.find(":") != std::string::npos)
{
const size_t index = arg.find(":");
const std::string key = std::string(argv[i]).substr(1, index - 1);
const std::string value = std::string(argv[i]).substr(index + 1);
UnitTest::GlobalSettings::Add(key, value);
}
else
{
UnitTest::GlobalSettings::Add(arg.substr(1), std::string{});
}
}
else if (arg.find("/debug") == 0)
{
printf("Attach debugger now...\n");
int temp;
std::cin >> temp;
}
else
{
g_test_binaries.push_back(arg);
}
}
return 0;
}
static bool matched_properties(const UnitTest::TestProperties& test_props)
{
// TestRunner can only execute either desktop or winrt tests, but not both.
// This starts with visual studio versions after VS 2012.
#if defined(_MSC_VER) && (_MSC_VER >= 1800)
#ifdef WINRT_TEST_RUNNER
UnitTest::GlobalSettings::Add("winrt", std::string{});
#elif defined DESKTOP_TEST_RUNNER
UnitTest::GlobalSettings::Add("desktop", std::string{});
#endif
#endif
// The 'Require' property on a test case is special.
// It requires a certain global setting to be fulfilled to execute.
if (test_props.Has("Requires"))
{
const std::string requires = test_props.Get("Requires");
std::vector<std::string> requirements;
// Can be multiple requirements, a semi colon seperated list
std::string::size_type pos = requires.find_first_of(';');
std::string::size_type last_pos = 0;
while (pos != std::string::npos)
{
requirements.push_back(requires.substr(last_pos, pos - last_pos));
last_pos = pos + 1;
pos = requires.find_first_of(';', last_pos);
}
requirements.push_back(requires.substr(last_pos));
for (auto iter = requirements.begin(); iter != requirements.end(); ++iter)
{
if (!UnitTest::GlobalSettings::Has(to_lower(*iter)))
{
return false;
}
}
}
if (g_properties.size() == 0) return true;
// All the properties specified at the cmd line act as a 'filter'.
for (auto iter = g_properties.begin(); iter != g_properties.end(); ++iter)
{
auto name = iter->first;
auto value = iter->second;
if (test_props.Has(name) && (value == "*" || test_props[name] == value))
{
return true;
}
}
return false;
}
// Functions to list all the test cases and their properties.
static void handle_list_option(bool listProperties, const UnitTest::TestList& tests, const std::regex& nameRegex)
{
UnitTest::Test* pTest = tests.GetFirst();
while (pTest != nullptr)
{
std::string fullTestName = pTest->m_details.suiteName;
fullTestName.append(":");
fullTestName.append(pTest->m_details.testName);
if (matched_properties(pTest->m_properties) && std::regex_match(fullTestName, nameRegex))
{
std::cout << " " << fullTestName << std::endl;
if (listProperties)
{
std::for_each(pTest->m_properties.begin(),
pTest->m_properties.end(),
[&](const std::pair<std::string, std::string> key_value) {
std::cout << " " << key_value.first << ": " << key_value.second << std::endl;
});
}
}
pTest = pTest->m_nextTest;
}
}
static void ChangeConsoleTextColorToRed()
{
#if defined(__cplusplus_winrt)
#elif defined(_WIN32)
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 0x0004 | 0x0008);
#else
std::cout << "\033[1;31m";
#endif
}
static void ChangeConsoleTextColorToGreen()
{
#if defined(__cplusplus_winrt)
#elif defined(_WIN32)
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 0x0002 | 0x0008);
#else
std::cout << "\033[1;32m";
#endif
}
static void ChangeConsoleTextColorToGrey()
{
#if defined(__cplusplus_winrt)
#elif defined(_WIN32)
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN);
#else
std::cout << "\033[0m";
#endif
}
bool IsTestIgnored(UnitTest::Test* pTest)
{
if (pTest->m_properties.Has("Ignore")) return true;
#ifdef _WIN32
if (pTest->m_properties.Has("Ignore:Windows")) return true;
#elif defined(__APPLE__)
if (pTest->m_properties.Has("Ignore:Apple")) return true;
#elif (defined(ANDROID) || defined(__ANDROID__))
if (pTest->m_properties.Has("Ignore:Android")) return true;
#else
if (pTest->m_properties.Has("Ignore:Linux")) return true;
#endif
return false;
}
typedef std::map<std::string, UnitTest::TestList> testlist_t;
void list_test_options(testlist_t& testlists)
{
std::regex nameRegex;
if (UnitTest::GlobalSettings::Has("name"))
{
nameRegex = replace_wildcard_for_regex(UnitTest::GlobalSettings::Get("name"));
}
else
{
nameRegex = std::regex(".*");
}
bool listProperties = UnitTest::GlobalSettings::Has("listproperties");
for (auto& test_p : testlists)
{
std::cout << "=== Showing options for " << test_p.first << " ===" << std::endl;
handle_list_option(listProperties, test_p.second, nameRegex);
}
}
testlist_t load_all_tests(test_module_loader& module_loader)
{
// Remember where each list of tests came from.
testlist_t testlists;
// Retrieve the static tests and clear for dll loading.
testlists.insert({"<static>", UnitTest::GetTestList()});
UnitTest::GetTestList().Clear();
// Cycle through all the test binaries and load them
for (auto& binary_names : g_test_binaries)
{
std::vector<std::string> matchingBinaries = get_matching_binaries(binary_names);
if (matchingBinaries.empty())
{
ChangeConsoleTextColorToRed();
std::cout << "Pattern '" << binary_names << "' not found." << std::endl;
ChangeConsoleTextColorToGrey();
}
for (auto& binary : matchingBinaries)
{
unsigned long error_code = module_loader.load(binary);
if (error_code != 0)
{
// Only omit an error if a wildcard wasn't used.
if (binary_names.find('*') == std::string::npos)
{
ChangeConsoleTextColorToRed();
std::cout << "Error loading " << binary << ": " << error_code << std::endl;
ChangeConsoleTextColorToGrey();
std::exit(error_code);
}
else
{
continue;
}
}
std::cout << "Loaded " << binary << "..." << std::endl;
// Store the loaded binary into the test list map
testlists.insert({binary, UnitTest::GetTestList()});
UnitTest::GetTestList().Clear();
}
}
return testlists;
}
void run_all_tests(UnitTest::TestRunner& testRunner, testlist_t& testlists)
{
int numTimesToRun = 1;
if (UnitTest::GlobalSettings::Has("loop"))
{
std::istringstream strstream(UnitTest::GlobalSettings::Get("loop"));
strstream >> numTimesToRun;
}
const bool include_ignored_tests = UnitTest::GlobalSettings::Has("noignore");
for (int i = 0; i < numTimesToRun; ++i)
{
for (auto& test_p : testlists)
{
std::cout << "=== Running tests from: " << test_p.first << " ===" << std::endl;
UnitTest::TestList& tests = test_p.second;
std::regex nameRegex(".*");
if (UnitTest::GlobalSettings::Has("name"))
{
nameRegex = replace_wildcard_for_regex(UnitTest::GlobalSettings::Get("name"));
}
testRunner.RunTestsIf(tests,
[&](UnitTest::Test* pTest) -> bool {
// Combine suite and test name
std::string fullTestName = pTest->m_details.suiteName;
fullTestName.append(":");
fullTestName.append(pTest->m_details.testName);
if (IsTestIgnored(pTest) && !include_ignored_tests)
return false;
else
return matched_properties(pTest->m_properties) &&
std::regex_match(fullTestName, nameRegex);
},
g_individual_test_timeout);
}
}
}
#if defined(__cplusplus_winrt)
#include "ROApi.h"
#endif
int main(int argc, char* argv[])
{
#if defined(__cplusplus_winrt)
Windows::Foundation::Initialize(RO_INIT_MULTITHREADED);
#elif defined(_WIN32)
// Add standard error as output as well.
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_WNDW | _CRTDBG_MODE_DEBUG);
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_WNDW | _CRTDBG_MODE_DEBUG);
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
// The test runner built with WinRT support might be used on a pre Win8 machine.
// Obviously in that case WinRT test cases can't run, but non WinRT ones should be
// fine. So dynamically try to call RoInitialize/RoUninitialize.
HMODULE hComBase = LoadLibrary(L"combase.dll");
if (hComBase != nullptr)
{
typedef HRESULT(WINAPI * RoInit)(int);
RoInit roInitFunc = (RoInit)GetProcAddress(hComBase, "RoInitialize");
if (roInitFunc != nullptr)
{
roInitFunc(1); // RO_INIT_MULTITHREADED
}
}
struct console_restorer
{
CONSOLE_SCREEN_BUFFER_INFO m_originalConsoleInfo;
console_restorer() { GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &m_originalConsoleInfo); }
~console_restorer()
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), m_originalConsoleInfo.wAttributes);
}
} local;
#endif
if (parse_command_line(argc, argv) != 0)
{
return -1;
}
if (g_test_binaries.empty())
{
std::cout << "Warning: no test binaries were specified" << std::endl;
}
int totalTestCount = 0, failedTestCount = 0;
std::vector<std::string> failedTests;
UnitTest::TestReporterStdout testReporter;
bool breakOnError = false;
if (UnitTest::GlobalSettings::Has("breakonerror"))
{
breakOnError = true;
}
// The list_test_options() function determines if list or listProperties.
bool listOption = false;
if (UnitTest::GlobalSettings::Has("list"))
{
listOption = true;
}
if (UnitTest::GlobalSettings::Has("listproperties"))
{
listOption = true;
}
#ifdef _WIN32
if (UnitTest::GlobalSettings::Has("detectleaks"))
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
}
#endif
// Start timer.
UnitTest::Timer timer;
timer.Start();
test_module_loader module_loader;
testlist_t testlists = load_all_tests(module_loader);
if (listOption)
{
list_test_options(testlists);
return 0;
}
// Run test cases
UnitTest::TestRunner testRunner(testReporter, breakOnError);
run_all_tests(testRunner, testlists);
totalTestCount += testRunner.GetTestResults()->GetTotalTestCount();
failedTestCount += testRunner.GetTestResults()->GetFailedTestCount();
if (totalTestCount == 0)
{
std::cout << "No tests were run. Check the command line syntax (try 'TestRunner.exe /help')" << std::endl;
}
else
{
if (testRunner.GetTestResults()->GetFailedTestCount() > 0)
{
ChangeConsoleTextColorToRed();
const std::vector<std::string>& failed = testRunner.GetTestResults()->GetFailedTests();
std::for_each(failed.begin(), failed.end(), [](const std::string& failedTest) {
std::cout << "**** " << failedTest << " FAILED ****" << std::endl << std::endl;
std::fflush(stdout);
});
ChangeConsoleTextColorToGrey();
}
else
{
ChangeConsoleTextColorToGreen();
std::cout << "All test cases PASSED" << std::endl << std::endl;
ChangeConsoleTextColorToGrey();
}
const std::vector<std::string>& newFailedTests = testRunner.GetTestResults()->GetFailedTests();
failedTests.insert(failedTests.end(), newFailedTests.begin(), newFailedTests.end());
const double elapsedTime = timer.GetTimeInMs();
std::cout << "Finished running all " << totalTestCount << " tests." << std::endl
<< "Took " << elapsedTime << "ms" << std::endl;
}
#if defined(__cplusplus_winrt)
#elif defined(_WIN32)
if (hComBase != nullptr)
{
typedef void(WINAPI * RoUnInit)();
RoUnInit roUnInitFunc = (RoUnInit)GetProcAddress(hComBase, "RoUninitialize");
if (roUnInitFunc != nullptr)
{
roUnInitFunc();
}
FreeLibrary(hComBase);
}
#endif
return failedTestCount;
}