1 /*
2 * Copyright (C) 2017 The Android Open Source Project
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 #include "perfetto/ext/base/thread_checker.h"
18
19 #include <functional>
20 #include <memory>
21 #include <thread>
22
23 #include "test/gtest_and_gmock.h"
24
25 namespace perfetto {
26 namespace base {
27 namespace {
28
RunOnThread(std::function<bool (void)> closure)29 bool RunOnThread(std::function<bool(void)> closure) {
30 bool res = false;
31 std::thread thread([&res, &closure] { res = closure(); });
32 thread.join();
33 return res;
34 }
35
TEST(ThreadCheckerTest,Basic)36 TEST(ThreadCheckerTest, Basic) {
37 ThreadChecker thread_checker;
38 ASSERT_TRUE(thread_checker.CalledOnValidThread());
39 bool res = RunOnThread(
40 [&thread_checker] { return thread_checker.CalledOnValidThread(); });
41 ASSERT_TRUE(thread_checker.CalledOnValidThread());
42 ASSERT_FALSE(res);
43 }
44
TEST(ThreadCheckerTest,Detach)45 TEST(ThreadCheckerTest, Detach) {
46 ThreadChecker thread_checker;
47 ASSERT_TRUE(thread_checker.CalledOnValidThread());
48 thread_checker.DetachFromThread();
49 bool res = RunOnThread(
50 [&thread_checker] { return thread_checker.CalledOnValidThread(); });
51 ASSERT_TRUE(res);
52 ASSERT_FALSE(thread_checker.CalledOnValidThread());
53 }
54
TEST(ThreadCheckerTest,CopyConstructor)55 TEST(ThreadCheckerTest, CopyConstructor) {
56 ThreadChecker thread_checker;
57 ThreadChecker copied_thread_checker = thread_checker;
58 ASSERT_TRUE(thread_checker.CalledOnValidThread());
59 ASSERT_TRUE(copied_thread_checker.CalledOnValidThread());
60 bool res = RunOnThread([&copied_thread_checker] {
61 return copied_thread_checker.CalledOnValidThread();
62 });
63 ASSERT_FALSE(res);
64
65 copied_thread_checker.DetachFromThread();
66 res = RunOnThread([&thread_checker, &copied_thread_checker] {
67 return copied_thread_checker.CalledOnValidThread() &&
68 !thread_checker.CalledOnValidThread();
69 });
70 ASSERT_TRUE(res);
71 }
72
73 } // namespace
74 } // namespace base
75 } // namespace perfetto
76