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 TestRunner::Status TestRunner::RunTestCase(const TestCaseStruct& testCase)
211 setCurrentTestCase(&(const_cast<TestCaseStruct &>(testCase)));
214 } catch (const TestFailed &e) {
215 // Simple test failure
216 CollectResult(testCase.name,
217 TestResultsCollectorBase::FailStatus::FAILED,
218 getConcatedFailReason(e.GetMessage()));
220 setCurrentTestCase(nullptr);
222 } catch (const TestIgnored &e) {
224 // Simple test have to be implemented
225 CollectResult(testCase.name,
226 TestResultsCollectorBase::FailStatus::IGNORED,
230 setCurrentTestCase(nullptr);
232 } catch (const std::exception &) {
233 // std exception failure
234 CollectResult(testCase.name,
235 TestResultsCollectorBase::FailStatus::FAILED,
238 setCurrentTestCase(nullptr);
241 // Unknown exception failure
242 CollectResult(testCase.name,
243 TestResultsCollectorBase::FailStatus::FAILED,
244 "unknown exception");
246 setCurrentTestCase(nullptr);
250 CollectResult(testCase.name,
251 TestResultsCollectorBase::FailStatus::NONE,
253 testCase.m_isPerformanceTest,
254 testCase.m_performanceTestDurationTime,
255 testCase.m_performanceMaxTime);
256 setCurrentTestCase(nullptr);
262 void TestRunner::RunTests()
264 using namespace DPL::Colors::Text;
267 for (auto &collector : m_collectors) {
268 collector.second->Start();
272 for (auto &group : m_testGroups) {
273 count += group.second.size();
275 fprintf(stderr, "%sFound %d testcases...%s\n", GREEN_BEGIN, count, GREEN_END);
276 fprintf(stderr, "%s%s%s\n", GREEN_BEGIN, "Running tests...", GREEN_END);
277 for (auto &group : m_testGroups) {
278 TestCaseStructList list = group.second;
280 for (auto &collector : m_collectors) {
281 collector.second->CollectCurrentTestGroupName(group.first);
285 for (TestCaseStructList::const_iterator iterator = list.begin();
286 iterator != list.end();
289 TestCaseStruct test = *iterator;
290 if (m_startTestId == test.name) {
294 if (m_startTestId.empty()) {
297 if (m_terminate == true) {
298 // Terminate quietly without any logs
305 std::for_each(m_collectors.begin(),
307 [] (const TestResultsCollectors::value_type & collector)
309 collector.second->Finish();
313 fprintf(stderr, "%s%s%s\n\n", GREEN_BEGIN, "Finished", GREEN_END);
316 TestRunner::TestCaseStruct *TestRunner::getCurrentTestCase()
318 return m_currentTestCase;
321 void TestRunner::setCurrentTestCase(TestCaseStruct* testCase)
323 m_currentTestCase = testCase;
326 void TestRunner::beginPerformanceTestTime(std::chrono::system_clock::duration maxTimeInMicroseconds)
328 TestCaseStruct* testCase = getCurrentTestCase();
332 testCase->m_isPerformanceTest = true;
333 testCase->m_performanceMaxTime = maxTimeInMicroseconds;
334 testCase->m_performanceTestStartTime = std::chrono::system_clock::now();
336 // Set result to 0 microseconds. Display 0ms result when end macro is missing.
337 testCase->m_performanceTestDurationTime = std::chrono::microseconds::zero();
340 void TestRunner::endPerformanceTestTime()
342 TestCaseStruct* testCase = getCurrentTestCase();
346 testCase->m_performanceTestDurationTime = std::chrono::system_clock::now() -
347 testCase->m_performanceTestStartTime;
350 void TestRunner::getCurrentTestCasePerformanceResult(bool& isPerformanceTest,
351 std::chrono::system_clock::duration& result,
352 std::chrono::system_clock::duration& resultMax)
354 TestCaseStruct* testCase = getCurrentTestCase();
355 if (!testCase || !(testCase->m_isPerformanceTest)){
356 isPerformanceTest = false;
360 isPerformanceTest = testCase->m_isPerformanceTest;
361 result = testCase->m_performanceTestDurationTime;
362 resultMax = testCase->m_performanceMaxTime;
365 void TestRunner::setCurrentTestCasePerformanceResult(bool isPerformanceTest,
366 std::chrono::system_clock::duration result,
367 std::chrono::system_clock::duration resultMax)
369 TestCaseStruct* testCase = getCurrentTestCase();
373 testCase->m_isPerformanceTest = isPerformanceTest;
374 testCase->m_performanceTestDurationTime = result;
375 testCase->m_performanceMaxTime = resultMax;
378 void TestRunner::addFailReason(const std::string &reason)
380 m_failReason.push(reason);
383 std::string TestRunner::getConcatedFailReason(const std::string &reason)
386 while (!m_failReason.empty())
388 ret += m_failReason.front();
394 void TestRunner::CollectResult(
395 const std::string& id,
396 const TestResultsCollectorBase::FailStatus status,
397 const std::string& reason,
398 const bool& isPerformanceTest,
399 const std::chrono::system_clock::duration& performanceTestDurationTime,
400 const std::chrono::system_clock::duration& performanceMaxTime)
402 std::for_each(m_collectors.begin(),
404 [&](const TestResultsCollectors::value_type & collector)
406 collector.second->CollectResult(id,
410 performanceTestDurationTime,
415 void TestRunner::Banner()
417 using namespace DPL::Colors::Text;
431 void TestRunner::InvalidArgs(const std::string& message)
433 using namespace DPL::Colors::Text;
441 void TestRunner::Usage()
443 fprintf(stderr, "Usage: runner [options]\n\n");
444 fprintf(stderr, "Output type:\n");
445 fprintf(stderr, " --output=<output type> --output=<output type> ...\n");
446 fprintf(stderr, "\n possible output types:\n");
447 for (std::string &type : TestResultsCollectorBase::GetCollectorsNames()) {
448 fprintf(stderr, " --output=%s\n", type.c_str());
450 fprintf(stderr, "\n example:\n");
452 " test-binary --output=text --output=xml --file=output.xml\n\n");
453 fprintf(stderr, "Other parameters:\n");
455 " --regexp='regexp'\t Only selected tests"
456 " which names match regexp run\n\n");
457 fprintf(stderr, " --start=<test id>\tStart from concrete test id");
458 fprintf(stderr, " --group=<group name>\t Run tests only from one group\n");
459 fprintf(stderr, " --runignored\t Run also ignored tests\n");
460 fprintf(stderr, " --list\t Show a list of Test IDs\n");
461 fprintf(stderr, " --listgroups\t Show a list of Test Group names \n");
462 fprintf(stderr, " --only-from-xml=<xml file>\t Run only testcases specified in XML file \n"
463 " XML name is taken from attribute id=\"part1_part2\" as whole.\n"
464 " If part1 is not found (no _) then it is implicitily "
465 "set according to suite part1 from binary tests\n");
468 " --listingroup=<group name>\t Show a list of Test IDS in one group\n");
469 fprintf(stderr, " --allowchildlogs\t Allow to print logs from child process on screen.\n");
470 fprintf(stderr, " When active child process will be able to print logs on stdout and stderr.\n");
471 fprintf(stderr, " Both descriptors will be closed after test.\n");
472 fprintf(stderr, " --help\t This help\n\n");
473 std::for_each(m_collectors.begin(),
475 [] (const TestResultsCollectors::value_type & collector)
478 "Output %s has specific args:\n",
479 collector.first.c_str());
483 CollectorSpecificHelp().c_str());
485 fprintf(stderr, "For bug reporting, please write to:\n");
486 fprintf(stderr, "<p.dobrowolsk@samsung.com>\n");
489 int TestRunner::ExecTestRunner(int argc, char *argv[])
491 std::vector<std::string> args;
492 for (int i = 0; i < argc; ++i) {
493 args.push_back(argv[i]);
495 return ExecTestRunner(args);
498 void TestRunner::MarkAssertion()
503 int TestRunner::ExecTestRunner(ArgsList args)
505 m_runIgnored = false;
506 // Parse command line
508 args.erase(args.begin());
510 bool showHelp = false;
511 bool justList = false;
512 std::vector<std::string> xmlFiles;
514 TestResultsCollectorBasePtr currentCollector;
516 // Parse each argument
517 for(std::string &arg : args)
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.name == 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 TestCaseStructList 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.name.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 TestCaseStructList newList;
627 for (auto &tc : group.second)
629 if (re.PartialMatch(tc.name)) {
630 newList.push_back(tc);
633 group.second = newList;
635 } else if(arg.find(onlyFromXML) == 0) {
636 arg.erase(0, onlyFromXML.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 xmlFiles.push_back(arg);
662 if(!xmlFiles.empty())
664 if(!filterGroupsByXmls(xmlFiles))
666 fprintf(stderr, "XML file is not correct\n");
673 for (auto &group : m_testGroups) {
674 for (auto &tc : group.second) {
675 printf("ID:%s:%s\n", group.first.c_str(), tc.name.c_str());
681 currentCollector.reset();
689 if (m_collectors.empty()) {
690 TestResultsCollectorBasePtr collector(
691 TestResultsCollectorBase::Create("text"));
692 m_collectors["text"] = collector;
695 for (auto &collector : m_collectors) {
696 if (!collector.second->Configure()) {
697 fprintf(stderr, "Could not configure selected output");
708 bool TestRunner::getRunIgnored() const
713 void TestRunner::Terminate()
718 bool TestRunner::GetAllowChildLogs()
720 return m_allowChildLogs;