Create class for test result
[platform/core/test/security-tests.git] / src / framework / src / test_runner.cpp
1 /*
2  * Copyright (c) 2014-2015 Samsung Electronics Co., Ltd All Rights Reserved
3  *
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
7  *
8  *        http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 /*
17  * @file        test_runner.cpp
18  * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
19  * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
20  * @version     1.0
21  * @brief       This file is the implementation file of test runner
22  */
23 #include <stddef.h>
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>
30 #include <pcrecpp.h>
31 #include <algorithm>
32 #include <cstdio>
33 #include <memory.h>
34 #include <libgen.h>
35 #include <cstring>
36 #include <cstdlib>
37
38 #include <libxml/xpath.h>
39 #include <libxml/xpathInternals.h>
40 #include <libxml/parser.h>
41 #include <libxml/tree.h>
42
43 #include <dpl/singleton_impl.h>
44 IMPLEMENT_SINGLETON(DPL::Test::TestRunner)
45
46 namespace {
47
48 std::string getXMLNode(xmlNodePtr node)
49 {
50     std::string ret;
51     xmlChar * value = xmlNodeGetContent(node);
52     ret = std::string(reinterpret_cast<char*>(value));
53     xmlFree(value);
54     return ret;
55 }
56
57 }
58
59
60 namespace DPL {
61 namespace Test {
62 namespace // anonymous
63 {
64 std::string BaseName(std::string aPath)
65 {
66     ScopedFree<char> path(strdup(aPath.c_str()));
67     if (nullptr == path.Get()) {
68         throw std::bad_alloc();
69     }
70     char* baseName = basename(path.Get());
71     std::string retValue = baseName;
72     return retValue;
73 }
74 } // namespace anonymous
75
76 //! \brief Failed test message creator
77 //!
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,
83                                    const char* aFile,
84                                    int aLine,
85                                    const std::string &aMessage)
86 {
87     std::ostringstream assertMsg;
88     assertMsg << "[" << BaseName(aFile) << ":" << aLine
89               << "] Assertion failed ("
90               << aTest << ") " << aMessage;
91     m_message = assertMsg.str();
92 }
93
94 TestRunner::TestFailed::TestFailed(const std::string &message)
95 {
96     m_message = message;
97 }
98
99 void TestRunner::RegisterTest(const char *testName, TestCase proc)
100 {
101     m_testGroups[m_currentGroup].push_back(TestCaseStruct(testName, proc));
102 }
103
104 void TestRunner::InitGroup(const char* name)
105 {
106     m_currentGroup = name;
107 }
108
109 void TestRunner::normalizeXMLTag(std::string& str, const std::string& testcase)
110 {
111     //Add testcase if missing
112     std::string::size_type pos = str.find(testcase);
113     if(pos != 0)
114     {
115         str = testcase + "_" + str;
116     }
117
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(), '-', '_');
121 }
122
123 bool TestRunner::filterGroupsByXmls(const std::vector<std::string> & files)
124 {
125     DECLARE_EXCEPTION_TYPE(DPL::Exception, XMLError)
126
127     const std::string idPath = "/test_definition/suite/set/testcase/@id";
128
129     bool success = true;
130     std::map<std::string, bool> casesMap;
131
132     std::string testsuite;
133     if(!m_testGroups.empty())
134     {
135         for(TestCaseGroupMap::const_iterator cit = m_testGroups.begin(); cit != m_testGroups.end(); ++cit)
136         {
137             if(!cit->second.empty())
138             {
139                 for(TestCaseStructList::const_iterator cj = cit->second.begin(); cj != cit->second.end(); ++cj)
140                 {
141                     std::string name = cj->name;
142                     std::string::size_type st = name.find('_');
143                     if(st != std::string::npos)
144                     {
145                         name = name.substr(0, st);
146                         testsuite = name;
147                         break;
148                     }
149                 }
150                 if(!testsuite.empty()) break;
151             }
152         }
153     }
154
155     xmlInitParser();
156     LIBXML_TEST_VERSION
157     xmlXPathInit();
158
159     Try
160     {
161         for (const std::string &file : files)
162         {
163             xmlDocPtr doc;
164             xmlXPathContextPtr xpathCtx;
165
166             doc = xmlReadFile(file.c_str(), nullptr, 0);
167             if (doc == nullptr) {
168                 ThrowMsg(XMLError, "File Problem");
169             } else {
170                 //context
171                 xpathCtx = xmlXPathNewContext(doc);
172                 if (xpathCtx == nullptr) {
173                     ThrowMsg(XMLError,
174                              "Error: unable to create new XPath context\n");
175                 }
176                 xpathCtx->node = xmlDocGetRootElement(doc);
177             }
178
179             std::string result;
180             xmlXPathObjectPtr xpathObject;
181             //get requested node's values
182             xpathObject = xmlXPathEvalExpression(BAD_CAST idPath.c_str(), xpathCtx);
183             if (xpathObject == nullptr)
184             {
185                 ThrowMsg(XMLError, "XPath evaluation failure: " << idPath);
186             }
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)
191             {
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));
199                 }
200             }
201             //Cleanup of XPath data
202             xmlXPathFreeObject(xpathObject);
203             xmlXPathFreeContext(xpathCtx);
204             xmlFreeDoc(doc);
205         }
206     }
207     Catch(XMLError)
208     {
209         LogError("Libxml error: " << _rethrown_exception.DumpToString());
210         success = false;
211     }
212     xmlCleanupParser();
213
214     if(!filterByXML(casesMap))
215     {
216         success = false;
217     }
218
219     return success;
220 }
221
222 bool TestRunner::filterByXML(std::map<std::string, bool> & casesMap)
223 {
224     for (auto &group : m_testGroups) {
225         TestCaseStructList newList;
226         for (auto &tc : group.second)
227         {
228             if (casesMap.find(tc.name) != casesMap.end()) {
229                 casesMap[tc.name] = true;
230                 newList.push_back(tc);
231             }
232         }
233         group.second = newList;
234     }
235     for (auto &cs : casesMap)
236     {
237         if(cs.second == false)
238         {
239             LogError("Cannot find testcase from XML file: " << cs.first);
240             return false;
241         }
242     }
243     return true;
244 }
245
246 TestRunner::Status TestRunner::RunTestCase(const TestCaseStruct& testCase)
247 {
248     setCurrentTestCase(&(const_cast<TestCaseStruct &>(testCase)));
249     try {
250         testCase.proc();
251     } catch (const TestFailed &e) {
252         // Simple test failure
253         CollectResult(testCase.name,
254                       TestResult(TestResult::FailStatus::FAILED,
255                                  getConcatedFailReason(e.GetMessage())));
256
257         setCurrentTestCase(nullptr);
258         return FAILED;
259     } catch (const Ignored &e) {
260         if (m_runIgnored) {
261             // Simple test have to be implemented
262             CollectResult(testCase.name,
263                           TestResult(TestResult::FailStatus::IGNORED, e.GetMessage()));
264         }
265
266         setCurrentTestCase(nullptr);
267         return IGNORED;
268     } catch (const std::exception &) {
269         // std exception failure
270         CollectResult(testCase.name,
271                       TestResult(TestResult::FailStatus::FAILED, "std exception"));
272
273         setCurrentTestCase(nullptr);
274         return FAILED;
275     } catch (...) {
276         // Unknown exception failure
277         CollectResult(testCase.name,
278                       TestResult(TestResult::FailStatus::FAILED, "unknown exception"));
279         setCurrentTestCase(nullptr);
280         return FAILED;
281     }
282
283     CollectResult(testCase.name,
284                   TestResult(TestResult::FailStatus::NONE,
285                              std::string(),
286                              testCase.performance));
287     setCurrentTestCase(nullptr);
288
289     // Everything OK
290     return PASS;
291 }
292
293 void TestRunner::RunTests()
294 {
295     using namespace DPL::Colors::Text;
296
297     Banner();
298     for (auto &collector : m_collectors) {
299         collector.second->Start();
300     }
301
302     unsigned count = 0;
303     for (auto &group : m_testGroups) {
304         count += group.second.size();
305     }
306     fprintf(stderr, "%sFound %d testcases...%s\n", GREEN_BEGIN, count, GREEN_END);
307     fprintf(stderr, "%s%s%s\n", GREEN_BEGIN, "Running tests...", GREEN_END);
308     for (auto &group : m_testGroups) {
309         TestCaseStructList list = group.second;
310         if (!list.empty()) {
311             for (auto &collector : m_collectors) {
312                 collector.second->CollectCurrentTestGroupName(group.first);
313             }
314             list.sort();
315
316             for (TestCaseStructList::const_iterator iterator = list.begin();
317                  iterator != list.end();
318                  ++iterator)
319             {
320                 TestCaseStruct test = *iterator;
321                 if (m_startTestId == test.name) {
322                     m_startTestId = "";
323                 }
324
325                 if (m_startTestId.empty()) {
326                     RunTestCase(test);
327                 }
328                 if (m_terminate == true) {
329                     // Terminate quietly without any logs
330                     return;
331                 }
332             }
333         }
334     }
335
336     std::for_each(m_collectors.begin(),
337                   m_collectors.end(),
338                   [] (const TestResultsCollectors::value_type & collector)
339                   {
340                       collector.second->Finish();
341                   });
342
343     // Finished
344     fprintf(stderr, "%s%s%s\n\n", GREEN_BEGIN, "Finished", GREEN_END);
345 }
346
347 TestRunner::TestCaseStruct *TestRunner::getCurrentTestCase()
348 {
349     return m_currentTestCase;
350 }
351
352 void TestRunner::setCurrentTestCase(TestCaseStruct* testCase)
353 {
354     m_currentTestCase = testCase;
355 }
356
357 void TestRunner::beginPerformance(std::chrono::system_clock::duration maxDurationInMicroseconds)
358 {
359     TestCaseStruct* testCase = getCurrentTestCase();
360     if (!testCase)
361         return;
362
363     if (!testCase->performance)
364         testCase->performance.reset(new PerformanceResult(maxDurationInMicroseconds));
365 }
366
367 void TestRunner::endPerformance()
368 {
369     TestCaseStruct* testCase = getCurrentTestCase();
370     if (!testCase)
371         return;
372
373     testCase->performance->Finish();
374 }
375
376 ConstPerformanceResultPtr TestRunner::getCurrentTestCasePerformanceResult()
377 {
378     TestCaseStruct* testCase = getCurrentTestCase();
379     if (!testCase)
380         return nullptr;
381
382     return testCase->performance;
383 }
384
385 void TestRunner::setCurrentTestCasePerformanceResult(const PerformanceResultPtr &performance)
386 {
387     TestCaseStruct* testCase = getCurrentTestCase();
388     if (!testCase)
389         return;
390
391     testCase->performance = performance;
392 }
393
394 void TestRunner::addFailReason(const std::string &reason)
395 {
396     m_failReason.push(reason);
397 }
398
399 std::string TestRunner::getConcatedFailReason(const std::string &reason)
400 {
401     std::string ret;
402     while (!m_failReason.empty())
403     {
404         ret += m_failReason.front();
405         m_failReason.pop();
406     }
407     return reason + ret;
408 }
409
410 void TestRunner::CollectResult(const std::string& id, const TestResult& result)
411 {
412     std::for_each(m_collectors.begin(),
413                   m_collectors.end(),
414                   [&](const TestResultsCollectors::value_type & collector)
415                   {
416                       collector.second->CollectResult(id, result);
417                   });
418 }
419
420 void TestRunner::Banner()
421 {
422     using namespace DPL::Colors::Text;
423     fprintf(stderr,
424             "%s%s%s\n",
425             BOLD_GREEN_BEGIN,
426             "DPL tests runner",
427             BOLD_GREEN_END);
428     fprintf(stderr,
429             "%s%s%s%s\n\n",
430             GREEN_BEGIN,
431             "Build: ",
432             __TIMESTAMP__,
433             GREEN_END);
434 }
435
436 void TestRunner::InvalidArgs(const std::string& message)
437 {
438     using namespace DPL::Colors::Text;
439     fprintf(stderr,
440             "%s%s%s\n",
441             BOLD_RED_BEGIN,
442             message.c_str(),
443             BOLD_RED_END);
444 }
445
446 void TestRunner::Usage()
447 {
448     fprintf(stderr, "Usage: runner [options]\n\n");
449     fprintf(stderr, "Output type:\n");
450     fprintf(stderr, "  --output=<output type> --output=<output type> ...\n");
451     fprintf(stderr, "\n  possible output types:\n");
452     for (std::string &type : TestResultsCollectorBase::GetCollectorsNames()) {
453         fprintf(stderr, "    --output=%s\n", type.c_str());
454     }
455     fprintf(stderr, "\n  example:\n");
456     fprintf(stderr,
457             "    test-binary --output=text --output=xml --file=output.xml\n\n");
458     fprintf(stderr, "Other parameters:\n");
459     fprintf(stderr,
460             "  --regexp='regexp'\t Only selected tests"
461             " which names match regexp run\n\n");
462     fprintf(stderr, "  --start=<test id>\tStart from concrete test id");
463     fprintf(stderr, "  --group=<group name>\t Run tests only from one group\n");
464     fprintf(stderr, "  --runignored\t Run also ignored tests\n");
465     fprintf(stderr, "  --list\t Show a list of Test IDs\n");
466     fprintf(stderr, "  --listgroups\t Show a list of Test Group names \n");
467     fprintf(stderr, "  --only-from-xml=<xml file>\t Run only testcases specified in XML file \n"
468                     "       XML name is taken from attribute id=\"part1_part2\" as whole.\n"
469                     "       If part1 is not found (no _) then it is implicitily "
470                            "set according to suite part1 from binary tests\n");
471     fprintf(
472         stderr,
473         "  --listingroup=<group name>\t Show a list of Test IDS in one group\n");
474     fprintf(stderr, "  --allowchildlogs\t Allow to print logs from child process on screen.\n");
475     fprintf(stderr, "       When active child process will be able to print logs on stdout and stderr.\n");
476     fprintf(stderr, "       Both descriptors will be closed after test.\n");
477     fprintf(stderr, "  --help\t This help\n\n");
478     std::for_each(m_collectors.begin(),
479                   m_collectors.end(),
480                   [] (const TestResultsCollectors::value_type & collector)
481                   {
482                       fprintf(stderr,
483                               "Output %s has specific args:\n",
484                               collector.first.c_str());
485                       fprintf(stderr,
486                               "%s\n",
487                               collector.second->
488                                   CollectorSpecificHelp().c_str());
489                   });
490     fprintf(stderr, "For bug reporting, please write to:\n");
491     fprintf(stderr, "<p.dobrowolsk@samsung.com>\n");
492 }
493
494 int TestRunner::ExecTestRunner(int argc, char *argv[])
495 {
496     std::vector<std::string> args;
497     for (int i = 0; i < argc; ++i) {
498         args.push_back(argv[i]);
499     }
500     return ExecTestRunner(args);
501 }
502
503 void TestRunner::MarkAssertion()
504 {
505     ++m_totalAssertions;
506 }
507
508 int TestRunner::ExecTestRunner(ArgsList args)
509 {
510     m_runIgnored = false;
511     // Parse command line
512
513     args.erase(args.begin());
514
515     bool showHelp = false;
516     bool justList = false;
517     std::vector<std::string> xmlFiles;
518
519     TestResultsCollectorBasePtr currentCollector;
520
521     // Parse each argument
522     for(std::string &arg : args)
523     {
524         const std::string regexp = "--regexp=";
525         const std::string output = "--output=";
526         const std::string groupId = "--group=";
527         const std::string runIgnored = "--runignored";
528         const std::string listCmd = "--list";
529         const std::string startCmd = "--start=";
530         const std::string listGroupsCmd = "--listgroups";
531         const std::string listInGroup = "--listingroup=";
532         const std::string allowChildLogs = "--allowchildlogs";
533         const std::string onlyFromXML = "--only-from-xml=";
534
535         if (currentCollector) {
536             if (currentCollector->ParseCollectorSpecificArg(arg)) {
537                 continue;
538             }
539         }
540
541         if (arg.find(startCmd) == 0) {
542             arg.erase(0, startCmd.length());
543             for (auto &group : m_testGroups) {
544                 for (auto &tc : group.second) {
545                     if (tc.name == arg) {
546                         m_startTestId = arg;
547                         break;
548                     }
549                 }
550                 if (!m_startTestId.empty()) {
551                     break;
552                 }
553             }
554             if (!m_startTestId.empty()) {
555                 continue;
556             }
557             InvalidArgs();
558             fprintf(stderr, "Start test id has not been found\n");
559             Usage();
560             return 0;
561         } else if (arg.find(groupId) == 0) {
562             arg.erase(0, groupId.length());
563             TestCaseGroupMap::iterator found = m_testGroups.find(arg);
564             if (found != m_testGroups.end()) {
565                 std::string name = found->first;
566                 TestCaseStructList newList = found->second;
567                 m_testGroups.clear();
568                 m_testGroups[name] = newList;
569             } else {
570                 fprintf(stderr, "Group %s not found\n", arg.c_str());
571                 InvalidArgs();
572                 Usage();
573                 return -1;
574             }
575         } else if (arg == runIgnored) {
576             m_runIgnored = true;
577         } else if (arg == listCmd) {
578             justList = true;
579         } else if (arg == listGroupsCmd) {
580             for (auto &group : m_testGroups) {
581                 printf("GR:%s\n", group.first.c_str());
582             }
583             return 0;
584         } else if (arg.find(listInGroup) == 0) {
585             arg.erase(0, listInGroup.length());
586             for (auto &test : m_testGroups[arg]) {
587                 printf("ID:%s\n", test.name.c_str());
588             }
589             return 0;
590         } else if (arg.find(allowChildLogs) == 0) {
591             arg.erase(0, allowChildLogs.length());
592             m_allowChildLogs = true;
593         } else if (arg == "--help") {
594             showHelp = true;
595         } else if (arg.find(output) == 0) {
596             arg.erase(0, output.length());
597             if (m_collectors.find(arg) != m_collectors.end()) {
598                 InvalidArgs(
599                     "Multiple outputs of the same type are not supported!");
600                 Usage();
601                 return -1;
602             }
603             currentCollector.reset(TestResultsCollectorBase::Create(arg));
604             if (!currentCollector) {
605                 InvalidArgs("Unsupported output type!");
606                 Usage();
607                 return -1;
608             }
609             m_collectors[arg] = currentCollector;
610         } else if (arg.find(regexp) == 0) {
611             arg.erase(0, regexp.length());
612             if (arg.length() == 0) {
613                 InvalidArgs();
614                 Usage();
615                 return -1;
616             }
617
618             if (arg[0] == '\'' && arg[arg.length() - 1] == '\'') {
619                 arg.erase(0);
620                 arg.erase(arg.length() - 1);
621             }
622
623             if (arg.length() == 0) {
624                 InvalidArgs();
625                 Usage();
626                 return -1;
627             }
628
629             pcrecpp::RE re(arg.c_str());
630             for (auto &group : m_testGroups) {
631                 TestCaseStructList newList;
632                 for (auto &tc : group.second)
633                 {
634                     if (re.PartialMatch(tc.name)) {
635                         newList.push_back(tc);
636                     }
637                 }
638                 group.second = newList;
639             }
640         } else if(arg.find(onlyFromXML) == 0) {
641             arg.erase(0, onlyFromXML.length());
642             if (arg.length() == 0) {
643                 InvalidArgs();
644                 Usage();
645                 return -1;
646             }
647
648             if (arg[0] == '\'' && arg[arg.length() - 1] == '\'') {
649                 arg.erase(0);
650                 arg.erase(arg.length() - 1);
651             }
652
653             if (arg.length() == 0) {
654                 InvalidArgs();
655                 Usage();
656                 return -1;
657             }
658
659             xmlFiles.push_back(arg);
660         } else {
661             InvalidArgs();
662             Usage();
663             return -1;
664         }
665     }
666
667     if(!xmlFiles.empty())
668     {
669         if(!filterGroupsByXmls(xmlFiles))
670         {
671             fprintf(stderr, "XML file is not correct\n");
672             return 0;
673         }
674     }
675
676     if(justList)
677     {
678         for (auto &group : m_testGroups) {
679             for (auto &tc : group.second) {
680                 printf("ID:%s:%s\n", group.first.c_str(), tc.name.c_str());
681             }
682         }
683         return 0;
684     }
685
686     currentCollector.reset();
687
688     // Show help
689     if (showHelp) {
690         Usage();
691         return 0;
692     }
693
694     if (m_collectors.empty()) {
695         TestResultsCollectorBasePtr collector(
696             TestResultsCollectorBase::Create("text"));
697         m_collectors["text"] = collector;
698     }
699
700     for (auto &collector : m_collectors) {
701         if (!collector.second->Configure()) {
702             fprintf(stderr, "Could not configure selected output");
703             return 0;
704         }
705     }
706
707     // Run tests
708     RunTests();
709
710     return 0;
711 }
712
713 bool TestRunner::getRunIgnored() const
714 {
715     return m_runIgnored;
716 }
717
718 void TestRunner::Terminate()
719 {
720     m_terminate = true;
721 }
722
723 bool TestRunner::GetAllowChildLogs()
724 {
725     return m_allowChildLogs;
726 }
727
728 }
729 } // namespace DPL