2 * Copyright (c) 2014-2015 Samsung Electronics Co., Ltd All Rights Reserved
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 * @file test_runner.cpp
18 * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
19 * @author Lukasz Wrzosek (l.wrzosek@samsung.com)
21 * @brief This file is the implementation file of test runner
24 #include <dpl/test/test_failed.h>
25 #include <dpl/test/test_ignored.h>
26 #include <dpl/test/test_runner.h>
27 #include <dpl/test/test_results_collector.h>
28 #include <dpl/exception.h>
29 #include <dpl/scoped_free.h>
30 #include <dpl/log/log.h>
31 #include <dpl/colors.h>
40 #include <libxml/xpath.h>
41 #include <libxml/xpathInternals.h>
42 #include <libxml/parser.h>
43 #include <libxml/tree.h>
45 #include <dpl/singleton_impl.h>
46 IMPLEMENT_SINGLETON(DPL::Test::TestRunner)
50 std::string getXMLNode(xmlNodePtr node)
53 xmlChar * value = xmlNodeGetContent(node);
54 ret = std::string(reinterpret_cast<char*>(value));
64 TestResult::FailStatus TryCatch(const std::function<void(void)> &func, std::string &reason) {
67 } catch (const DPL::Test::TestFailed &e) {
68 reason = e.GetMessage();
69 return TestResult::FailStatus::FAILED;
70 } catch (const DPL::Test::TestIgnored &e) {
71 reason = e.GetMessage();
72 return TestResult::FailStatus::IGNORED;
73 } catch (const std::exception &e) {
75 return TestResult::FailStatus::FAILED;
77 reason = "Unknown exception";
78 return TestResult::FailStatus::FAILED;
80 reason = std::string();
81 return TestResult::FailStatus::NONE;
84 void TestRunner::RegisterTest(TestCasePtr testCase)
86 m_testGroups[m_currentGroup].push_back(testCase);
87 m_testCaseSet.insert(testCase);
90 void TestRunner::InitGroup(const char* name)
92 m_currentGroup = name;
95 void TestRunner::normalizeXMLTag(std::string& str, const std::string& testcase)
97 //Add testcase if missing
98 std::string::size_type pos = str.find(testcase);
101 str = testcase + "_" + str;
104 //dpl test runner cannot have '-' character in name so it have to be replaced
105 // for TCT case to make comparision works
106 std::replace(str.begin(), str.end(), '-', '_');
109 bool TestRunner::filterGroupsByXmls(const std::vector<std::string> & files)
111 DECLARE_EXCEPTION_TYPE(DPL::Exception, XMLError)
113 const std::string idPath = "/test_definition/suite/set/testcase/@id";
116 std::map<std::string, bool> casesMap;
118 std::string testsuite;
119 if(!m_testGroups.empty())
121 for(TestCaseGroupMap::const_iterator cit = m_testGroups.begin(); cit != m_testGroups.end(); ++cit)
123 if(!cit->second.empty())
125 for(TestCaseList::const_iterator cj = cit->second.begin(); cj != cit->second.end(); ++cj)
127 std::string name = (*cj)->GetName();
128 std::string::size_type st = name.find('_');
129 if(st != std::string::npos)
131 name = name.substr(0, st);
136 if(!testsuite.empty()) break;
147 for (const std::string &file : files)
150 xmlXPathContextPtr xpathCtx;
152 doc = xmlReadFile(file.c_str(), nullptr, 0);
153 if (doc == nullptr) {
154 ThrowMsg(XMLError, "File Problem");
157 xpathCtx = xmlXPathNewContext(doc);
158 if (xpathCtx == nullptr) {
160 "Error: unable to create new XPath context\n");
162 xpathCtx->node = xmlDocGetRootElement(doc);
166 xmlXPathObjectPtr xpathObject;
167 //get requested node's values
168 xpathObject = xmlXPathEvalExpression(BAD_CAST idPath.c_str(), xpathCtx);
169 if (xpathObject == nullptr)
171 ThrowMsg(XMLError, "XPath evaluation failure: " << idPath);
173 xmlNodeSetPtr nodes = xpathObject->nodesetval;
174 unsigned size = (nodes) ? nodes->nodeNr : 0;
175 LogDebug("Found " << size << " nodes matching xpath");
176 for(unsigned i = 0; i < size; ++i)
178 LogPedantic("Type: " << nodes->nodeTab[i]->type);
179 if (nodes->nodeTab[i]->type == XML_ATTRIBUTE_NODE) {
180 xmlNodePtr curNode = nodes->nodeTab[i];
181 result = getXMLNode(curNode);
182 LogPedantic("Result: " << result);
183 normalizeXMLTag(result, testsuite);
184 casesMap.insert(make_pair(result, false));
187 //Cleanup of XPath data
188 xmlXPathFreeObject(xpathObject);
189 xmlXPathFreeContext(xpathCtx);
195 LogError("Libxml error: " << _rethrown_exception.DumpToString());
200 if(!filterByXML(casesMap))
208 bool TestRunner::filterByXML(std::map<std::string, bool> & casesMap)
210 for (auto &group : m_testGroups) {
211 TestCaseList newList;
212 for (auto &tc : group.second)
214 if (casesMap.find(tc->GetName()) != casesMap.end()) {
215 casesMap[tc->GetName()] = true;
216 newList.push_back(tc);
219 group.second = newList;
221 for (auto &cs : casesMap)
223 if(cs.second == false)
225 LogError("Cannot find testcase from XML file: " << cs.first);
232 void TestRunner::RunTestCase(TestCasePtr testCase)
234 setCurrentTestCase(testCase);
235 m_deferDeepness = 0U;
237 std::string initReason;
238 TestResult::FailStatus initStatus = TryCatch(std::bind(&TestCase::Init, testCase),
240 if (initStatus != TestResult::FailStatus::NONE) {
241 CollectResult(testCase->GetName(),
242 TestResult(initStatus, getConcatedFailReason(initReason), testCase->GetPerformance()));
243 setCurrentTestCase(nullptr);
247 std::string testReason;
248 TestResult::FailStatus testStatus = TryCatch(std::bind(&TestCase::Test, testCase),
250 testReason = getConcatedFailReason(testReason);
251 std::string finishReason;
252 TestResult::FailStatus finishStatus = TryCatch(std::bind(&TestCase::Finish, testCase),
254 finishReason = getConcatedFailReason(finishReason);
256 switch (finishStatus) {
257 case TestResult::FailStatus::FAILED:
258 testStatus = TestResult::FailStatus::FAILED;
259 if (!testReason.empty())
261 testReason += finishReason;
263 case TestResult::FailStatus::IGNORED:
264 if (testStatus == TestResult::FailStatus::NONE)
265 testStatus = TestResult::FailStatus::IGNORED;
266 if (!testReason.empty())
268 testReason += finishReason;
269 case TestResult::FailStatus::NONE:
272 Assert(false && "Unhandled fail status");
275 CollectResult(testCase->GetName(),
276 TestResult(testStatus, testReason, testCase->GetPerformance()));
277 setCurrentTestCase(nullptr);
280 void TestRunner::RunTests()
282 using namespace DPL::Colors::Text;
285 for (auto &collector : m_collectors) {
286 collector.second->Start();
290 for (auto &group : m_testGroups) {
291 count += group.second.size();
293 fprintf(stderr, "%sFound %d testcases...%s\n", GREEN_BEGIN, count, GREEN_END);
294 fprintf(stderr, "%s%s%s\n", GREEN_BEGIN, "Running tests...", GREEN_END);
295 for (auto &group : m_testGroups) {
296 TestCaseList list = group.second;
298 for (auto &collector : m_collectors) {
299 collector.second->CollectCurrentTestGroupName(group.first);
301 list.sort([](const TestCasePtr &a, const TestCasePtr &b) { return (*a < *b); });
303 for (TestCaseList::const_iterator iterator = list.begin();
304 iterator != list.end();
307 TestCasePtr test = *iterator;
308 if (m_startTestId == test->GetName()) {
312 if (m_startTestId.empty()) {
315 if (m_terminate == true) {
316 // Terminate quietly without any logs
323 std::for_each(m_collectors.begin(),
325 [] (const TestResultsCollectors::value_type & collector)
327 collector.second->Finish();
331 fprintf(stderr, "%s%s%s\n\n", GREEN_BEGIN, "Finished", GREEN_END);
334 TestCasePtr TestRunner::getCurrentTestCase()
336 return m_currentTestCase;
339 void TestRunner::setCurrentTestCase(TestCasePtr testCase)
341 m_currentTestCase = testCase;
344 void TestRunner::beginPerformance(std::chrono::system_clock::duration maxDurationInMicroseconds)
346 TestCasePtr testCase = getCurrentTestCase();
350 if (!testCase->GetPerformance())
351 testCase->SetPerformance(
352 std::unique_ptr<PerformanceResult> \
353 (new PerformanceResult(maxDurationInMicroseconds)));
356 void TestRunner::endPerformance()
358 TestCasePtr testCase = getCurrentTestCase();
362 testCase->GetPerformance()->Finish();
365 ConstPerformanceResultPtr TestRunner::getCurrentTestCasePerformanceResult()
367 TestCasePtr testCase = getCurrentTestCase();
371 return testCase->GetPerformance();
374 void TestRunner::setCurrentTestCasePerformanceResult(const PerformanceResultPtr &performance)
376 TestCasePtr testCase = getCurrentTestCase();
380 testCase->SetPerformance(performance);
383 void TestRunner::addFailReason(const std::string &reason)
385 m_failReason.push(reason);
388 std::string TestRunner::getConcatedFailReason(const std::string &reason)
391 while (!m_failReason.empty())
393 ret += m_failReason.front();
399 TestRunner::~TestRunner()
401 for(auto &t : m_testCaseSet)
405 void TestRunner::CollectResult(const std::string& id, const TestResult& result)
407 if (result.GetFailStatus() == TestResult::FailStatus::IGNORED && m_runIgnored)
410 std::for_each(m_collectors.begin(),
412 [&](const TestResultsCollectors::value_type & collector)
414 collector.second->CollectResult(id, result);
418 void TestRunner::Banner()
420 using namespace DPL::Colors::Text;
434 void TestRunner::InvalidArgs(const std::string& message)
436 using namespace DPL::Colors::Text;
444 void TestRunner::Usage()
446 fprintf(stderr, "Usage: runner [options]\n\n");
447 fprintf(stderr, "Output type:\n");
448 fprintf(stderr, " --output=<output type> --output=<output type> ...\n");
449 fprintf(stderr, "\n possible output types:\n");
450 for (std::string &type : TestResultsCollectorBase::GetCollectorsNames()) {
451 fprintf(stderr, " --output=%s\n", type.c_str());
453 fprintf(stderr, "\n example:\n");
455 " test-binary --output=text --output=xml --file=output.xml\n\n");
456 fprintf(stderr, "Other parameters:\n");
457 fprintf(stderr, " --test=<test name> Run only one test\n");
459 " --regexp='regexp'\t Only selected tests"
460 " which names match regexp run\n\n");
461 fprintf(stderr, " --start=<test id>\tStart from concrete test id\n");
462 fprintf(stderr, " --group=<group name>\t Run tests only from one group\n");
463 fprintf(stderr, " --runignored\t Run also ignored tests\n");
464 fprintf(stderr, " --list\t Show a list of Test IDs\n");
465 fprintf(stderr, " --listgroups\t Show a list of Test Group names \n");
466 fprintf(stderr, " --only-from-xml=<xml file>\t Run only testcases specified in XML file \n"
467 " XML name is taken from attribute id=\"part1_part2\" as whole.\n"
468 " If part1 is not found (no _) then it is implicitily "
469 "set according to suite part1 from binary tests\n");
472 " --listingroup=<group name>\t Show a list of Test IDS in one group\n");
473 fprintf(stderr, " --allowchildlogs\t Allow to print logs from child process on screen.\n");
474 fprintf(stderr, " When active child process will be able to print logs on stdout and stderr.\n");
475 fprintf(stderr, " Both descriptors will be closed after test.\n");
476 fprintf(stderr, " --help\t This help\n\n");
477 std::for_each(m_collectors.begin(),
479 [] (const TestResultsCollectors::value_type & collector)
482 "Output %s has specific args:\n",
483 collector.first.c_str());
487 CollectorSpecificHelp().c_str());
489 fprintf(stderr, "For bug reporting, please write to:\n");
490 fprintf(stderr, "<p.dobrowolsk@samsung.com>\n");
493 int TestRunner::ExecTestRunner(int argc, char *argv[])
495 std::vector<std::string> args;
496 for (int i = 0; i < argc; ++i) {
497 args.push_back(argv[i]);
499 return ExecTestRunner(args);
502 int TestRunner::ExecTestRunner(ArgsList args)
504 m_runIgnored = false;
505 // Parse command line
507 args.erase(args.begin());
509 bool showHelp = false;
510 bool justList = false;
511 std::vector<std::string> xmlFiles;
513 TestResultsCollectorBasePtr currentCollector;
515 // Parse each argument
516 for(std::string &arg : args)
518 const std::string test = "--test=";
519 const std::string regexp = "--regexp=";
520 const std::string output = "--output=";
521 const std::string groupId = "--group=";
522 const std::string runIgnored = "--runignored";
523 const std::string listCmd = "--list";
524 const std::string startCmd = "--start=";
525 const std::string listGroupsCmd = "--listgroups";
526 const std::string listInGroup = "--listingroup=";
527 const std::string allowChildLogs = "--allowchildlogs";
528 const std::string onlyFromXML = "--only-from-xml=";
530 if (currentCollector) {
531 if (currentCollector->ParseCollectorSpecificArg(arg)) {
536 if (arg.find(startCmd) == 0) {
537 arg.erase(0, startCmd.length());
538 for (auto &group : m_testGroups) {
539 for (auto &tc : group.second) {
540 if (tc->GetName() == arg) {
545 if (!m_startTestId.empty()) {
549 if (!m_startTestId.empty()) {
553 fprintf(stderr, "Start test id has not been found\n");
556 } else if (arg.find(groupId) == 0) {
557 arg.erase(0, groupId.length());
558 TestCaseGroupMap::iterator found = m_testGroups.find(arg);
559 if (found != m_testGroups.end()) {
560 std::string name = found->first;
561 TestCaseList newList = found->second;
562 m_testGroups.clear();
563 m_testGroups[name] = newList;
565 fprintf(stderr, "Group %s not found\n", arg.c_str());
570 } else if (arg == runIgnored) {
572 } else if (arg == listCmd) {
574 } else if (arg == listGroupsCmd) {
575 for (auto &group : m_testGroups) {
576 printf("GR:%s\n", group.first.c_str());
579 } else if (arg.find(listInGroup) == 0) {
580 arg.erase(0, listInGroup.length());
581 for (auto &test : m_testGroups[arg]) {
582 printf("ID:%s\n", test->GetName().c_str());
585 } else if (arg.find(allowChildLogs) == 0) {
586 arg.erase(0, allowChildLogs.length());
587 m_allowChildLogs = true;
588 } else if (arg == "--help") {
590 } else if (arg.find(output) == 0) {
591 arg.erase(0, output.length());
592 if (m_collectors.find(arg) != m_collectors.end()) {
594 "Multiple outputs of the same type are not supported!");
598 currentCollector.reset(TestResultsCollectorBase::Create(arg));
599 if (!currentCollector) {
600 InvalidArgs("Unsupported output type!");
604 m_collectors[arg] = currentCollector;
605 } else if (arg.find(regexp) == 0) {
606 arg.erase(0, regexp.length());
607 if (arg.length() == 0) {
613 if (arg[0] == '\'' && arg[arg.length() - 1] == '\'') {
615 arg.erase(arg.length() - 1);
618 if (arg.length() == 0) {
624 pcrecpp::RE re(arg.c_str());
625 for (auto &group : m_testGroups) {
626 TestCaseList newList;
627 for (auto &tc : group.second)
629 if (re.PartialMatch(tc->GetName())) {
630 newList.push_back(tc);
633 group.second = newList;
635 } else if (arg.find(test) == 0) {
636 arg.erase(0, test.length());
637 if (arg.length() == 0) {
643 if (arg[0] == '\'' && arg[arg.length() - 1] == '\'') {
645 arg.erase(arg.length() - 1);
648 if (arg.length() == 0) {
654 pcrecpp::RE re(arg.c_str());
655 for (auto &group : m_testGroups) {
656 TestCaseList newList;
657 for (auto &tc : group.second)
659 if (re.FullMatch(tc->GetName())) {
660 newList.push_back(tc);
663 group.second = newList;
665 } else if(arg.find(onlyFromXML) == 0) {
666 arg.erase(0, onlyFromXML.length());
667 if (arg.length() == 0) {
673 if (arg[0] == '\'' && arg[arg.length() - 1] == '\'') {
675 arg.erase(arg.length() - 1);
678 if (arg.length() == 0) {
684 xmlFiles.push_back(arg);
692 if(!xmlFiles.empty())
694 if(!filterGroupsByXmls(xmlFiles))
696 fprintf(stderr, "XML file is not correct\n");
703 for (auto &group : m_testGroups) {
704 for (auto &tc : group.second) {
705 printf("ID:%s:%s\n", group.first.c_str(), tc->GetName().c_str());
711 currentCollector.reset();
719 if (m_collectors.empty()) {
720 TestResultsCollectorBasePtr collector(
721 TestResultsCollectorBase::Create("text"));
722 m_collectors["text"] = collector;
725 for (auto &collector : m_collectors) {
726 if (!collector.second->Configure()) {
727 fprintf(stderr, "Could not configure selected output");
738 void TestRunner::Terminate()
743 bool TestRunner::GetAllowChildLogs()
745 return m_allowChildLogs;
748 void TestRunner::deferFailedException(const DPL::Test::TestFailed &ex)
750 if (m_deferDeepness <= 0)
753 if (m_deferredExceptionsMessages.empty()) {
754 m_firstDeferredFail = ex;
755 m_firstDeferredExceptionType = DeferredExceptionType::DEFERRED_FAILED;
757 m_deferredExceptionsMessages.push_back(ex.GetMessage());
760 void TestRunner::deferIgnoredException(const DPL::Test::TestIgnored &ex)
762 if (m_deferDeepness <= 0)
765 if (m_deferredExceptionsMessages.empty()) {
766 m_firstDeferredIgnore = ex;
767 m_firstDeferredExceptionType = DeferredExceptionType::DEFERRED_IGNORED;
769 m_deferredExceptionsMessages.push_back(ex.GetMessage());
772 void TestRunner::deferBegin()
777 void TestRunner::deferEnd()
779 if (m_deferDeepness > 0)
782 if (m_deferDeepness > 0)
785 for (size_t i = 0; i < m_deferredExceptionsMessages.size(); ++i) {
786 addFailReason(m_deferredExceptionsMessages[i]);
789 if (!m_deferredExceptionsMessages.empty())
791 m_deferredExceptionsMessages.clear();
792 switch (m_firstDeferredExceptionType) {
793 case DeferredExceptionType::DEFERRED_FAILED:
794 throw m_firstDeferredFail;
795 case DeferredExceptionType::DEFERRED_IGNORED:
796 throw m_firstDeferredIgnore;
799 m_deferredExceptionsMessages.clear();