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>
37 #include <libxml/xpath.h>
38 #include <libxml/xpathInternals.h>
39 #include <libxml/parser.h>
40 #include <libxml/tree.h>
42 #include <dpl/singleton_impl.h>
43 IMPLEMENT_SINGLETON(DPL::Test::TestRunner)
47 std::string getXMLNode(xmlNodePtr node)
50 xmlChar * value = xmlNodeGetContent(node);
51 ret = std::string(reinterpret_cast<char*>(value));
62 void TestRunner::RegisterTest(const char *testName, TestCase proc)
64 m_testGroups[m_currentGroup].push_back(TestCaseStruct(testName, proc));
67 void TestRunner::InitGroup(const char* name)
69 m_currentGroup = name;
72 void TestRunner::normalizeXMLTag(std::string& str, const std::string& testcase)
74 //Add testcase if missing
75 std::string::size_type pos = str.find(testcase);
78 str = testcase + "_" + str;
81 //dpl test runner cannot have '-' character in name so it have to be replaced
82 // for TCT case to make comparision works
83 std::replace(str.begin(), str.end(), '-', '_');
86 bool TestRunner::filterGroupsByXmls(const std::vector<std::string> & files)
88 DECLARE_EXCEPTION_TYPE(DPL::Exception, XMLError)
90 const std::string idPath = "/test_definition/suite/set/testcase/@id";
93 std::map<std::string, bool> casesMap;
95 std::string testsuite;
96 if(!m_testGroups.empty())
98 for(TestCaseGroupMap::const_iterator cit = m_testGroups.begin(); cit != m_testGroups.end(); ++cit)
100 if(!cit->second.empty())
102 for(TestCaseStructList::const_iterator cj = cit->second.begin(); cj != cit->second.end(); ++cj)
104 std::string name = cj->name;
105 std::string::size_type st = name.find('_');
106 if(st != std::string::npos)
108 name = name.substr(0, st);
113 if(!testsuite.empty()) break;
124 for (const std::string &file : files)
127 xmlXPathContextPtr xpathCtx;
129 doc = xmlReadFile(file.c_str(), nullptr, 0);
130 if (doc == nullptr) {
131 ThrowMsg(XMLError, "File Problem");
134 xpathCtx = xmlXPathNewContext(doc);
135 if (xpathCtx == nullptr) {
137 "Error: unable to create new XPath context\n");
139 xpathCtx->node = xmlDocGetRootElement(doc);
143 xmlXPathObjectPtr xpathObject;
144 //get requested node's values
145 xpathObject = xmlXPathEvalExpression(BAD_CAST idPath.c_str(), xpathCtx);
146 if (xpathObject == nullptr)
148 ThrowMsg(XMLError, "XPath evaluation failure: " << idPath);
150 xmlNodeSetPtr nodes = xpathObject->nodesetval;
151 unsigned size = (nodes) ? nodes->nodeNr : 0;
152 LogDebug("Found " << size << " nodes matching xpath");
153 for(unsigned i = 0; i < size; ++i)
155 LogPedantic("Type: " << nodes->nodeTab[i]->type);
156 if (nodes->nodeTab[i]->type == XML_ATTRIBUTE_NODE) {
157 xmlNodePtr curNode = nodes->nodeTab[i];
158 result = getXMLNode(curNode);
159 LogPedantic("Result: " << result);
160 normalizeXMLTag(result, testsuite);
161 casesMap.insert(make_pair(result, false));
164 //Cleanup of XPath data
165 xmlXPathFreeObject(xpathObject);
166 xmlXPathFreeContext(xpathCtx);
172 LogError("Libxml error: " << _rethrown_exception.DumpToString());
177 if(!filterByXML(casesMap))
185 bool TestRunner::filterByXML(std::map<std::string, bool> & casesMap)
187 for (auto &group : m_testGroups) {
188 TestCaseStructList newList;
189 for (auto &tc : group.second)
191 if (casesMap.find(tc.name) != casesMap.end()) {
192 casesMap[tc.name] = true;
193 newList.push_back(tc);
196 group.second = newList;
198 for (auto &cs : casesMap)
200 if(cs.second == false)
202 LogError("Cannot find testcase from XML file: " << cs.first);
209 void TestRunner::RunTestCase(const TestCaseStruct& testCase)
211 setCurrentTestCase(&(const_cast<TestCaseStruct &>(testCase)));
212 m_deferDeepness = 0U;
215 } catch (const TestFailed &e) {
216 // Simple test failure
217 CollectResult(testCase.name,
218 TestResult(TestResult::FailStatus::FAILED,
219 getConcatedFailReason(e.GetMessage())));
221 setCurrentTestCase(nullptr);
223 } catch (const TestIgnored &e) {
225 // Simple test have to be implemented
226 CollectResult(testCase.name,
227 TestResult(TestResult::FailStatus::IGNORED, e.GetMessage()));
230 setCurrentTestCase(nullptr);
232 } catch (const std::exception &) {
233 // std exception failure
234 CollectResult(testCase.name,
235 TestResult(TestResult::FailStatus::FAILED, "std exception"));
237 setCurrentTestCase(nullptr);
240 // Unknown exception failure
241 CollectResult(testCase.name,
242 TestResult(TestResult::FailStatus::FAILED, "unknown exception"));
243 setCurrentTestCase(nullptr);
248 CollectResult(testCase.name,
249 TestResult(TestResult::FailStatus::NONE,
251 testCase.performance));
252 setCurrentTestCase(nullptr);
255 void TestRunner::RunTests()
257 using namespace DPL::Colors::Text;
260 for (auto &collector : m_collectors) {
261 collector.second->Start();
265 for (auto &group : m_testGroups) {
266 count += group.second.size();
268 fprintf(stderr, "%sFound %d testcases...%s\n", GREEN_BEGIN, count, GREEN_END);
269 fprintf(stderr, "%s%s%s\n", GREEN_BEGIN, "Running tests...", GREEN_END);
270 for (auto &group : m_testGroups) {
271 TestCaseStructList list = group.second;
273 for (auto &collector : m_collectors) {
274 collector.second->CollectCurrentTestGroupName(group.first);
278 for (TestCaseStructList::const_iterator iterator = list.begin();
279 iterator != list.end();
282 TestCaseStruct test = *iterator;
283 if (m_startTestId == test.name) {
287 if (m_startTestId.empty()) {
290 if (m_terminate == true) {
291 // Terminate quietly without any logs
298 std::for_each(m_collectors.begin(),
300 [] (const TestResultsCollectors::value_type & collector)
302 collector.second->Finish();
306 fprintf(stderr, "%s%s%s\n\n", GREEN_BEGIN, "Finished", GREEN_END);
309 TestRunner::TestCaseStruct *TestRunner::getCurrentTestCase()
311 return m_currentTestCase;
314 void TestRunner::setCurrentTestCase(TestCaseStruct* testCase)
316 m_currentTestCase = testCase;
319 void TestRunner::beginPerformance(std::chrono::system_clock::duration maxDurationInMicroseconds)
321 TestCaseStruct* testCase = getCurrentTestCase();
325 if (!testCase->performance)
326 testCase->performance.reset(new PerformanceResult(maxDurationInMicroseconds));
329 void TestRunner::endPerformance()
331 TestCaseStruct* testCase = getCurrentTestCase();
335 testCase->performance->Finish();
338 ConstPerformanceResultPtr TestRunner::getCurrentTestCasePerformanceResult()
340 TestCaseStruct* testCase = getCurrentTestCase();
344 return testCase->performance;
347 void TestRunner::setCurrentTestCasePerformanceResult(const PerformanceResultPtr &performance)
349 TestCaseStruct* testCase = getCurrentTestCase();
353 testCase->performance = performance;
356 void TestRunner::addFailReason(const std::string &reason)
358 m_failReason.push(reason);
361 std::string TestRunner::getConcatedFailReason(const std::string &reason)
364 while (!m_failReason.empty())
366 ret += m_failReason.front();
372 void TestRunner::CollectResult(const std::string& id, const TestResult& result)
374 std::for_each(m_collectors.begin(),
376 [&](const TestResultsCollectors::value_type & collector)
378 collector.second->CollectResult(id, result);
382 void TestRunner::Banner()
384 using namespace DPL::Colors::Text;
398 void TestRunner::InvalidArgs(const std::string& message)
400 using namespace DPL::Colors::Text;
408 void TestRunner::Usage()
410 fprintf(stderr, "Usage: runner [options]\n\n");
411 fprintf(stderr, "Output type:\n");
412 fprintf(stderr, " --output=<output type> --output=<output type> ...\n");
413 fprintf(stderr, "\n possible output types:\n");
414 for (std::string &type : TestResultsCollectorBase::GetCollectorsNames()) {
415 fprintf(stderr, " --output=%s\n", type.c_str());
417 fprintf(stderr, "\n example:\n");
419 " test-binary --output=text --output=xml --file=output.xml\n\n");
420 fprintf(stderr, "Other parameters:\n");
422 " --regexp='regexp'\t Only selected tests"
423 " which names match regexp run\n\n");
424 fprintf(stderr, " --start=<test id>\tStart from concrete test id");
425 fprintf(stderr, " --group=<group name>\t Run tests only from one group\n");
426 fprintf(stderr, " --runignored\t Run also ignored tests\n");
427 fprintf(stderr, " --list\t Show a list of Test IDs\n");
428 fprintf(stderr, " --listgroups\t Show a list of Test Group names \n");
429 fprintf(stderr, " --only-from-xml=<xml file>\t Run only testcases specified in XML file \n"
430 " XML name is taken from attribute id=\"part1_part2\" as whole.\n"
431 " If part1 is not found (no _) then it is implicitily "
432 "set according to suite part1 from binary tests\n");
435 " --listingroup=<group name>\t Show a list of Test IDS in one group\n");
436 fprintf(stderr, " --allowchildlogs\t Allow to print logs from child process on screen.\n");
437 fprintf(stderr, " When active child process will be able to print logs on stdout and stderr.\n");
438 fprintf(stderr, " Both descriptors will be closed after test.\n");
439 fprintf(stderr, " --help\t This help\n\n");
440 std::for_each(m_collectors.begin(),
442 [] (const TestResultsCollectors::value_type & collector)
445 "Output %s has specific args:\n",
446 collector.first.c_str());
450 CollectorSpecificHelp().c_str());
452 fprintf(stderr, "For bug reporting, please write to:\n");
453 fprintf(stderr, "<p.dobrowolsk@samsung.com>\n");
456 int TestRunner::ExecTestRunner(int argc, char *argv[])
458 std::vector<std::string> args;
459 for (int i = 0; i < argc; ++i) {
460 args.push_back(argv[i]);
462 return ExecTestRunner(args);
465 void TestRunner::MarkAssertion()
470 int TestRunner::ExecTestRunner(ArgsList args)
472 m_runIgnored = false;
473 // Parse command line
475 args.erase(args.begin());
477 bool showHelp = false;
478 bool justList = false;
479 std::vector<std::string> xmlFiles;
481 TestResultsCollectorBasePtr currentCollector;
483 // Parse each argument
484 for(std::string &arg : args)
486 const std::string regexp = "--regexp=";
487 const std::string output = "--output=";
488 const std::string groupId = "--group=";
489 const std::string runIgnored = "--runignored";
490 const std::string listCmd = "--list";
491 const std::string startCmd = "--start=";
492 const std::string listGroupsCmd = "--listgroups";
493 const std::string listInGroup = "--listingroup=";
494 const std::string allowChildLogs = "--allowchildlogs";
495 const std::string onlyFromXML = "--only-from-xml=";
497 if (currentCollector) {
498 if (currentCollector->ParseCollectorSpecificArg(arg)) {
503 if (arg.find(startCmd) == 0) {
504 arg.erase(0, startCmd.length());
505 for (auto &group : m_testGroups) {
506 for (auto &tc : group.second) {
507 if (tc.name == arg) {
512 if (!m_startTestId.empty()) {
516 if (!m_startTestId.empty()) {
520 fprintf(stderr, "Start test id has not been found\n");
523 } else if (arg.find(groupId) == 0) {
524 arg.erase(0, groupId.length());
525 TestCaseGroupMap::iterator found = m_testGroups.find(arg);
526 if (found != m_testGroups.end()) {
527 std::string name = found->first;
528 TestCaseStructList newList = found->second;
529 m_testGroups.clear();
530 m_testGroups[name] = newList;
532 fprintf(stderr, "Group %s not found\n", arg.c_str());
537 } else if (arg == runIgnored) {
539 } else if (arg == listCmd) {
541 } else if (arg == listGroupsCmd) {
542 for (auto &group : m_testGroups) {
543 printf("GR:%s\n", group.first.c_str());
546 } else if (arg.find(listInGroup) == 0) {
547 arg.erase(0, listInGroup.length());
548 for (auto &test : m_testGroups[arg]) {
549 printf("ID:%s\n", test.name.c_str());
552 } else if (arg.find(allowChildLogs) == 0) {
553 arg.erase(0, allowChildLogs.length());
554 m_allowChildLogs = true;
555 } else if (arg == "--help") {
557 } else if (arg.find(output) == 0) {
558 arg.erase(0, output.length());
559 if (m_collectors.find(arg) != m_collectors.end()) {
561 "Multiple outputs of the same type are not supported!");
565 currentCollector.reset(TestResultsCollectorBase::Create(arg));
566 if (!currentCollector) {
567 InvalidArgs("Unsupported output type!");
571 m_collectors[arg] = currentCollector;
572 } else if (arg.find(regexp) == 0) {
573 arg.erase(0, regexp.length());
574 if (arg.length() == 0) {
580 if (arg[0] == '\'' && arg[arg.length() - 1] == '\'') {
582 arg.erase(arg.length() - 1);
585 if (arg.length() == 0) {
591 pcrecpp::RE re(arg.c_str());
592 for (auto &group : m_testGroups) {
593 TestCaseStructList newList;
594 for (auto &tc : group.second)
596 if (re.PartialMatch(tc.name)) {
597 newList.push_back(tc);
600 group.second = newList;
602 } else if(arg.find(onlyFromXML) == 0) {
603 arg.erase(0, onlyFromXML.length());
604 if (arg.length() == 0) {
610 if (arg[0] == '\'' && arg[arg.length() - 1] == '\'') {
612 arg.erase(arg.length() - 1);
615 if (arg.length() == 0) {
621 xmlFiles.push_back(arg);
629 if(!xmlFiles.empty())
631 if(!filterGroupsByXmls(xmlFiles))
633 fprintf(stderr, "XML file is not correct\n");
640 for (auto &group : m_testGroups) {
641 for (auto &tc : group.second) {
642 printf("ID:%s:%s\n", group.first.c_str(), tc.name.c_str());
648 currentCollector.reset();
656 if (m_collectors.empty()) {
657 TestResultsCollectorBasePtr collector(
658 TestResultsCollectorBase::Create("text"));
659 m_collectors["text"] = collector;
662 for (auto &collector : m_collectors) {
663 if (!collector.second->Configure()) {
664 fprintf(stderr, "Could not configure selected output");
675 bool TestRunner::getRunIgnored() const
680 void TestRunner::Terminate()
685 bool TestRunner::GetAllowChildLogs()
687 return m_allowChildLogs;
690 void TestRunner::deferFailedException(const DPL::Test::TestFailed &ex)
692 if (m_deferDeepness <= 0)
695 if (m_deferredExceptionsMessages.empty()) {
696 m_firstDeferredFail = ex;
697 m_firstDeferredExceptionType = DeferredExceptionType::DEFERRED_FAILED;
699 m_deferredExceptionsMessages.push_back(ex.GetMessage());
702 void TestRunner::deferIgnoredException(const DPL::Test::TestIgnored &ex)
704 if (m_deferDeepness <= 0)
707 if (m_deferredExceptionsMessages.empty()) {
708 m_firstDeferredIgnore = ex;
709 m_firstDeferredExceptionType = DeferredExceptionType::DEFERRED_IGNORED;
711 m_deferredExceptionsMessages.push_back(ex.GetMessage());
714 void TestRunner::deferBegin()
719 void TestRunner::deferEnd()
721 if (m_deferDeepness > 0)
724 if (m_deferDeepness > 0)
727 bool oops = std::uncaught_exception();
728 size_t additionalExceptions = oops ? 0 : 1;
729 for (size_t i = additionalExceptions; i < m_deferredExceptionsMessages.size(); ++i)
730 addFailReason(m_deferredExceptionsMessages[i]);
732 if (!oops && !m_deferredExceptionsMessages.empty())
734 m_deferredExceptionsMessages.clear();
735 switch (m_firstDeferredExceptionType) {
736 case DeferredExceptionType::DEFERRED_FAILED:
737 throw m_firstDeferredFail;
738 case DeferredExceptionType::DEFERRED_IGNORED:
739 throw m_firstDeferredIgnore;
742 m_deferredExceptionsMessages.clear();