fix flaky ConnectTFOTimeout and ConnectTFOFallbackTimeout tests
[folly.git] / folly / io / async / test / ScopedEventBaseThreadTest.cpp
1 /*
2  * Copyright 2016 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 #include <folly/Baton.h>
21
22 #include <gtest/gtest.h>
23
24 using namespace std;
25 using namespace std::chrono;
26 using namespace folly;
27
28 class ScopedEventBaseThreadTest : public testing::Test {};
29
30 TEST_F(ScopedEventBaseThreadTest, example) {
31   ScopedEventBaseThread sebt;
32
33   Baton<> done;
34   sebt.getEventBase()->runInEventBaseThread([&] { done.post(); });
35   done.timed_wait(steady_clock::now() + milliseconds(100));
36 }
37
38 TEST_F(ScopedEventBaseThreadTest, start_stop) {
39   ScopedEventBaseThread sebt(false);
40
41   for (size_t i = 0; i < 4; ++i) {
42     EXPECT_EQ(nullptr, sebt.getEventBase());
43     sebt.start();
44     EXPECT_NE(nullptr, sebt.getEventBase());
45
46     Baton<> done;
47     sebt.getEventBase()->runInEventBaseThread([&] { done.post(); });
48     done.timed_wait(steady_clock::now() + milliseconds(100));
49
50     EXPECT_NE(nullptr, sebt.getEventBase());
51     sebt.stop();
52     EXPECT_EQ(nullptr, sebt.getEventBase());
53   }
54 }
55
56 TEST_F(ScopedEventBaseThreadTest, move) {
57   auto sebt0 = ScopedEventBaseThread();
58   auto sebt1 = std::move(sebt0);
59   auto sebt2 = std::move(sebt1);
60
61   EXPECT_EQ(nullptr, sebt0.getEventBase());
62   EXPECT_EQ(nullptr, sebt1.getEventBase());
63   EXPECT_NE(nullptr, sebt2.getEventBase());
64
65   Baton<> done;
66   sebt2.getEventBase()->runInEventBaseThread([&] { done.post(); });
67   done.timed_wait(steady_clock::now() + milliseconds(100));
68 }
69
70 TEST_F(ScopedEventBaseThreadTest, self_move) {
71   ScopedEventBaseThread sebt0;
72   auto sebt = std::move(sebt0);
73
74   EXPECT_NE(nullptr, sebt.getEventBase());
75
76   Baton<> done;
77   sebt.getEventBase()->runInEventBaseThread([&] { done.post(); });
78   done.timed_wait(steady_clock::now() + milliseconds(100));
79 }
80
81 TEST_F(ScopedEventBaseThreadTest, manager) {
82   EventBaseManager ebm;
83   ScopedEventBaseThread sebt(&ebm);
84   auto sebt_eb = sebt.getEventBase();
85   auto ebm_eb = (EventBase*)nullptr;
86   sebt_eb->runInEventBaseThreadAndWait([&] {
87       ebm_eb = ebm.getEventBase();
88   });
89   EXPECT_EQ(uintptr_t(sebt_eb), uintptr_t(ebm_eb));
90 }