Make CryptoAlgorithm copyable.
[platform/core/security/key-manager.git] / 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
43     ~WatchedThread() {
44         m_thread.join();
45         if (!m_error.empty())
46             BOOST_FAIL(m_error);
47     }
48
49     NONCOPYABLE(WatchedThread);
50
51     WatchedThread(WatchedThread&&) = default;
52     WatchedThread& operator=(WatchedThread&&) = default;
53
54 protected:
55
56     void Wrapper(const Args&... args) {
57         try {
58             m_function(args...);
59         } catch (const ThreadErrorMessage& e) {
60             m_error = e.DumpToString();
61         }
62     }
63
64     std::string m_error;
65     F m_function;
66     std::thread m_thread;
67 };
68
69 template <typename F, typename... Args>
70 WatchedThread<F, Args...> CreateWatchedThread(F&& function, const Args&... args)
71 {
72     return WatchedThread<F, Args...>(std::move(function), args...);
73 }
74
75 #define THREAD_REQUIRE_MESSAGE(expr, message)                \
76     do {                                                     \
77         if (!(expr))                                         \
78             ThrowMsg( ThreadErrorMessage, message);          \
79     } while (false);