ee1d7c345268226218a51b4e0375470e2a7bf4c0
[platform/core/test/security-tests.git] / src / framework / include / dpl / test / test_runner.h
1 /*
2  * Copyright (c) 2011-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.h
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 header file of test runner
22  */
23
24 #ifndef DPL_TEST_RUNNER_H
25 #define DPL_TEST_RUNNER_H
26
27 #include <chrono>
28 #include <cstdlib>
29 #include <cstring>
30 #include <exception>
31 #include <iostream>
32 #include <list>
33 #include <map>
34 #include <queue>
35 #include <set>
36 #include <sstream>
37 #include <string>
38 #include <vector>
39
40 #include <dpl/atomic.h>
41 #include <dpl/availability.h>
42 #include <dpl/colors.h>
43 #include <dpl/gdbbacktrace.h>
44 #include <dpl/singleton.h>
45 #include <dpl/test/performance_result.h>
46 #include <dpl/test/test_exception.h>
47 #include <dpl/test/test_failed.h>
48 #include <dpl/test/test_ignored.h>
49 #include <dpl/test/test_result.h>
50 #include <dpl/test/test_results_collector.h>
51
52 namespace DPL {
53 namespace Test {
54 class TestRunner
55 {
56     typedef std::map<std::string, TestResultsCollectorBasePtr>
57     TestResultsCollectors;
58     TestResultsCollectors m_collectors;
59
60     std::string m_startTestId;
61     bool m_runIgnored;
62
63     std::queue<std::string> m_failReason;
64
65   public:
66     TestRunner() :
67         m_currentTestCase(nullptr)
68       , m_terminate(false)
69       , m_allowChildLogs(false)
70       , m_deferDeepness(0U)
71       , m_firstDeferredExceptionType(DeferredExceptionType::DEFERRED_FAILED)
72     {}
73
74     void beginPerformance(std::chrono::system_clock::duration maxDurationInMicroseconds);
75     void endPerformance();
76     void setCurrentTestCasePerformanceResult(const PerformanceResultPtr &performance);
77     ConstPerformanceResultPtr getCurrentTestCasePerformanceResult();
78
79     void addFailReason(const std::string &reason);
80
81     typedef void (*TestCase)();
82
83   private:
84     struct TestCaseStruct
85     {
86         std::string name;
87         TestCase proc;
88         PerformanceResultPtr performance;
89
90         bool operator <(const TestCaseStruct &other) const
91         {
92             return name < other.name;
93         }
94
95         bool operator ==(const TestCaseStruct &other) const
96         {
97             return name == other.name;
98         }
99
100         TestCaseStruct(const std::string &n, TestCase p) :
101             name(n),
102             proc(p)
103         {}
104     };
105
106     typedef std::list<TestCaseStruct> TestCaseStructList;
107     typedef std::map<std::string, TestCaseStructList> TestCaseGroupMap;
108     TestCaseGroupMap m_testGroups;
109
110     TestCaseStruct * m_currentTestCase;
111
112     std::string m_currentGroup;
113
114     // Terminate without any logs.
115     // Some test requires to call fork function.
116     // Child process must not produce any logs and should die quietly.
117     bool m_terminate;
118     bool m_allowChildLogs;
119
120     void Banner();
121     void InvalidArgs(const std::string& message = "Invalid arguments!");
122     void Usage();
123
124     bool filterGroupsByXmls(const std::vector<std::string> & files);
125     bool filterByXML(std::map<std::string, bool> & casesMap);
126     void normalizeXMLTag(std::string& str, const std::string& testcase);
127
128     void RunTestCase(const TestCaseStruct& testCase);
129
130     void setCurrentTestCase(TestCaseStruct* testCase);
131     TestCaseStruct *getCurrentTestCase();
132
133     void RunTests();
134
135     std::string getConcatedFailReason(const std::string &reason);
136
137     void CollectResult(const std::string& id, const TestResult &result);
138
139   public:
140     void RegisterTest(const char *testName, TestCase proc);
141     void InitGroup(const char* name);
142
143     int ExecTestRunner(int argc, char *argv[]);
144     typedef std::vector<std::string> ArgsList;
145     int ExecTestRunner(ArgsList args);
146     // The runner will terminate as soon as possible (after current test).
147     void Terminate();
148     bool GetAllowChildLogs();
149
150     void deferFailedException(const DPL::Test::TestFailed &ex);
151     void deferIgnoredException(const DPL::Test::TestIgnored &ex);
152     void deferBegin();
153     void deferEnd();
154
155 private:
156     std::vector<std::string> m_deferredExceptionsMessages;
157     std::size_t m_deferDeepness;
158     enum DeferredExceptionType {
159         DEFERRED_FAILED,
160         DEFERRED_IGNORED,
161     } m_firstDeferredExceptionType;
162     DPL::Test::TestFailed m_firstDeferredFail;
163     DPL::Test::TestIgnored m_firstDeferredIgnore;
164 };
165
166 typedef DPL::Singleton<TestRunner> TestRunnerSingleton;
167 }
168 } // namespace DPL
169
170 #define RUNNER_TEST_GROUP_INIT(GroupName)                                 \
171     static int Static##GroupName##Init()                                  \
172     {                                                                     \
173         DPL::Test::TestRunnerSingleton::Instance().InitGroup(#GroupName); \
174         return 0;                                                         \
175     }                                                                     \
176     const int DPL_UNUSED Static##GroupName##InitVar =                     \
177         Static##GroupName##Init();
178
179 #define RUNNER_TEST(Proc)                                                      \
180     void Proc();                                                               \
181     static int Static##Proc##Init()                                            \
182     {                                                                          \
183         DPL::Test::TestRunnerSingleton::Instance().RegisterTest(#Proc, &Proc); \
184         return 0;                                                              \
185     }                                                                          \
186     const int DPL_UNUSED Static##Proc##InitVar = Static##Proc##Init();         \
187     void Proc()
188
189
190 /**
191  * ASSERT MACROS
192  *
193  * Use them to create assertions in test cases. To do that put them inside test
194  * body. Failing assertion indicates failing test.
195  */
196
197 #define RUNNER_ASSERT_MSG(test, message)                                              \
198     do                                                                                \
199     {                                                                                 \
200         if (!(test))                                                                  \
201         {                                                                             \
202             std::ostringstream assertMsg;                                             \
203             assertMsg << message << DPL::gdbbacktrace();                              \
204             DPL::Test::TestFailed e(#test,                                            \
205                                     __FILE__,                                         \
206                                     __LINE__,                                         \
207                                     assertMsg.str());                                 \
208             if (!std::uncaught_exception())                                           \
209                 throw e;                                                              \
210             DPL::Test::TestRunnerSingleton::Instance().addFailReason(e.GetMessage()); \
211         }                                                                             \
212     } while (0)
213
214 #define RUNNER_ASSERT_ERRNO_MSG(test, message)                                        \
215     do                                                                                \
216     {                                                                                 \
217         if (!(test))                                                                  \
218         {                                                                             \
219             const char *err = strerror(errno);                                        \
220             std::ostringstream assertMsg;                                             \
221             assertMsg << message;                                                     \
222             if (!assertMsg.str().empty())                                             \
223                 assertMsg << ". ";                                                    \
224             assertMsg << err << DPL::gdbbacktrace();                                  \
225             DPL::Test::TestFailed e(#test,                                            \
226                                     __FILE__,                                         \
227                                     __LINE__,                                         \
228                                     assertMsg.str());                                 \
229             if (!std::uncaught_exception())                                           \
230                 throw e;                                                              \
231             DPL::Test::TestRunnerSingleton::Instance().addFailReason(e.GetMessage()); \
232         }                                                                             \
233     } while (0)
234
235 #define RUNNER_ASSERT_ERRNO(test) \
236     RUNNER_ASSERT_ERRNO_MSG(test, "")
237
238 #define RUNNER_FAIL_MSG(message) \
239     RUNNER_ASSERT_MSG(false, message)
240
241 #define RUNNER_ASSERT(test) \
242     RUNNER_ASSERT_MSG(test, "")
243
244 /**
245  * IGNORE MACRO
246  *
247  * When test reaches this macro call, its furhter code will be ignored.
248  * To ignore whole test, put this macro call at the beginning of this tests
249  * body.
250  */
251
252 #define RUNNER_IGNORED_MSG(message)                    \
253     do                                                 \
254     {                                                  \
255         std::ostringstream assertMsg;                  \
256         assertMsg << message;                          \
257         throw DPL::Test::TestIgnored(assertMsg.str()); \
258     } while (0)
259
260 /**
261  * PERF MACROS
262  *
263  * Use these macros to do the time measurement. The first macro will start time measurement,
264  * the second will gather the result. These macros can be used only once per test-case.
265  * The result of time measurement will be displayed only if the test will pass.
266  * Notice that these macros will work only if will be used in parent process. If these
267  * macros will be used in child process then there will be no time measure results printed.
268  * This macro in multiprocess tests has effect only if used in parent process. This macro
269  * used in child process in multiprocess test has no effect.
270  * The precision of measurement is 1 microsecond - the smallest time value that can be
271  * measured is 0.000001s.
272  * The time measure results will be printed only specific output format:
273  *     - text
274  *     - html
275  *     - xml
276  */
277
278 #define RUNNER_PERF_TEST_BEGIN(maxTime)                                                \
279     do {                                                                               \
280         DPL::Test::TestRunnerSingleton::Instance().beginPerformance(                   \
281             std::chrono::microseconds{static_cast<long long int>(maxTime*1000000.0)}); \
282     } while (0)
283
284 #define RUNNER_PERF_TEST_END()                                       \
285     do {                                                             \
286         DPL::Test::TestRunnerSingleton::Instance().endPerformance(); \
287     } while (0)
288
289 /**
290  * MSG MACROS
291  *
292  * Use these macros to print error messages during test run time
293  */
294
295 #define RUNNER_ERROR_MSG(message)                             \
296     do {                                                      \
297         std::cerr << DPL::Colors::Text::RED_BEGIN << message  \
298                   << DPL::Colors::Text::RED_END << std::endl; \
299     } while (0)
300
301 /**
302  * DEFER MACROS
303  *
304  * Use them to defer fails and ignores in test cases.
305  * Some code constructions disallow to throw. Such places can be surrounded
306  * with RUNNER_DEFER_SCOPE macro. RUNNER_DEFER_TRYCATCH macro can be used to catch possibly thrown
307  * exceptions within such scope. Possibly catched exceptions will be rethrown
308  * when leaving RUNNER_DEFER_SCOPE scope.
309  * Macros can be safely nested.
310  */
311
312
313 #define RUNNER_DEFER_TRYCATCH(scope)                                              \
314     do {                                                                          \
315         try                                                                       \
316         {                                                                         \
317             scope                                                                 \
318         }                                                                         \
319         catch (const DPL::Test::TestFailed &ex)                                   \
320         {                                                                         \
321             DPL::Test::TestRunnerSingleton::Instance().deferFailedException(ex);  \
322         }                                                                         \
323         catch (const DPL::Test::TestIgnored &ex)                                  \
324         {                                                                         \
325             DPL::Test::TestRunnerSingleton::Instance().deferIgnoredException(ex); \
326         }                                                                         \
327     } while (0)                                                                   \
328
329 #define RUNNER_DEFER_SCOPE(scope)                                \
330     do {                                                         \
331         DPL::Test::TestRunnerSingleton::Instance().deferBegin(); \
332         scope                                                    \
333         DPL::Test::TestRunnerSingleton::Instance().deferEnd();   \
334     } while (0)                                                  \
335
336 #endif // DPL_TEST_RUNNER_H