1 /*-------------------------------------------------------------------------
2 * drawElements Quality Program Test Executor
3 * ------------------------------------------
5 * Copyright 2014 The Android Open Source Project
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
21 * \brief Command line test executor.
22 *//*--------------------------------------------------------------------*/
24 #include "xeBatchExecutor.hpp"
25 #include "xeLocalTcpIpLink.hpp"
26 #include "xeTcpIpLink.hpp"
27 #include "xeTestCaseListParser.hpp"
28 #include "xeTestLogWriter.hpp"
29 #include "xeTestResultParser.hpp"
31 #include "deCommandLine.hpp"
32 #include "deDirectoryIterator.hpp"
33 #include "deStringUtil.hpp"
47 #if (DE_OS == DE_OS_UNIX) || (DE_OS == DE_OS_ANDROID) || (DE_OS == DE_OS_WIN32)
57 // Command line arguments.
61 DE_DECLARE_COMMAND_LINE_OPT(StartServer, string);
62 DE_DECLARE_COMMAND_LINE_OPT(Host, string);
63 DE_DECLARE_COMMAND_LINE_OPT(Port, int);
64 DE_DECLARE_COMMAND_LINE_OPT(CaseListDir, string);
65 DE_DECLARE_COMMAND_LINE_OPT(TestSet, vector<string>);
66 DE_DECLARE_COMMAND_LINE_OPT(ExcludeSet, vector<string>);
67 DE_DECLARE_COMMAND_LINE_OPT(ContinueFile, string);
68 DE_DECLARE_COMMAND_LINE_OPT(TestLogFile, string);
69 DE_DECLARE_COMMAND_LINE_OPT(InfoLogFile, string);
70 DE_DECLARE_COMMAND_LINE_OPT(Summary, bool);
72 // TargetConfiguration
73 DE_DECLARE_COMMAND_LINE_OPT(BinaryName, string);
74 DE_DECLARE_COMMAND_LINE_OPT(WorkingDir, string);
75 DE_DECLARE_COMMAND_LINE_OPT(CmdLineArgs, string);
77 void parseCommaSeparatedList (const char* src, vector<string>* dst)
79 std::istringstream inStr (src);
82 while (std::getline(inStr, comp, ','))
86 void registerOptions (de::cmdline::Parser& parser)
88 using de::cmdline::Option;
89 using de::cmdline::NamedValue;
91 static const NamedValue<bool> s_yesNo[] =
97 parser << Option<StartServer> ("s", "start-server", "Start local execserver. Path to the execserver binary.")
98 << Option<Host> ("c", "connect", "Connect to host. Address of the execserver.")
99 << Option<Port> ("p", "port", "TCP port of the execserver.", "50016")
100 << Option<CaseListDir> ("cd", "caselistdir", "Path to the directory containing test case XML files.", ".")
101 << Option<TestSet> ("t", "testset", "Comma-separated list of include filters.", parseCommaSeparatedList)
102 << Option<ExcludeSet> ("e", "exclude", "Comma-separated list of exclude filters.", parseCommaSeparatedList, "")
103 << Option<ContinueFile> (DE_NULL, "continue", "Continue execution by initializing results from existing test log.")
104 << Option<TestLogFile> ("o", "out", "Output test log filename.", "TestLog.qpa")
105 << Option<InfoLogFile> ("i", "info", "Output info log filename.", "InfoLog.txt")
106 << Option<Summary> (DE_NULL, "summary", "Print summary after running tests.", s_yesNo, "yes")
107 << Option<BinaryName> ("b", "binaryname", "Test binary path. Relative to working directory.", "<Unused>")
108 << Option<WorkingDir> ("wd", "workdir", "Working directory for the test execution.", ".")
109 << Option<CmdLineArgs> (DE_NULL, "cmdline", "Additional command line arguments for the test binary.", "");
128 xe::TargetConfiguration targetCfg;
130 string serverBinOrAddress;
133 vector<string> testset;
134 vector<string> exclude;
141 bool parseCommandLine (CommandLine& cmdLine, int argc, const char* const* argv)
143 de::cmdline::Parser parser;
144 de::cmdline::CommandLine opts;
148 opt::registerOptions(parser);
150 if (!parser.parse(argc-1, argv+1, &opts, std::cerr))
152 std::cout << argv[0] << " [options]\n";
153 parser.help(std::cout);
157 if (opts.hasOption<opt::StartServer>() && opts.hasOption<opt::Host>())
159 std::cout << "Invalid command line arguments. Both --start-server and --connect defined." << std::endl;
162 else if (!opts.hasOption<opt::StartServer>() && !opts.hasOption<opt::Host>())
164 std::cout << "Invalid command line arguments. Must define either --start-server or --connect." << std::endl;
168 if (!opts.hasOption<opt::TestSet>())
170 std::cout << "Invalid command line arguments. --testset not defined." << std::endl;
174 if (opts.hasOption<opt::StartServer>())
176 cmdLine.runMode = RUNMODE_START_SERVER;
177 cmdLine.serverBinOrAddress = opts.getOption<opt::StartServer>();
181 cmdLine.runMode = RUNMODE_CONNECT;
182 cmdLine.serverBinOrAddress = opts.getOption<opt::Host>();
185 if (opts.hasOption<opt::ContinueFile>())
187 cmdLine.inFile = opts.getOption<opt::ContinueFile>();
189 if (cmdLine.inFile.empty())
191 std::cout << "Invalid command line arguments. --continue argument is empty." << std::endl;
196 cmdLine.port = opts.getOption<opt::Port>();
197 cmdLine.caseListDir = opts.getOption<opt::CaseListDir>();
198 cmdLine.testset = opts.getOption<opt::TestSet>();
199 cmdLine.exclude = opts.getOption<opt::ExcludeSet>();
200 cmdLine.outFile = opts.getOption<opt::TestLogFile>();
201 cmdLine.infoFile = opts.getOption<opt::InfoLogFile>();
202 cmdLine.summary = opts.getOption<opt::Summary>();
203 cmdLine.targetCfg.binaryName = opts.getOption<opt::BinaryName>();
204 cmdLine.targetCfg.workingDir = opts.getOption<opt::WorkingDir>();
205 cmdLine.targetCfg.cmdLineArgs = opts.getOption<opt::CmdLineArgs>();
210 bool checkCasePathPatternMatch (const char* pattern, const char* casePath, bool isTestGroup)
217 char c = casePath[casePos];
218 char p = pattern[ptrnPos];
222 /* Recurse to rest of positions. */
226 if (checkCasePathPatternMatch(pattern+ptrnPos+1, casePath+next, isTestGroup))
229 if (casePath[next] == 0)
230 return DE_FALSE; /* No match found. */
236 else if (c == 0 && p == 0)
240 /* Incomplete match is ok for test groups. */
254 void readCaseList (xe::TestGroup* root, const char* filename)
256 xe::TestCaseListParser caseListParser;
257 std::ifstream in (filename, std::ios_base::binary);
262 caseListParser.init(root);
266 in.read((char*)&buf[0], sizeof(buf));
267 int numRead = (int)in.gcount();
270 caseListParser.parse(&buf[0], numRead);
272 if (numRead < (int)sizeof(buf))
277 void readCaseLists (xe::TestRoot& root, const char* caseListDir)
279 int testCaseListCount = 0;
280 de::DirectoryIterator iter (caseListDir);
282 for (; iter.hasItem(); iter.next())
284 de::FilePath item = iter.getItem();
286 if (item.getType() == de::FilePath::TYPE_FILE)
288 string baseName = item.getBaseName();
289 if (baseName.find("-cases.xml") == baseName.length()-10)
291 string packageName = baseName.substr(0, baseName.length()-10);
292 xe::TestGroup* package = root.createGroup(packageName.c_str(), "");
294 readCaseList(package, item.getPath());
300 if (testCaseListCount == 0)
301 throw xe::Error("Couldn't find test case lists from test case list directory: '" + string(caseListDir) + "'");
304 void addMatchingCases (const xe::TestGroup& group, xe::TestSet& testSet, const char* filter)
306 for (int childNdx = 0; childNdx < group.getNumChildren(); childNdx++)
308 const xe::TestNode* child = group.getChild(childNdx);
309 const bool isGroup = child->getNodeType() == xe::TESTNODETYPE_GROUP;
310 const string fullPath = child->getFullPath();
312 if (checkCasePathPatternMatch(filter, fullPath.c_str(), isGroup))
316 // Recurse into group.
317 addMatchingCases(static_cast<const xe::TestGroup&>(*child), testSet, filter);
321 DE_ASSERT(child->getNodeType() == xe::TESTNODETYPE_TEST_CASE);
328 void removeMatchingCases (const xe::TestGroup& group, xe::TestSet& testSet, const char* filter)
330 for (int childNdx = 0; childNdx < group.getNumChildren(); childNdx++)
332 const xe::TestNode* child = group.getChild(childNdx);
333 const bool isGroup = child->getNodeType() == xe::TESTNODETYPE_GROUP;
334 const string fullPath = child->getFullPath();
336 if (checkCasePathPatternMatch(filter, fullPath.c_str(), isGroup))
340 // Recurse into group.
341 removeMatchingCases(static_cast<const xe::TestGroup&>(*child), testSet, filter);
345 DE_ASSERT(child->getNodeType() == xe::TESTNODETYPE_TEST_CASE);
346 testSet.remove(child);
352 class BatchResultHandler : public xe::TestLogHandler
355 BatchResultHandler (xe::BatchResult* batchResult)
356 : m_batchResult(batchResult)
360 void setSessionInfo (const xe::SessionInfo& sessionInfo)
362 m_batchResult->getSessionInfo() = sessionInfo;
365 xe::TestCaseResultPtr startTestCaseResult (const char* casePath)
367 // \todo [2012-11-01 pyry] What to do with duplicate results?
368 if (m_batchResult->hasTestCaseResult(casePath))
369 return m_batchResult->getTestCaseResult(casePath);
371 return m_batchResult->createTestCaseResult(casePath);
374 void testCaseResultUpdated (const xe::TestCaseResultPtr&)
378 void testCaseResultComplete (const xe::TestCaseResultPtr&)
383 xe::BatchResult* m_batchResult;
386 void readLogFile (xe::BatchResult* batchResult, const char* filename)
388 std::ifstream in (filename, std::ifstream::binary|std::ifstream::in);
389 BatchResultHandler handler (batchResult);
390 xe::TestLogParser parser (&handler);
396 in.read((char*)&buf[0], DE_LENGTH_OF_ARRAY(buf));
397 numRead = (int)in.gcount();
402 parser.parse(&buf[0], numRead);
408 void printBatchResultSummary (const xe::TestNode* root, const xe::TestSet& testSet, const xe::BatchResult& batchResult)
410 int countByStatusCode[xe::TESTSTATUSCODE_LAST];
411 std::fill(&countByStatusCode[0], &countByStatusCode[0]+DE_LENGTH_OF_ARRAY(countByStatusCode), 0);
413 for (xe::ConstTestNodeIterator iter = xe::ConstTestNodeIterator::begin(root); iter != xe::ConstTestNodeIterator::end(root); ++iter)
415 const xe::TestNode* node = *iter;
416 if (node->getNodeType() == xe::TESTNODETYPE_TEST_CASE && testSet.hasNode(node))
418 const xe::TestCase* testCase = static_cast<const xe::TestCase*>(node);
420 xe::TestStatusCode statusCode = xe::TESTSTATUSCODE_PENDING;
421 testCase->getFullPath(fullPath);
423 // Parse result data if such exists.
424 if (batchResult.hasTestCaseResult(fullPath.c_str()))
426 xe::ConstTestCaseResultPtr resultData = batchResult.getTestCaseResult(fullPath.c_str());
427 xe::TestCaseResult result;
428 xe::TestResultParser parser;
430 xe::parseTestCaseResultFromData(&parser, &result, *resultData.get());
431 statusCode = result.statusCode;
434 countByStatusCode[statusCode] += 1;
438 printf("\nTest run summary:\n");
440 for (int code = 0; code < xe::TESTSTATUSCODE_LAST; code++)
442 if (countByStatusCode[code] > 0)
443 printf(" %20s: %5d\n", xe::getTestStatusCodeName((xe::TestStatusCode)code), countByStatusCode[code]);
445 totalCases += countByStatusCode[code];
447 printf(" %20s: %5d\n", "Total", totalCases);
450 void writeInfoLog (const xe::InfoLog& log, const char* filename)
452 std::ofstream out(filename, std::ios_base::binary);
453 XE_CHECK(out.good());
454 out.write((const char*)log.getBytes(), log.getSize());
458 xe::CommLink* createCommLink (const CommandLine& cmdLine)
460 if (cmdLine.runMode == RUNMODE_START_SERVER)
462 xe::LocalTcpIpLink* link = new xe::LocalTcpIpLink();
465 link->start(cmdLine.serverBinOrAddress.c_str(), DE_NULL, cmdLine.port);
474 else if (cmdLine.runMode == RUNMODE_CONNECT)
476 de::SocketAddress address;
478 address.setFamily(DE_SOCKETFAMILY_INET4);
479 address.setProtocol(DE_SOCKETPROTOCOL_TCP);
480 address.setHost(cmdLine.serverBinOrAddress.c_str());
481 address.setPort(cmdLine.port);
483 xe::TcpIpLink* link = new xe::TcpIpLink();
488 link->connect(address);
491 catch (const std::exception& error)
494 throw xe::Error("Failed to connect to ExecServer at: " + cmdLine.serverBinOrAddress + ":" + de::toString(cmdLine.port) + ", " + error.what());
509 #if (DE_OS == DE_OS_UNIX) || (DE_OS == DE_OS_ANDROID)
511 static xe::BatchExecutor* s_executor = DE_NULL;
513 void signalHandler (int, siginfo_t*, void*)
516 s_executor->cancel();
519 void setupSignalHandler (xe::BatchExecutor* executor)
521 s_executor = executor;
524 sa.sa_sigaction = signalHandler;
525 sa.sa_flags = SA_SIGINFO | SA_RESTART;
526 sigfillset(&sa.sa_mask);
528 sigaction(SIGINT, &sa, DE_NULL);
531 void resetSignalHandler (void)
535 sa.sa_handler = SIG_DFL;
536 sa.sa_flags = SA_RESTART;
537 sigfillset(&sa.sa_mask);
539 sigaction(SIGINT, &sa, DE_NULL);
540 s_executor = DE_NULL;
543 #elif (DE_OS == DE_OS_WIN32)
545 static xe::BatchExecutor* s_executor = DE_NULL;
547 void signalHandler (int)
550 s_executor->cancel();
553 void setupSignalHandler (xe::BatchExecutor* executor)
555 s_executor = executor;
556 signal(SIGINT, signalHandler);
559 void resetSignalHandler (void)
561 signal(SIGINT, SIG_DFL);
562 s_executor = DE_NULL;
567 void setupSignalHandler (xe::BatchExecutor*)
571 void resetSignalHandler (void)
577 void runExecutor (const CommandLine& cmdLine)
581 // Read case list definitions.
582 readCaseLists(root, cmdLine.caseListDir.c_str());
588 for (vector<string>::const_iterator filterIter = cmdLine.testset.begin(); filterIter != cmdLine.testset.end(); ++filterIter)
589 addMatchingCases(root, testSet, filterIter->c_str());
592 throw xe::Error("None of the test case lists contains tests matching any of the test sets.");
594 // Remove excluded cases.
595 for (vector<string>::const_iterator filterIter = cmdLine.exclude.begin(); filterIter != cmdLine.exclude.end(); ++filterIter)
596 removeMatchingCases(root, testSet, filterIter->c_str());
598 // Initialize batch result.
599 xe::BatchResult batchResult;
602 // Read existing results from input file (if supplied).
603 if (!cmdLine.inFile.empty())
604 readLogFile(&batchResult, cmdLine.inFile.c_str());
606 // Initialize commLink.
607 std::auto_ptr<xe::CommLink> commLink(createCommLink(cmdLine));
609 xe::BatchExecutor executor(cmdLine.targetCfg, commLink.get(), &root, testSet, &batchResult, &infoLog);
613 setupSignalHandler(&executor);
615 resetSignalHandler();
619 resetSignalHandler();
621 if (!cmdLine.outFile.empty())
623 xe::writeBatchResultToFile(batchResult, cmdLine.outFile.c_str());
624 printf("Test log written to %s\n", cmdLine.outFile.c_str());
627 if (!cmdLine.infoFile.empty())
629 writeInfoLog(infoLog, cmdLine.infoFile.c_str());
630 printf("Info log written to %s\n", cmdLine.infoFile.c_str());
634 printBatchResultSummary(&root, testSet, batchResult);
639 if (!cmdLine.outFile.empty())
641 xe::writeBatchResultToFile(batchResult, cmdLine.outFile.c_str());
642 printf("Test log written to %s\n", cmdLine.outFile.c_str());
645 if (!cmdLine.infoFile.empty())
647 writeInfoLog(infoLog, cmdLine.infoFile.c_str());
648 printf("Info log written to %s\n", cmdLine.infoFile.c_str());
652 printBatchResultSummary(&root, testSet, batchResult);
657 if (commLink->getState(err) == xe::COMMLINKSTATE_ERROR)
658 throw xe::Error(err);
664 int main (int argc, const char* const* argv)
668 if (!parseCommandLine(cmdLine, argc, argv))
673 runExecutor(cmdLine);
675 catch (const std::exception& e)
677 printf("%s\n", e.what());