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_runner.h>
25 #include <dpl/test/test_results_collector.h>
26 #include <dpl/exception.h>
27 #include <dpl/scoped_free.h>
28 #include <dpl/log/log.h>
29 #include <dpl/colors.h>
38 #include <libxml/xpath.h>
39 #include <libxml/xpathInternals.h>
40 #include <libxml/parser.h>
41 #include <libxml/tree.h>
43 #include <dpl/singleton_impl.h>
44 IMPLEMENT_SINGLETON(DPL::Test::TestRunner)
48 std::string getXMLNode(xmlNodePtr node)
51 xmlChar * value = xmlNodeGetContent(node);
52 ret = std::string(reinterpret_cast<char*>(value));
62 namespace // anonymous
64 std::string BaseName(std::string aPath)
66 ScopedFree<char> path(strdup(aPath.c_str()));
67 if (nullptr == path.Get()) {
68 throw std::bad_alloc();
70 char* baseName = basename(path.Get());
71 std::string retValue = baseName;
74 } // namespace anonymous
76 //! \brief Failed test message creator
78 //! \param[in] aTest string for tested expression
79 //! \param[in] aFile source file name
80 //! \param[in] aLine source file line
81 //! \param[in] aMessage error message
82 TestRunner::TestFailed::TestFailed(const char* aTest,
85 const std::string &aMessage)
87 std::ostringstream assertMsg;
88 assertMsg << "[" << BaseName(aFile) << ":" << aLine
89 << "] Assertion failed ("
90 << aTest << ") " << aMessage;
91 m_message = assertMsg.str();
94 TestRunner::TestFailed::TestFailed(const std::string &message)
99 void TestRunner::RegisterTest(const char *testName, TestCase proc)
101 m_testGroups[m_currentGroup].push_back(TestCaseStruct(testName, proc));
104 void TestRunner::InitGroup(const char* name)
106 m_currentGroup = name;
109 void TestRunner::normalizeXMLTag(std::string& str, const std::string& testcase)
111 //Add testcase if missing
112 std::string::size_type pos = str.find(testcase);
115 str = testcase + "_" + str;
118 //dpl test runner cannot have '-' character in name so it have to be replaced
119 // for TCT case to make comparision works
120 std::replace(str.begin(), str.end(), '-', '_');
123 bool TestRunner::filterGroupsByXmls(const std::vector<std::string> & files)
125 DECLARE_EXCEPTION_TYPE(DPL::Exception, XMLError)
127 const std::string idPath = "/test_definition/suite/set/testcase/@id";
130 std::map<std::string, bool> casesMap;
132 std::string testsuite;
133 if(!m_testGroups.empty())
135 for(TestCaseGroupMap::const_iterator cit = m_testGroups.begin(); cit != m_testGroups.end(); ++cit)
137 if(!cit->second.empty())
139 for(TestCaseStructList::const_iterator cj = cit->second.begin(); cj != cit->second.end(); ++cj)
141 std::string name = cj->name;
142 std::string::size_type st = name.find('_');
143 if(st != std::string::npos)
145 name = name.substr(0, st);
150 if(!testsuite.empty()) break;
161 for (const std::string &file : files)
164 xmlXPathContextPtr xpathCtx;
166 doc = xmlReadFile(file.c_str(), nullptr, 0);
167 if (doc == nullptr) {
168 ThrowMsg(XMLError, "File Problem");
171 xpathCtx = xmlXPathNewContext(doc);
172 if (xpathCtx == nullptr) {
174 "Error: unable to create new XPath context\n");
176 xpathCtx->node = xmlDocGetRootElement(doc);
180 xmlXPathObjectPtr xpathObject;
181 //get requested node's values
182 xpathObject = xmlXPathEvalExpression(BAD_CAST idPath.c_str(), xpathCtx);
183 if (xpathObject == nullptr)
185 ThrowMsg(XMLError, "XPath evaluation failure: " << idPath);
187 xmlNodeSetPtr nodes = xpathObject->nodesetval;
188 unsigned size = (nodes) ? nodes->nodeNr : 0;
189 LogDebug("Found " << size << " nodes matching xpath");
190 for(unsigned i = 0; i < size; ++i)
192 LogPedantic("Type: " << nodes->nodeTab[i]->type);
193 if (nodes->nodeTab[i]->type == XML_ATTRIBUTE_NODE) {
194 xmlNodePtr curNode = nodes->nodeTab[i];
195 result = getXMLNode(curNode);
196 LogPedantic("Result: " << result);
197 normalizeXMLTag(result, testsuite);
198 casesMap.insert(make_pair(result, false));
201 //Cleanup of XPath data
202 xmlXPathFreeObject(xpathObject);
203 xmlXPathFreeContext(xpathCtx);
209 LogError("Libxml error: " << _rethrown_exception.DumpToString());
214 if(!filterByXML(casesMap))
222 bool TestRunner::filterByXML(std::map<std::string, bool> & casesMap)
224 for (auto &group : m_testGroups) {
225 TestCaseStructList newList;
226 for (auto &tc : group.second)
228 if (casesMap.find(tc.name) != casesMap.end()) {
229 casesMap[tc.name] = true;
230 newList.push_back(tc);
233 group.second = newList;
235 for (auto &cs : casesMap)
237 if(cs.second == false)
239 LogError("Cannot find testcase from XML file: " << cs.first);
246 TestRunner::Status TestRunner::RunTestCase(const TestCaseStruct& testCase)
248 setCurrentTestCase(&(const_cast<TestCaseStruct &>(testCase)));
251 } catch (const TestFailed &e) {
252 // Simple test failure
253 CollectResult(testCase.name,
254 TestResultsCollectorBase::FailStatus::FAILED,
255 getConcatedFailReason(e.GetMessage()));
257 setCurrentTestCase(nullptr);
259 } catch (const Ignored &e) {
261 // Simple test have to be implemented
262 CollectResult(testCase.name,
263 TestResultsCollectorBase::FailStatus::IGNORED,
267 setCurrentTestCase(nullptr);
269 } catch (const std::exception &) {
270 // std exception failure
271 CollectResult(testCase.name,
272 TestResultsCollectorBase::FailStatus::FAILED,
275 setCurrentTestCase(nullptr);
278 // Unknown exception failure
279 CollectResult(testCase.name,
280 TestResultsCollectorBase::FailStatus::FAILED,
281 "unknown exception");
283 setCurrentTestCase(nullptr);
287 CollectResult(testCase.name,
288 TestResultsCollectorBase::FailStatus::NONE,
290 testCase.performance);
291 setCurrentTestCase(nullptr);
297 void TestRunner::RunTests()
299 using namespace DPL::Colors::Text;
302 for (auto &collector : m_collectors) {
303 collector.second->Start();
307 for (auto &group : m_testGroups) {
308 count += group.second.size();
310 fprintf(stderr, "%sFound %d testcases...%s\n", GREEN_BEGIN, count, GREEN_END);
311 fprintf(stderr, "%s%s%s\n", GREEN_BEGIN, "Running tests...", GREEN_END);
312 for (auto &group : m_testGroups) {
313 TestCaseStructList list = group.second;
315 for (auto &collector : m_collectors) {
316 collector.second->CollectCurrentTestGroupName(group.first);
320 for (TestCaseStructList::const_iterator iterator = list.begin();
321 iterator != list.end();
324 TestCaseStruct test = *iterator;
325 if (m_startTestId == test.name) {
329 if (m_startTestId.empty()) {
332 if (m_terminate == true) {
333 // Terminate quietly without any logs
340 std::for_each(m_collectors.begin(),
342 [] (const TestResultsCollectors::value_type & collector)
344 collector.second->Finish();
348 fprintf(stderr, "%s%s%s\n\n", GREEN_BEGIN, "Finished", GREEN_END);
351 TestRunner::TestCaseStruct *TestRunner::getCurrentTestCase()
353 return m_currentTestCase;
356 void TestRunner::setCurrentTestCase(TestCaseStruct* testCase)
358 m_currentTestCase = testCase;
361 void TestRunner::beginPerformance(std::chrono::system_clock::duration maxDurationInMicroseconds)
363 TestCaseStruct* testCase = getCurrentTestCase();
367 if (!testCase->performance)
368 testCase->performance.reset(new PerformanceResult(maxDurationInMicroseconds));
371 void TestRunner::endPerformance()
373 TestCaseStruct* testCase = getCurrentTestCase();
377 testCase->performance->Finish();
380 ConstPerformanceResultPtr TestRunner::getCurrentTestCasePerformanceResult()
382 TestCaseStruct* testCase = getCurrentTestCase();
386 return testCase->performance;
389 void TestRunner::setCurrentTestCasePerformanceResult(const PerformanceResultPtr &performance)
391 TestCaseStruct* testCase = getCurrentTestCase();
395 testCase->performance = performance;
398 void TestRunner::addFailReason(const std::string &reason)
400 m_failReason.push(reason);
403 std::string TestRunner::getConcatedFailReason(const std::string &reason)
406 while (!m_failReason.empty())
408 ret += m_failReason.front();
414 void TestRunner::CollectResult(
415 const std::string& id,
416 const TestResultsCollectorBase::FailStatus status,
417 const std::string& reason,
418 const ConstPerformanceResultPtr &performance)
420 std::for_each(m_collectors.begin(),
422 [&](const TestResultsCollectors::value_type & collector)
424 collector.second->CollectResult(id,
431 void TestRunner::Banner()
433 using namespace DPL::Colors::Text;
447 void TestRunner::InvalidArgs(const std::string& message)
449 using namespace DPL::Colors::Text;
457 void TestRunner::Usage()
459 fprintf(stderr, "Usage: runner [options]\n\n");
460 fprintf(stderr, "Output type:\n");
461 fprintf(stderr, " --output=<output type> --output=<output type> ...\n");
462 fprintf(stderr, "\n possible output types:\n");
463 for (std::string &type : TestResultsCollectorBase::GetCollectorsNames()) {
464 fprintf(stderr, " --output=%s\n", type.c_str());
466 fprintf(stderr, "\n example:\n");
468 " test-binary --output=text --output=xml --file=output.xml\n\n");
469 fprintf(stderr, "Other parameters:\n");
471 " --regexp='regexp'\t Only selected tests"
472 " which names match regexp run\n\n");
473 fprintf(stderr, " --start=<test id>\tStart from concrete test id");
474 fprintf(stderr, " --group=<group name>\t Run tests only from one group\n");
475 fprintf(stderr, " --runignored\t Run also ignored tests\n");
476 fprintf(stderr, " --list\t Show a list of Test IDs\n");
477 fprintf(stderr, " --listgroups\t Show a list of Test Group names \n");
478 fprintf(stderr, " --only-from-xml=<xml file>\t Run only testcases specified in XML file \n"
479 " XML name is taken from attribute id=\"part1_part2\" as whole.\n"
480 " If part1 is not found (no _) then it is implicitily "
481 "set according to suite part1 from binary tests\n");
484 " --listingroup=<group name>\t Show a list of Test IDS in one group\n");
485 fprintf(stderr, " --allowchildlogs\t Allow to print logs from child process on screen.\n");
486 fprintf(stderr, " When active child process will be able to print logs on stdout and stderr.\n");
487 fprintf(stderr, " Both descriptors will be closed after test.\n");
488 fprintf(stderr, " --help\t This help\n\n");
489 std::for_each(m_collectors.begin(),
491 [] (const TestResultsCollectors::value_type & collector)
494 "Output %s has specific args:\n",
495 collector.first.c_str());
499 CollectorSpecificHelp().c_str());
501 fprintf(stderr, "For bug reporting, please write to:\n");
502 fprintf(stderr, "<p.dobrowolsk@samsung.com>\n");
505 int TestRunner::ExecTestRunner(int argc, char *argv[])
507 std::vector<std::string> args;
508 for (int i = 0; i < argc; ++i) {
509 args.push_back(argv[i]);
511 return ExecTestRunner(args);
514 void TestRunner::MarkAssertion()
519 int TestRunner::ExecTestRunner(ArgsList args)
521 m_runIgnored = false;
522 // Parse command line
524 args.erase(args.begin());
526 bool showHelp = false;
527 bool justList = false;
528 std::vector<std::string> xmlFiles;
530 TestResultsCollectorBasePtr currentCollector;
532 // Parse each argument
533 for(std::string &arg : args)
535 const std::string regexp = "--regexp=";
536 const std::string output = "--output=";
537 const std::string groupId = "--group=";
538 const std::string runIgnored = "--runignored";
539 const std::string listCmd = "--list";
540 const std::string startCmd = "--start=";
541 const std::string listGroupsCmd = "--listgroups";
542 const std::string listInGroup = "--listingroup=";
543 const std::string allowChildLogs = "--allowchildlogs";
544 const std::string onlyFromXML = "--only-from-xml=";
546 if (currentCollector) {
547 if (currentCollector->ParseCollectorSpecificArg(arg)) {
552 if (arg.find(startCmd) == 0) {
553 arg.erase(0, startCmd.length());
554 for (auto &group : m_testGroups) {
555 for (auto &tc : group.second) {
556 if (tc.name == arg) {
561 if (!m_startTestId.empty()) {
565 if (!m_startTestId.empty()) {
569 fprintf(stderr, "Start test id has not been found\n");
572 } else if (arg.find(groupId) == 0) {
573 arg.erase(0, groupId.length());
574 TestCaseGroupMap::iterator found = m_testGroups.find(arg);
575 if (found != m_testGroups.end()) {
576 std::string name = found->first;
577 TestCaseStructList newList = found->second;
578 m_testGroups.clear();
579 m_testGroups[name] = newList;
581 fprintf(stderr, "Group %s not found\n", arg.c_str());
586 } else if (arg == runIgnored) {
588 } else if (arg == listCmd) {
590 } else if (arg == listGroupsCmd) {
591 for (auto &group : m_testGroups) {
592 printf("GR:%s\n", group.first.c_str());
595 } else if (arg.find(listInGroup) == 0) {
596 arg.erase(0, listInGroup.length());
597 for (auto &test : m_testGroups[arg]) {
598 printf("ID:%s\n", test.name.c_str());
601 } else if (arg.find(allowChildLogs) == 0) {
602 arg.erase(0, allowChildLogs.length());
603 m_allowChildLogs = true;
604 } else if (arg == "--help") {
606 } else if (arg.find(output) == 0) {
607 arg.erase(0, output.length());
608 if (m_collectors.find(arg) != m_collectors.end()) {
610 "Multiple outputs of the same type are not supported!");
614 currentCollector.reset(TestResultsCollectorBase::Create(arg));
615 if (!currentCollector) {
616 InvalidArgs("Unsupported output type!");
620 m_collectors[arg] = currentCollector;
621 } else if (arg.find(regexp) == 0) {
622 arg.erase(0, regexp.length());
623 if (arg.length() == 0) {
629 if (arg[0] == '\'' && arg[arg.length() - 1] == '\'') {
631 arg.erase(arg.length() - 1);
634 if (arg.length() == 0) {
640 pcrecpp::RE re(arg.c_str());
641 for (auto &group : m_testGroups) {
642 TestCaseStructList newList;
643 for (auto &tc : group.second)
645 if (re.PartialMatch(tc.name)) {
646 newList.push_back(tc);
649 group.second = newList;
651 } else if(arg.find(onlyFromXML) == 0) {
652 arg.erase(0, onlyFromXML.length());
653 if (arg.length() == 0) {
659 if (arg[0] == '\'' && arg[arg.length() - 1] == '\'') {
661 arg.erase(arg.length() - 1);
664 if (arg.length() == 0) {
670 xmlFiles.push_back(arg);
678 if(!xmlFiles.empty())
680 if(!filterGroupsByXmls(xmlFiles))
682 fprintf(stderr, "XML file is not correct\n");
689 for (auto &group : m_testGroups) {
690 for (auto &tc : group.second) {
691 printf("ID:%s:%s\n", group.first.c_str(), tc.name.c_str());
697 currentCollector.reset();
705 if (m_collectors.empty()) {
706 TestResultsCollectorBasePtr collector(
707 TestResultsCollectorBase::Create("text"));
708 m_collectors["text"] = collector;
711 for (auto &collector : m_collectors) {
712 if (!collector.second->Configure()) {
713 fprintf(stderr, "Could not configure selected output");
724 bool TestRunner::getRunIgnored() const
729 void TestRunner::Terminate()
734 bool TestRunner::GetAllowChildLogs()
736 return m_allowChildLogs;