2 * Copyright (c) 2022 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 numPasses > 0 ? (float)numPasses * 100.0f / (numPasses + numFailures) : 0.0f,
234 numPasses > 0 ? (float)numFailures * 100.0f / (numPasses + numFailures) : 0.0f);
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[], std::string match, 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]);
387 if(match.compare(0, match.size(), testCase.name, match.size()))
395 testCase.result = RunTestCaseInChildProcess(testCase, quiet);
397 tt = system_clock::to_time_t(system_clock::now());
398 strftime(buffer, BUFSIZE, "%c", localtime(&tt));
399 std::string endTime(buffer);
401 if(testCase.result == 0)
411 OutputTestResult(ofs, processName, moduleName, testCase, startTime, endTime);
417 OutputStatistics(processName, numPasses, numFailures);
422 // Constantly runs up to MAX_NUM_CHILDREN processes
423 int32_t RunAllInParallel(const char* processName, ::testcase tc_array[], std::string match, bool reRunFailed, bool quiet)
425 int32_t numFailures = 0;
426 int32_t numPasses = 0;
428 RunningTestCases children;
429 std::vector<int32_t> failedTestCases;
431 // Fork up to MAX_NUM_CHILDREN processes, then
432 // wait. As soon as a proc completes, fork the next.
434 int32_t nextTestCase = 0;
435 int32_t numRunningChildren = 0;
437 while(tc_array[nextTestCase].name || numRunningChildren > 0)
439 // Create more children (up to the max number or til the end of the array)
440 while(numRunningChildren < MAX_NUM_CHILDREN && tc_array[nextTestCase].name)
445 if(match.compare(0, match.size(), tc_array[nextTestCase].name, match.size()))
452 int32_t pid = fork();
453 if(pid == 0) // Child process
455 TestCase testCase(nextTestCase, &tc_array[nextTestCase]);
456 int status = RunTestCaseRedirectOutput(testCase, quiet);
462 exit(EXIT_STATUS_FORK_FAILED);
464 else // Parent process
466 TestCase tc(nextTestCase, tc_array[nextTestCase].name);
467 tc.startTime = steady_clock::now();
468 tc.startSystemTime = system_clock::now();
473 numRunningChildren++;
483 int32_t childPid = 0;
484 if(numRunningChildren > 0) // Only wait if there are running children.
486 // Check to see if any children have finished yet
487 childPid = waitpid(-1, &status, WNOHANG);
492 // No children have finished.
493 // Check if any have exceeded execution time
494 auto endTime = std::chrono::steady_clock::now();
496 for(auto& tc : children)
498 std::chrono::steady_clock::duration timeSpan = endTime - tc.second.startTime;
499 std::chrono::duration<double> seconds = std::chrono::duration_cast<std::chrono::duration<double>>(timeSpan);
500 if(seconds.count() > MAXIMUM_CHILD_LIFETIME)
502 // Kill the child process. A subsequent call to waitpid will process signal result below.
503 kill(tc.first, SIGKILL);
507 else if(childPid == -1) // waitpid errored
510 exit(EXIT_STATUS_WAITPID_FAILED);
512 else // a child has finished
514 if(WIFEXITED(status))
516 auto& testCase = children[childPid];
517 testCase.result = WEXITSTATUS(status);
520 printf("Test case %s failed: %d\n", testCase.name, testCase.result);
521 failedTestCases.push_back(testCase.testCase);
528 numRunningChildren--;
531 else if(WIFSIGNALED(status) || WIFSTOPPED(status))
533 status = WIFSIGNALED(status) ? WTERMSIG(status) : WSTOPSIG(status);
535 RunningTestCases::iterator iter = children.find(childPid);
536 if(iter != children.end())
538 printf("Test case %s exited with signal %s\n", iter->second.name, strsignal(status));
539 iter->second.result = 1;
540 failedTestCases.push_back(iter->second.testCase);
544 printf("Unknown child process: %d signaled %s\n", childPid, strsignal(status));
548 numRunningChildren--;
555 OutputTestResults(processName, children);
558 OutputStatistics(processName, numPasses, numFailures);
562 for(uint32_t i = 0; i < failedTestCases.size(); i++)
564 char* testCaseStrapline;
565 int32_t numChars = asprintf(&testCaseStrapline, "Test case %s", tc_array[failedTestCases[i]].name);
566 printf("\n%s\n", testCaseStrapline);
567 for(int32_t j = 0; j < numChars; j++)
572 int index = failedTestCases[i];
573 TestCase testCase(index, &tc_array[index]);
574 RunTestCaseInChildProcess(testCase, false);
581 int32_t FindAndRunTestCase(::testcase tc_array[], const char* testCaseName)
583 int32_t result = EXIT_STATUS_TESTCASE_NOT_FOUND;
585 for(int32_t i = 0; tc_array[i].name; i++)
587 if(!strcmp(testCaseName, tc_array[i].name))
589 return RunTestCase(tc_array[i]);
593 printf("Unknown testcase name: \"%s\"\n", testCaseName);
597 void Usage(const char* program)
601 " %s <testcase name>\t\t Execute a test case\n"
602 " %s \t\t Execute all test cases in parallel\n"
603 " %s -r\t\t Execute all test cases in parallel, rerunning failed test cases\n"
604 " %s -s\t\t Execute all test cases serially\n"
605 " %s -q\t\t Run without output\n",
613 int RunTests(int argc, char* const argv[], ::testcase tc_array[])
615 int result = TestHarness::EXIT_STATUS_BAD_ARGUMENT;
616 const char* optString = "sfqm:";
617 bool optRerunFailed(true);
618 bool optRunSerially(false);
619 bool optQuiet(false);
620 std::string optMatch;
625 nextOpt = getopt(argc, argv, optString);
629 optRerunFailed = false;
632 optRunSerially = true;
641 TestHarness::Usage(argv[0]);
642 exit(TestHarness::EXIT_STATUS_BAD_ARGUMENT);
645 } while(nextOpt != -1);
647 if(optind == argc) // no testcase name in argument list
651 result = TestHarness::RunAll(argv[0], tc_array, optMatch, optQuiet);
655 result = TestHarness::RunAllInParallel(argv[0], tc_array, optMatch, optRerunFailed, optQuiet);
660 // optind is index of next argument - interpret as testcase name
661 result = TestHarness::FindAndRunTestCase(tc_array, argv[optind]);
666 } // namespace TestHarness