Allow to run tests without arguments
[platform/core/test/security-tests.git] / tests / framework / src / test_runner.cpp
1 /*
2  * Copyright (c) 2011 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 (NULL == 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(), NULL, 0);
167             if (doc == NULL) {
168                 ThrowMsg(XMLError, "File Problem");
169             } else {
170                 //context
171                 xpathCtx = xmlXPathNewContext(doc);
172                 if (xpathCtx == NULL) {
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 == NULL)
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                       "",
255                       TestResultsCollectorBase::FailStatus::FAILED,
256                       e.GetMessage());
257
258         setCurrentTestCase(NULL);
259         return FAILED;
260     } catch (const Ignored &e) {
261         if (m_runIgnored) {
262             // Simple test have to be implemented
263             CollectResult(testCase.name,
264                           "",
265                           TestResultsCollectorBase::FailStatus::IGNORED,
266                           e.GetMessage());
267         }
268
269         setCurrentTestCase(NULL);
270         return IGNORED;
271     } catch (const DPL::Exception &e) {
272         // DPL exception failure
273         CollectResult(testCase.name,
274                       "",
275                       TestResultsCollectorBase::FailStatus::INTERNAL,
276                       "DPL exception:" + e.GetMessage());
277
278         setCurrentTestCase(NULL);
279         return FAILED;
280     } catch (const std::exception &) {
281         // std exception failure
282         CollectResult(testCase.name,
283                       "",
284                       TestResultsCollectorBase::FailStatus::INTERNAL,
285                       "std exception");
286
287         setCurrentTestCase(NULL);
288         return FAILED;
289     } catch (...) {
290         // Unknown exception failure
291         CollectResult(testCase.name,
292                       "",
293                       TestResultsCollectorBase::FailStatus::INTERNAL,
294                       "unknown exception");
295
296         setCurrentTestCase(NULL);
297         return FAILED;
298     }
299
300     CollectResult(testCase.name,
301                   "",
302                   TestResultsCollectorBase::FailStatus::NONE,
303                   "",
304                   testCase.m_isPerformanceTest,
305                   testCase.m_performanceTestDurationTime,
306                   testCase.m_performanceMaxTime);
307     setCurrentTestCase(NULL);
308
309     // Everything OK
310     return PASS;
311 }
312
313 void TestRunner::RunTests()
314 {
315     using namespace DPL::Colors::Text;
316
317     Banner();
318     for (auto &collector : m_collectors) {
319         collector.second->Start();
320     }
321
322     unsigned count = 0;
323     for (auto &group : m_testGroups) {
324         count += group.second.size();
325     }
326     fprintf(stderr, "%sFound %d testcases...%s\n", GREEN_BEGIN, count, GREEN_END);
327     fprintf(stderr, "%s%s%s\n", GREEN_BEGIN, "Running tests...", GREEN_END);
328     for (auto &group : m_testGroups) {
329         TestCaseStructList list = group.second;
330         if (!list.empty()) {
331             for (auto &collector : m_collectors) {
332                 collector.second->CollectCurrentTestGroupName(group.first);
333             }
334             list.sort();
335
336             for (TestCaseStructList::const_iterator iterator = list.begin();
337                  iterator != list.end();
338                  ++iterator)
339             {
340                 TestCaseStruct test = *iterator;
341                 if (m_startTestId == test.name) {
342                     m_startTestId = "";
343                 }
344
345                 if (m_startTestId.empty()) {
346                     RunTestCase(test);
347                 }
348                 if (m_terminate == true) {
349                     // Terminate quietly without any logs
350                     return;
351                 }
352             }
353         }
354     }
355
356     std::for_each(m_collectors.begin(),
357                   m_collectors.end(),
358                   [] (const TestResultsCollectors::value_type & collector)
359                   {
360                       collector.second->Finish();
361                   });
362
363     // Finished
364     fprintf(stderr, "%s%s%s\n\n", GREEN_BEGIN, "Finished", GREEN_END);
365 }
366
367 TestRunner::TestCaseStruct *TestRunner::getCurrentTestCase()
368 {
369     return m_currentTestCase;
370 }
371
372 void TestRunner::setCurrentTestCase(TestCaseStruct* testCase)
373 {
374     m_currentTestCase = testCase;
375 }
376
377 void TestRunner::beginPerformanceTestTime(std::chrono::system_clock::duration maxTimeInMicroseconds)
378 {
379     TestCaseStruct* testCase = getCurrentTestCase();
380     if (!testCase)
381         return;
382
383     testCase->m_isPerformanceTest = true;
384     testCase->m_performanceMaxTime = maxTimeInMicroseconds;
385     testCase->m_performanceTestStartTime = std::chrono::system_clock::now();
386
387     // Set result to 0 microseconds. Display 0ms result when end macro is missing.
388     testCase->m_performanceTestDurationTime = std::chrono::microseconds::zero();
389 }
390
391 void TestRunner::endPerformanceTestTime()
392 {
393     TestCaseStruct* testCase = getCurrentTestCase();
394     if (!testCase)
395         return;
396
397     testCase->m_performanceTestDurationTime = std::chrono::system_clock::now() -
398             testCase->m_performanceTestStartTime;
399 }
400
401 void TestRunner::getCurrentTestCasePerformanceResult(bool& isPerformanceTest,
402                                                      std::chrono::system_clock::duration& result,
403                                                      std::chrono::system_clock::duration& resultMax)
404 {
405     TestCaseStruct* testCase = getCurrentTestCase();
406     if (!testCase || !(testCase->m_isPerformanceTest)){
407         isPerformanceTest = false;
408         return;
409     }
410
411     isPerformanceTest = testCase->m_isPerformanceTest;
412     result = testCase->m_performanceTestDurationTime;
413     resultMax = testCase->m_performanceMaxTime;
414 }
415
416 void TestRunner::setCurrentTestCasePerformanceResult(bool isPerformanceTest,
417                                                      std::chrono::system_clock::duration result,
418                                                      std::chrono::system_clock::duration resultMax)
419 {
420     TestCaseStruct* testCase = getCurrentTestCase();
421     if (!testCase)
422         return;
423
424     testCase->m_isPerformanceTest = isPerformanceTest;
425     testCase->m_performanceTestDurationTime = result;
426     testCase->m_performanceMaxTime = resultMax;
427 }
428
429
430 void TestRunner::CollectResult(
431     const std::string& id,
432     const std::string& description,
433     const TestResultsCollectorBase::FailStatus::Type status,
434     const std::string& reason,
435     const bool& isPerformanceTest,
436     const std::chrono::system_clock::duration& performanceTestDurationTime,
437     const std::chrono::system_clock::duration& performanceMaxTime)
438 {
439     std::for_each(m_collectors.begin(),
440                   m_collectors.end(),
441                   [&](const TestResultsCollectors::value_type & collector)
442                   {
443                       collector.second->CollectResult(id,
444                                                       description,
445                                                       status,
446                                                       reason,
447                                                       isPerformanceTest,
448                                                       performanceTestDurationTime,
449                                                       performanceMaxTime);
450                   });
451 }
452
453 void TestRunner::Banner()
454 {
455     using namespace DPL::Colors::Text;
456     fprintf(stderr,
457             "%s%s%s\n",
458             BOLD_GREEN_BEGIN,
459             "DPL tests runner",
460             BOLD_GREEN_END);
461     fprintf(stderr,
462             "%s%s%s%s\n\n",
463             GREEN_BEGIN,
464             "Build: ",
465             __TIMESTAMP__,
466             GREEN_END);
467 }
468
469 void TestRunner::InvalidArgs(const std::string& message)
470 {
471     using namespace DPL::Colors::Text;
472     fprintf(stderr,
473             "%s%s%s\n",
474             BOLD_RED_BEGIN,
475             message.c_str(),
476             BOLD_RED_END);
477 }
478
479 void TestRunner::Usage()
480 {
481     fprintf(stderr, "Usage: runner [options]\n\n");
482     fprintf(stderr, "Output type:\n");
483     fprintf(stderr, "  --output=<output type> --output=<output type> ...\n");
484     fprintf(stderr, "\n  possible output types:\n");
485     for (std::string &type : TestResultsCollectorBase::GetCollectorsNames()) {
486         fprintf(stderr, "    --output=%s\n", type.c_str());
487     }
488     fprintf(stderr, "\n  example:\n");
489     fprintf(stderr,
490             "    test-binary --output=text --output=xml --file=output.xml\n\n");
491     fprintf(stderr, "Other parameters:\n");
492     fprintf(stderr,
493             "  --regexp='regexp'\t Only selected tests"
494             " which names match regexp run\n\n");
495     fprintf(stderr, "  --start=<test id>\tStart from concrete test id");
496     fprintf(stderr, "  --group=<group name>\t Run tests only from one group\n");
497     fprintf(stderr, "  --runignored\t Run also ignored tests\n");
498     fprintf(stderr, "  --list\t Show a list of Test IDs\n");
499     fprintf(stderr, "  --listgroups\t Show a list of Test Group names \n");
500     fprintf(stderr, "  --only-from-xml=<xml file>\t Run only testcases specified in XML file \n"
501                     "       XML name is taken from attribute id=\"part1_part2\" as whole.\n"
502                     "       If part1 is not found (no _) then it is implicitily "
503                            "set according to suite part1 from binary tests\n");
504     fprintf(
505         stderr,
506         "  --listingroup=<group name>\t Show a list of Test IDS in one group\n");
507     fprintf(stderr, "  --allowchildlogs\t Allow to print logs from child process on screen.\n");
508     fprintf(stderr, "       When active child process will be able to print logs on stdout and stderr.\n");
509     fprintf(stderr, "       Both descriptors will be closed after test.\n");
510     fprintf(stderr, "  --help\t This help\n\n");
511     std::for_each(m_collectors.begin(),
512                   m_collectors.end(),
513                   [] (const TestResultsCollectors::value_type & collector)
514                   {
515                       fprintf(stderr,
516                               "Output %s has specific args:\n",
517                               collector.first.c_str());
518                       fprintf(stderr,
519                               "%s\n",
520                               collector.second->
521                                   CollectorSpecificHelp().c_str());
522                   });
523     fprintf(stderr, "For bug reporting, please write to:\n");
524     fprintf(stderr, "<p.dobrowolsk@samsung.com>\n");
525 }
526
527 int TestRunner::ExecTestRunner(int argc, char *argv[])
528 {
529     std::vector<std::string> args;
530     for (int i = 0; i < argc; ++i) {
531         args.push_back(argv[i]);
532     }
533     return ExecTestRunner(args);
534 }
535
536 void TestRunner::MarkAssertion()
537 {
538     ++m_totalAssertions;
539 }
540
541 int TestRunner::ExecTestRunner(ArgsList args)
542 {
543     m_runIgnored = false;
544     // Parse command line
545
546     args.erase(args.begin());
547
548     bool showHelp = false;
549     bool justList = false;
550     std::vector<std::string> xmlFiles;
551
552     TestResultsCollectorBasePtr currentCollector;
553
554     // Parse each argument
555     for(std::string &arg : args)
556     {
557         const std::string regexp = "--regexp=";
558         const std::string output = "--output=";
559         const std::string groupId = "--group=";
560         const std::string runIgnored = "--runignored";
561         const std::string listCmd = "--list";
562         const std::string startCmd = "--start=";
563         const std::string listGroupsCmd = "--listgroups";
564         const std::string listInGroup = "--listingroup=";
565         const std::string allowChildLogs = "--allowchildlogs";
566         const std::string onlyFromXML = "--only-from-xml=";
567
568         if (currentCollector) {
569             if (currentCollector->ParseCollectorSpecificArg(arg)) {
570                 continue;
571             }
572         }
573
574         if (arg.find(startCmd) == 0) {
575             arg.erase(0, startCmd.length());
576             for (auto &group : m_testGroups) {
577                 for (auto &tc : group.second) {
578                     if (tc.name == arg) {
579                         m_startTestId = arg;
580                         break;
581                     }
582                 }
583                 if (!m_startTestId.empty()) {
584                     break;
585                 }
586             }
587             if (!m_startTestId.empty()) {
588                 continue;
589             }
590             InvalidArgs();
591             fprintf(stderr, "Start test id has not been found\n");
592             Usage();
593             return 0;
594         } else if (arg.find(groupId) == 0) {
595             arg.erase(0, groupId.length());
596             TestCaseGroupMap::iterator found = m_testGroups.find(arg);
597             if (found != m_testGroups.end()) {
598                 std::string name = found->first;
599                 TestCaseStructList newList = found->second;
600                 m_testGroups.clear();
601                 m_testGroups[name] = newList;
602             } else {
603                 fprintf(stderr, "Group %s not found\n", arg.c_str());
604                 InvalidArgs();
605                 Usage();
606                 return -1;
607             }
608         } else if (arg == runIgnored) {
609             m_runIgnored = true;
610         } else if (arg == listCmd) {
611             justList = true;
612         } else if (arg == listGroupsCmd) {
613             for (auto &group : m_testGroups) {
614                 printf("GR:%s\n", group.first.c_str());
615             }
616             return 0;
617         } else if (arg.find(listInGroup) == 0) {
618             arg.erase(0, listInGroup.length());
619             for (auto &test : m_testGroups[arg]) {
620                 printf("ID:%s\n", test.name.c_str());
621             }
622             return 0;
623         } else if (arg.find(allowChildLogs) == 0) {
624             arg.erase(0, allowChildLogs.length());
625             m_allowChildLogs = true;
626         } else if (arg == "--help") {
627             showHelp = true;
628         } else if (arg.find(output) == 0) {
629             arg.erase(0, output.length());
630             if (m_collectors.find(arg) != m_collectors.end()) {
631                 InvalidArgs(
632                     "Multiple outputs of the same type are not supported!");
633                 Usage();
634                 return -1;
635             }
636             currentCollector.reset(TestResultsCollectorBase::Create(arg));
637             if (!currentCollector) {
638                 InvalidArgs("Unsupported output type!");
639                 Usage();
640                 return -1;
641             }
642             m_collectors[arg] = currentCollector;
643         } else if (arg.find(regexp) == 0) {
644             arg.erase(0, regexp.length());
645             if (arg.length() == 0) {
646                 InvalidArgs();
647                 Usage();
648                 return -1;
649             }
650
651             if (arg[0] == '\'' && arg[arg.length() - 1] == '\'') {
652                 arg.erase(0);
653                 arg.erase(arg.length() - 1);
654             }
655
656             if (arg.length() == 0) {
657                 InvalidArgs();
658                 Usage();
659                 return -1;
660             }
661
662             pcrecpp::RE re(arg.c_str());
663             for (auto &group : m_testGroups) {
664                 TestCaseStructList newList;
665                 for (auto &tc : group.second)
666                 {
667                     if (re.PartialMatch(tc.name)) {
668                         newList.push_back(tc);
669                     }
670                 }
671                 group.second = newList;
672             }
673         } else if(arg.find(onlyFromXML) == 0) {
674             arg.erase(0, onlyFromXML.length());
675             if (arg.length() == 0) {
676                 InvalidArgs();
677                 Usage();
678                 return -1;
679             }
680
681             if (arg[0] == '\'' && arg[arg.length() - 1] == '\'') {
682                 arg.erase(0);
683                 arg.erase(arg.length() - 1);
684             }
685
686             if (arg.length() == 0) {
687                 InvalidArgs();
688                 Usage();
689                 return -1;
690             }
691
692             xmlFiles.push_back(arg);
693         } else {
694             InvalidArgs();
695             Usage();
696             return -1;
697         }
698     }
699
700     if(!xmlFiles.empty())
701     {
702         if(!filterGroupsByXmls(xmlFiles))
703         {
704             fprintf(stderr, "XML file is not correct\n");
705             return 0;
706         }
707     }
708
709     if(justList)
710     {
711         for (auto &group : m_testGroups) {
712             for (auto &tc : group.second) {
713                 printf("ID:%s:%s\n", group.first.c_str(), tc.name.c_str());
714             }
715         }
716         return 0;
717     }
718
719     currentCollector.reset();
720
721     // Show help
722     if (showHelp) {
723         Usage();
724         return 0;
725     }
726
727     if (m_collectors.empty()) {
728         TestResultsCollectorBasePtr collector(
729             TestResultsCollectorBase::Create("text"));
730         m_collectors["text"] = collector;
731     }
732
733     for (auto &collector : m_collectors) {
734         if (!collector.second->Configure()) {
735             fprintf(stderr, "Could not configure selected output");
736             return 0;
737         }
738     }
739
740     // Run tests
741     RunTests();
742
743     return 0;
744 }
745
746 bool TestRunner::getRunIgnored() const
747 {
748     return m_runIgnored;
749 }
750
751 void TestRunner::Terminate()
752 {
753     m_terminate = true;
754 }
755
756 bool TestRunner::GetAllowChildLogs()
757 {
758     return m_allowChildLogs;
759 }
760
761 }
762 } // namespace DPL