2 * Copyright (c) 2021 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "test-harness.h"
21 #include <sys/types.h>
37 using std::chrono::steady_clock;
38 using std::chrono::system_clock;
42 typedef std::map<int32_t, TestCase> RunningTestCases;
44 const double MAXIMUM_CHILD_LIFETIME(60.0f); // 1 minute
46 const char* basename(const char* path)
48 const char* ptr = path;
49 const char* slash = NULL;
50 for(; *ptr != '\0'; ++ptr)
52 if(*ptr == '/') slash = ptr;
54 if(slash != NULL) ++slash;
58 std::vector<std::string> Split(const std::string& aString, char delimiter)
60 std::vector<std::string> tokens;
62 std::istringstream tokenStream(aString);
63 while(std::getline(tokenStream, token, delimiter))
65 tokens.push_back(token);
70 std::string Join(const std::vector<std::string>& tokens, char delimiter)
72 std::ostringstream oss;
74 unsigned int delimiterCount = 0;
75 for(auto& token : tokens)
78 if(delimiterCount < tokens.size() - 1)
87 std::string ChildOutputFilename(int pid)
89 std::ostringstream os;
90 os << "/tmp/tct-child." << pid;
94 std::string TestModuleFilename(const char* processName)
96 auto pathComponents = Split(processName, '/');
97 auto aModule = pathComponents.back();
98 aModule += "-tests.xml";
102 std::string TestModuleName(const char* processName)
104 auto pathComponents = Split(processName, '/');
105 auto aModule = pathComponents.back();
106 auto moduleComponents = Split(aModule, '-');
108 moduleComponents[1][0] = std::toupper(moduleComponents[1][0]);
109 moduleComponents[2][0] = std::toupper(moduleComponents[2][0]);
111 std::ostringstream oss;
112 for(unsigned int i = 1; i < moduleComponents.size() - 1; ++i) // [0]=tct, [n-1]=core
114 oss << moduleComponents[i];
116 if(i > 1 && i < moduleComponents.size() - 2) // skip first and last delimiter
125 std::string ReadAndEscape(std::string filename)
127 std::ostringstream os;
129 ifs.open(filename, std::ifstream::in);
133 std::getline(ifs, line);
159 void OutputTestResult(
161 const char* pathToExecutable,
162 std::string testSuiteName,
164 std::string startTime,
167 std::string outputFilename = ChildOutputFilename(testCase.childPid);
168 std::string testOutput = ReadAndEscape(outputFilename);
170 ofs << "<testcase component=\"CoreAPI/" << testSuiteName << "/default\" execution_type=\"auto\" id=\""
171 << testCase.name << "\" purpose=\"\" result=\"" << (testCase.result == 0 ? "PASS" : "FAIL") << "\">" << std::endl
172 << "<description><test_script_entry test_script_expected_result=\"0\">"
173 << pathToExecutable << testCase.name << "</test_script_entry>" << std::endl
175 << "<result_info><actual_result>" << (testCase.result == 0 ? "PASS" : "FAIL") << "</actual_result>" << std::endl
176 << "<start>" << startTime << "</start>"
177 << "<end>" << endTime << "</end>"
178 << "<stdout><![CDATA[]]></stdout>"
179 << "<stderr><![CDATA[" << testOutput << "]]></stderr></result_info></testcase>" << std::endl;
181 unlink(outputFilename.c_str());
184 void OutputTestResults(const char* processName, RunningTestCases& children)
187 std::string filename = TestModuleFilename(processName);
188 std::string moduleName = TestModuleName(processName);
189 ofs.open(filename, std::ofstream::out | std::ofstream::app);
191 // Sort completed cases by original test case id
192 std::vector<TestCase> childTestCases;
193 childTestCases.reserve(children.size());
194 for(auto& element : children) childTestCases.push_back(element.second);
195 std::sort(childTestCases.begin(), childTestCases.end(), [](const TestCase& a, const TestCase& b) {
196 return a.testCase < b.testCase;
199 const int BUFSIZE = 256;
200 char buffer[BUFSIZE];
201 for(auto& testCase : childTestCases)
203 auto tt = system_clock::to_time_t(testCase.startSystemTime);
204 strftime(buffer, BUFSIZE, "%c", localtime(&tt));
205 std::string startTime(buffer);
206 OutputTestResult(ofs, processName, moduleName, testCase, startTime, startTime);
212 void OutputStatistics(const char* processName, int32_t numPasses, int32_t numFailures)
214 FILE* fp = fopen("summary.xml", "a");
218 " <suite name=\"%s-tests\">\n"
219 " <total_case>%d</total_case>\n"
220 " <pass_case>%d</pass_case>\n"
221 " <pass_rate>%5.2f</pass_rate>\n"
222 " <fail_case>%d</fail_case>\n"
223 " <fail_rate>%5.2f</fail_rate>\n"
224 " <block_case>0</block_case>\n"
225 " <block_rate>0.00</block_rate>\n"
226 " <na_case>0</na_case>\n"
227 " <na_rate>0.00</na_rate>\n"
229 basename(processName),
230 numPasses + numFailures,
232 (float)numPasses * 100.0f / (numPasses + numFailures),
234 (float)numFailures * 100.0f / (numPasses + numFailures));
239 int32_t RunTestCase(struct ::testcase_s& testCase)
241 int32_t result = EXIT_STATUS_TESTCASE_FAILED;
243 // dont want to catch exception as we want to be able to get
244 // gdb stack trace from the first error
245 // by default tests should all always pass with no exceptions
252 result = testCase.function();
256 // just catch test fail exception, return is already set to EXIT_STATUS_TESTCASE_FAILED
266 int32_t RunTestCaseRedirectOutput(TestCase& testCase, bool suppressOutput)
268 // Executing in child process
269 // Close stdout and stderr to suppress the log output
270 close(STDOUT_FILENO); // File descriptor number for stdout is 1
272 // The POSIX specification requires that /dev/null must be provided,
273 // The open function always chooses the lowest unused file descriptor
274 // It is sufficient for stdout to be writable.
275 open("/dev/null", O_WRONLY); // Redirect file descriptor number 1 (i.e. stdout) to /dev/null
278 close(STDERR_FILENO);
281 stderr = fopen("/dev/null", "w+"); // Redirect fd 2 to /dev/null
285 // When stderr is opened it must be both readable and writable.
286 std::string childOutputFilename = ChildOutputFilename(getpid());
287 stderr = fopen(childOutputFilename.c_str(), "w+");
290 int32_t status = RunTestCase(*testCase.tctPtr);
298 int32_t RunTestCaseInChildProcess(TestCase& testCase, bool redirect)
300 int32_t testResult = EXIT_STATUS_TESTCASE_FAILED;
302 int32_t pid = fork();
303 if(pid == 0) // Child process
307 int status = RunTestCaseRedirectOutput(testCase, false);
312 int status = RunTestCase(*testCase.tctPtr);
319 exit(EXIT_STATUS_FORK_FAILED);
321 else // Parent process
324 int32_t childPid = waitpid(pid, &status, 0);
325 testCase.childPid = childPid;
329 exit(EXIT_STATUS_WAITPID_FAILED);
331 if(WIFEXITED(status))
335 testResult = WEXITSTATUS(status);
338 printf("Test case %s failed: %d\n", testCase.name, testResult);
342 else if(WIFSIGNALED(status))
344 int32_t signal = WTERMSIG(status);
345 testResult = EXIT_STATUS_TESTCASE_ABORTED;
346 if(signal == SIGABRT)
348 printf("Test case %s failed: test case asserted\n", testCase.name);
352 printf("Test case %s failed: exit with signal %s\n", testCase.name, strsignal(WTERMSIG(status)));
355 else if(WIFSTOPPED(status))
357 printf("Test case %s failed: stopped with signal %s\n", testCase.name, strsignal(WSTOPSIG(status)));
365 int32_t RunAll(const char* processName, ::testcase tc_array[], bool quiet)
367 int32_t numFailures = 0;
368 int32_t numPasses = 0;
370 std::string filename = TestModuleFilename(processName);
371 std::string moduleName = TestModuleName(processName);
372 ofs.open(filename, std::ofstream::out | std::ofstream::app);
373 const int BUFSIZE = 256;
374 char buffer[BUFSIZE];
376 // Run test cases in child process( to handle signals ), but run serially.
377 for(uint32_t i = 0; tc_array[i].name; i++)
379 auto tt = system_clock::to_time_t(system_clock::now());
380 strftime(buffer, BUFSIZE, "%c", localtime(&tt));
381 std::string startTime(buffer);
383 TestCase testCase(i, &tc_array[i]);
384 testCase.result = RunTestCaseInChildProcess(testCase, quiet);
386 tt = system_clock::to_time_t(system_clock::now());
387 strftime(buffer, BUFSIZE, "%c", localtime(&tt));
388 std::string endTime(buffer);
390 if(testCase.result == 0)
400 OutputTestResult(ofs, processName, moduleName, testCase, startTime, endTime);
405 OutputStatistics(processName, numPasses, numFailures);
410 // Constantly runs up to MAX_NUM_CHILDREN processes
411 int32_t RunAllInParallel(const char* processName, ::testcase tc_array[], bool reRunFailed, bool quiet)
413 int32_t numFailures = 0;
414 int32_t numPasses = 0;
416 RunningTestCases children;
417 std::vector<int32_t> failedTestCases;
419 // Fork up to MAX_NUM_CHILDREN processes, then
420 // wait. As soon as a proc completes, fork the next.
422 int32_t nextTestCase = 0;
423 int32_t numRunningChildren = 0;
425 while(tc_array[nextTestCase].name || numRunningChildren > 0)
427 // Create more children (up to the max number or til the end of the array)
428 while(numRunningChildren < MAX_NUM_CHILDREN && tc_array[nextTestCase].name)
430 int32_t pid = fork();
431 if(pid == 0) // Child process
433 TestCase testCase(nextTestCase, &tc_array[nextTestCase]);
434 int status = RunTestCaseRedirectOutput(testCase, quiet);
440 exit(EXIT_STATUS_FORK_FAILED);
442 else // Parent process
444 TestCase tc(nextTestCase, tc_array[nextTestCase].name);
445 tc.startTime = steady_clock::now();
446 tc.startSystemTime = system_clock::now();
451 numRunningChildren++;
455 // Check to see if any children have finished yet
457 int32_t childPid = waitpid(-1, &status, WNOHANG);
460 // No children have finished.
461 // Check if any have exceeded execution time
462 auto endTime = std::chrono::steady_clock::now();
464 for(auto& tc : children)
466 std::chrono::steady_clock::duration timeSpan = endTime - tc.second.startTime;
467 std::chrono::duration<double> seconds = std::chrono::duration_cast<std::chrono::duration<double>>(timeSpan);
468 if(seconds.count() > MAXIMUM_CHILD_LIFETIME)
470 // Kill the child process. A subsequent call to waitpid will process signal result below.
471 kill(tc.first, SIGKILL);
475 else if(childPid == -1) // waitpid errored
478 exit(EXIT_STATUS_WAITPID_FAILED);
480 else // a child has finished
482 if(WIFEXITED(status))
484 auto& testCase = children[childPid];
485 testCase.result = WEXITSTATUS(status);
488 printf("Test case %s failed: %d\n", testCase.name, testCase.result);
489 failedTestCases.push_back(testCase.testCase);
496 numRunningChildren--;
499 else if(WIFSIGNALED(status) || WIFSTOPPED(status))
501 status = WIFSIGNALED(status) ? WTERMSIG(status) : WSTOPSIG(status);
503 RunningTestCases::iterator iter = children.find(childPid);
504 if(iter != children.end())
506 printf("Test case %s exited with signal %s\n", iter->second.name, strsignal(status));
507 iter->second.result = 1;
508 failedTestCases.push_back(iter->second.testCase);
512 printf("Unknown child process: %d signaled %s\n", childPid, strsignal(status));
516 numRunningChildren--;
523 OutputTestResults(processName, children);
526 OutputStatistics(processName, numPasses, numFailures);
530 for(uint32_t i = 0; i < failedTestCases.size(); i++)
532 char* testCaseStrapline;
533 int32_t numChars = asprintf(&testCaseStrapline, "Test case %s", tc_array[failedTestCases[i]].name);
534 printf("\n%s\n", testCaseStrapline);
535 for(int32_t j = 0; j < numChars; j++)
540 int index = failedTestCases[i];
541 TestCase testCase(index, &tc_array[index]);
542 RunTestCaseInChildProcess(testCase, false);
549 int32_t FindAndRunTestCase(::testcase tc_array[], const char* testCaseName)
551 int32_t result = EXIT_STATUS_TESTCASE_NOT_FOUND;
553 for(int32_t i = 0; tc_array[i].name; i++)
555 if(!strcmp(testCaseName, tc_array[i].name))
557 return RunTestCase(tc_array[i]);
561 printf("Unknown testcase name: \"%s\"\n", testCaseName);
565 void Usage(const char* program)
569 " %s <testcase name>\t\t Execute a test case\n"
570 " %s \t\t Execute all test cases in parallel\n"
571 " %s -r\t\t Execute all test cases in parallel, rerunning failed test cases\n"
572 " %s -s\t\t Execute all test cases serially\n"
573 " %s -q\t\t Run without output\n",
581 int RunTests(int argc, char* const argv[], ::testcase tc_array[])
583 int result = TestHarness::EXIT_STATUS_BAD_ARGUMENT;
584 const char* optString = "sfq";
585 bool optRerunFailed(true);
586 bool optRunSerially(false);
587 bool optQuiet(false);
592 nextOpt = getopt(argc, argv, optString);
596 optRerunFailed = false;
599 optRunSerially = true;
605 TestHarness::Usage(argv[0]);
606 exit(TestHarness::EXIT_STATUS_BAD_ARGUMENT);
609 } while(nextOpt != -1);
611 if(optind == argc) // no testcase name in argument list
615 result = TestHarness::RunAll(argv[0], tc_array, optQuiet);
619 result = TestHarness::RunAllInParallel(argv[0], tc_array, optRerunFailed, optQuiet);
624 // optind is index of next argument - interpret as testcase name
625 result = TestHarness::FindAndRunTestCase(tc_array, argv[optind]);
630 } // namespace TestHarness