Move non-template functions to timeout.cpp file
[platform/core/test/security-tests.git] / src / common / timeout.h
1 /*
2  * Copyright (c) 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        timeout.h
18  * @author      Lukasz Wojciechowski <l.wojciechow@partner.samsung.com>
19  * @brief       Definition of time limited execution of synchronous functions
20  */
21
22 #ifndef TIMEOUT_H
23 #define TIMEOUT_H
24
25 #include <chrono>
26 #include <functional>
27 #include <future>
28 #include <type_traits>
29 #include <utility>
30
31 #include <dpl/test/test_runner.h>
32
33 namespace Timeout {
34
35 template <class Rep, class Period>
36 using Timeout = std::chrono::duration<Rep, Period>;
37
38 typedef std::function<void(void)> CancelFunction;
39
40 enum ExpectMode {
41     FINISHED,
42     TIMEOUT,
43     IGNORE,
44 };
45
46 std::ostream& operator<<(std::ostream& os, const std::future_status &status);
47
48 template <class Rep, class Period, class F, class... Args>
49     typename std::result_of<F(Args...)>::type
50     callAndWait(const Timeout<Rep, Period> &timeout,
51                  ExpectMode expect,
52                  CancelFunction cancelFunction,
53                  F&& function,
54                  Args&&... args) {
55
56     auto fut = std::async(std::launch::async, function, std::forward<Args>(args)...);
57     std::future_status status = fut.wait_for(timeout);
58
59     if (status == std::future_status::timeout && cancelFunction)
60         cancelFunction();
61
62     switch (expect) {
63         case FINISHED:
64             RUNNER_ASSERT_MSG(status == std::future_status::ready,
65                                  "expected future status is " << std::future_status::ready
66                                      << " received future status is " << status);
67             break;
68         case TIMEOUT:
69             RUNNER_ASSERT_MSG(status == std::future_status::timeout,
70                                  "expected future status is " << std::future_status::timeout
71                                      << " received future status is " << status);
72             break;
73         case IGNORE:
74             break;
75     }
76
77     return fut.get();
78 }
79
80 } // namespace Timeout
81
82 #endif // TIMEOUT_H