2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <folly/io/async/ScopedEventBaseThread.h>
20 #include <folly/Baton.h>
21 #include <folly/portability/GTest.h>
24 using namespace std::chrono;
25 using namespace folly;
27 class ScopedEventBaseThreadTest : public testing::Test {};
29 TEST_F(ScopedEventBaseThreadTest, example) {
30 ScopedEventBaseThread sebt;
33 sebt.getEventBase()->runInEventBaseThread([&] { done.post(); });
34 ASSERT_TRUE(done.timed_wait(seconds(1)));
37 TEST_F(ScopedEventBaseThreadTest, start_stop) {
38 ScopedEventBaseThread sebt(false);
40 for (size_t i = 0; i < 4; ++i) {
41 EXPECT_EQ(nullptr, sebt.getEventBase());
43 EXPECT_NE(nullptr, sebt.getEventBase());
46 sebt.getEventBase()->runInEventBaseThread([&] { done.post(); });
47 ASSERT_TRUE(done.timed_wait(seconds(1)));
49 EXPECT_NE(nullptr, sebt.getEventBase());
51 EXPECT_EQ(nullptr, sebt.getEventBase());
55 TEST_F(ScopedEventBaseThreadTest, move) {
56 auto sebt0 = ScopedEventBaseThread();
57 auto sebt1 = std::move(sebt0);
58 auto sebt2 = std::move(sebt1);
60 EXPECT_EQ(nullptr, sebt0.getEventBase());
61 EXPECT_EQ(nullptr, sebt1.getEventBase());
62 EXPECT_NE(nullptr, sebt2.getEventBase());
65 sebt2.getEventBase()->runInEventBaseThread([&] { done.post(); });
66 ASSERT_TRUE(done.timed_wait(seconds(1)));
69 TEST_F(ScopedEventBaseThreadTest, self_move) {
70 ScopedEventBaseThread sebt0;
71 auto sebt = std::move(sebt0);
73 EXPECT_NE(nullptr, sebt.getEventBase());
76 sebt.getEventBase()->runInEventBaseThread([&] { done.post(); });
77 ASSERT_TRUE(done.timed_wait(seconds(1)));
80 TEST_F(ScopedEventBaseThreadTest, default_manager) {
81 auto ebm = EventBaseManager::get();
82 ScopedEventBaseThread sebt;
83 auto sebt_eb = sebt.getEventBase();
84 auto ebm_eb = static_cast<EventBase*>(nullptr);
85 sebt_eb->runInEventBaseThreadAndWait([&] { ebm_eb = ebm->getEventBase(); });
86 EXPECT_EQ(uintptr_t(sebt_eb), uintptr_t(ebm_eb));
89 TEST_F(ScopedEventBaseThreadTest, custom_manager) {
91 ScopedEventBaseThread sebt(&ebm);
92 auto sebt_eb = sebt.getEventBase();
93 auto ebm_eb = static_cast<EventBase*>(nullptr);
94 sebt_eb->runInEventBaseThreadAndWait([&] { ebm_eb = ebm.getEventBase(); });
95 EXPECT_EQ(uintptr_t(sebt_eb), uintptr_t(ebm_eb));