2017
[folly.git] / folly / io / async / test / ScopedEventBaseThreadTest.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
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 <folly/io/async/ScopedEventBaseThread.h>
18
19 #include <chrono>
20
21 #include <folly/Baton.h>
22 #include <folly/Optional.h>
23 #include <folly/io/async/EventBaseManager.h>
24 #include <folly/portability/GTest.h>
25
26 using namespace std;
27 using namespace std::chrono;
28 using namespace folly;
29
30 class ScopedEventBaseThreadTest : public testing::Test {};
31
32 TEST_F(ScopedEventBaseThreadTest, example) {
33   ScopedEventBaseThread sebt;
34
35   Baton<> done;
36   sebt.getEventBase()->runInEventBaseThread([&] { done.post(); });
37   ASSERT_TRUE(done.timed_wait(seconds(1)));
38 }
39
40 TEST_F(ScopedEventBaseThreadTest, default_manager) {
41   auto ebm = EventBaseManager::get();
42   ScopedEventBaseThread sebt;
43   auto sebt_eb = sebt.getEventBase();
44   auto ebm_eb = static_cast<EventBase*>(nullptr);
45   sebt_eb->runInEventBaseThreadAndWait([&] { ebm_eb = ebm->getEventBase(); });
46   EXPECT_EQ(uintptr_t(sebt_eb), uintptr_t(ebm_eb));
47 }
48
49 TEST_F(ScopedEventBaseThreadTest, custom_manager) {
50   EventBaseManager ebm;
51   ScopedEventBaseThread sebt(&ebm);
52   auto sebt_eb = sebt.getEventBase();
53   auto ebm_eb = static_cast<EventBase*>(nullptr);
54   sebt_eb->runInEventBaseThreadAndWait([&] { ebm_eb = ebm.getEventBase(); });
55   EXPECT_EQ(uintptr_t(sebt_eb), uintptr_t(ebm_eb));
56 }
57
58 TEST_F(ScopedEventBaseThreadTest, eb_dtor_in_io_thread) {
59   Optional<ScopedEventBaseThread> sebt;
60   sebt.emplace();
61   auto const io_thread_id = sebt->getThreadId();
62   EXPECT_NE(this_thread::get_id(), io_thread_id) << "sanity";
63
64   auto const eb = sebt->getEventBase();
65   thread::id eb_dtor_thread_id;
66   eb->runOnDestruction(new EventBase::FunctionLoopCallback(
67       [&] { eb_dtor_thread_id = this_thread::get_id(); }));
68   sebt.clear();
69   EXPECT_EQ(io_thread_id, eb_dtor_thread_id);
70 }