Release 0.1.66
[platform/core/security/key-manager.git] / unit-tests / test_watched-thread.h
1 /*
2  *  Copyright (c) 2000 - 2014 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_watched-thread.h
18  * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
19  * @version    1.0
20  */
21
22 #pragma once
23
24 #include <functional>
25 #include <thread>
26 #include <utility>
27 #include <boost/test/test_tools.hpp>
28 #include <dpl/exception.h>
29 #include <noncopyable.h>
30
31 // Error handling in threads
32 DECLARE_EXCEPTION_TYPE(CKM::Exception, ThreadErrorMessage)
33
34 template <typename F, typename... Args>
35 class WatchedThread {
36 public:
37         // can't use rreferences for Args because std::thread needs to copy all arguments
38         explicit WatchedThread(F &&function, const Args &... args) :
39                 m_function(std::move(function)),
40                 m_thread(&WatchedThread::Wrapper, this, args...) {}
41
42         ~WatchedThread()
43         {
44                 m_thread.join();
45
46                 if (!m_error.empty())
47                         BOOST_FAIL(m_error);
48         }
49
50         NONCOPYABLE(WatchedThread);
51
52         WatchedThread(WatchedThread &&) = default;
53         WatchedThread &operator=(WatchedThread &&) = default;
54
55 protected:
56         void Wrapper(const Args &... args)
57         {
58                 try {
59                         m_function(args...);
60                 } catch (const ThreadErrorMessage &e) {
61                         m_error = e.DumpToString();
62                 }
63         }
64
65         std::string m_error;
66         F m_function;
67         std::thread m_thread;
68 };
69
70 template <typename F, typename... Args>
71 WatchedThread<F, Args...> CreateWatchedThread(F &&function,
72                 const Args &... args)
73 {
74         return WatchedThread<F, Args...>(std::move(function), args...);
75 }
76
77 #define THREAD_REQUIRE_MESSAGE(expr, message)      \
78         do {                                           \
79                 if (!(expr))                               \
80                         ThrowMsg(ThreadErrorMessage, message); \
81         } while (false);