4567b93c3f1b70558e29d4e477f1af7e252634ec
[folly.git] / folly / futures / test / TimekeeperTest.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/futures/Timekeeper.h>
18 #include <folly/Singleton.h>
19 #include <folly/futures/ThreadWheelTimekeeper.h>
20 #include <folly/portability/GTest.h>
21
22 using namespace folly;
23 using std::chrono::milliseconds;
24
25 std::chrono::milliseconds const zero_ms(0);
26 std::chrono::milliseconds const one_ms(1);
27 std::chrono::milliseconds const awhile(10);
28 std::chrono::seconds const too_long(10);
29
30 std::chrono::steady_clock::time_point now() {
31   return std::chrono::steady_clock::now();
32 }
33
34 struct TimekeeperFixture : public testing::Test {
35   TimekeeperFixture() :
36     timeLord_(folly::detail::getTimekeeperSingleton())
37   {}
38
39   std::shared_ptr<Timekeeper> timeLord_;
40 };
41
42 TEST_F(TimekeeperFixture, after) {
43   auto t1 = now();
44   auto f = timeLord_->after(awhile);
45   EXPECT_FALSE(f.isReady());
46   f.get();
47   auto t2 = now();
48
49   EXPECT_GE(t2 - t1, awhile);
50 }
51
52 TEST(Timekeeper, futureGet) {
53   Promise<int> p;
54   auto t = std::thread([&]{ p.setValue(42); });
55   EXPECT_EQ(42, p.getFuture().get());
56   t.join();
57 }
58
59 TEST(Timekeeper, futureGetBeforeTimeout) {
60   Promise<int> p;
61   auto t = std::thread([&]{ p.setValue(42); });
62   // Technically this is a race and if the test server is REALLY overloaded
63   // and it takes more than a second to do that thread it could be flaky. But
64   // I want a low timeout (in human terms) so if this regresses and someone
65   // runs it by hand they're not sitting there forever wondering why it's
66   // blocked, and get a useful error message instead. If it does get flaky,
67   // empirically increase the timeout to the point where it's very improbable.
68   EXPECT_EQ(42, p.getFuture().get(std::chrono::seconds(2)));
69   t.join();
70 }
71
72 TEST(Timekeeper, futureGetTimeout) {
73   Promise<int> p;
74   EXPECT_THROW(p.getFuture().get(one_ms), folly::TimedOut);
75 }
76
77 TEST(Timekeeper, futureSleep) {
78   auto t1 = now();
79   futures::sleep(one_ms).get();
80   EXPECT_GE(now() - t1, one_ms);
81 }
82
83 TEST(Timekeeper, futureSleepHandlesNullTimekeeperSingleton) {
84   Singleton<ThreadWheelTimekeeper>::make_mock([] { return nullptr; });
85   SCOPE_EXIT {
86     Singleton<ThreadWheelTimekeeper>::make_mock();
87   };
88   EXPECT_THROW(futures::sleep(one_ms).get(), NoTimekeeper);
89 }
90
91 TEST(Timekeeper, futureDelayed) {
92   auto t1 = now();
93   auto dur = makeFuture()
94     .delayed(one_ms)
95     .then([=]{ return now() - t1; })
96     .get();
97
98   EXPECT_GE(dur, one_ms);
99 }
100
101 TEST(Timekeeper, futureWithinThrows) {
102   Promise<int> p;
103   auto f = p.getFuture()
104     .within(one_ms)
105     .onError([](TimedOut&) { return -1; });
106
107   EXPECT_EQ(-1, f.get());
108 }
109
110 TEST(Timekeeper, futureWithinAlreadyComplete) {
111   auto f = makeFuture(42)
112     .within(one_ms)
113     .onError([&](TimedOut&){ return -1; });
114
115   EXPECT_EQ(42, f.get());
116 }
117
118 TEST(Timekeeper, futureWithinFinishesInTime) {
119   Promise<int> p;
120   auto f = p.getFuture()
121     .within(std::chrono::minutes(1))
122     .onError([&](TimedOut&){ return -1; });
123   p.setValue(42);
124
125   EXPECT_EQ(42, f.get());
126 }
127
128 TEST(Timekeeper, futureWithinVoidSpecialization) {
129   makeFuture().within(one_ms);
130 }
131
132 TEST(Timekeeper, futureWithinException) {
133   Promise<Unit> p;
134   auto f = p.getFuture().within(awhile, std::runtime_error("expected"));
135   EXPECT_THROW(f.get(), std::runtime_error);
136 }
137
138 TEST(Timekeeper, onTimeout) {
139   bool flag = false;
140   makeFuture(42).delayed(10 * one_ms)
141     .onTimeout(zero_ms, [&]{ flag = true; return -1; })
142     .get();
143   EXPECT_TRUE(flag);
144 }
145
146 TEST(Timekeeper, onTimeoutComplete) {
147   bool flag = false;
148   makeFuture(42)
149     .onTimeout(zero_ms, [&]{ flag = true; return -1; })
150     .get();
151   EXPECT_FALSE(flag);
152 }
153
154 TEST(Timekeeper, onTimeoutReturnsFuture) {
155   bool flag = false;
156   makeFuture(42).delayed(10 * one_ms)
157     .onTimeout(zero_ms, [&]{ flag = true; return makeFuture(-1); })
158     .get();
159   EXPECT_TRUE(flag);
160 }
161
162 TEST(Timekeeper, onTimeoutVoid) {
163   makeFuture().delayed(one_ms)
164     .onTimeout(zero_ms, [&]{
165      });
166   makeFuture().delayed(one_ms)
167     .onTimeout(zero_ms, [&]{
168        return makeFuture<Unit>(std::runtime_error("expected"));
169      });
170   // just testing compilation here
171 }
172
173 TEST(Timekeeper, interruptDoesntCrash) {
174   auto f = futures::sleep(too_long);
175   f.cancel();
176 }
177
178 TEST(Timekeeper, chainedInterruptTest) {
179   bool test = false;
180   auto f = futures::sleep(milliseconds(100)).then([&](){
181     test = true;
182   });
183   f.cancel();
184   f.wait();
185   EXPECT_FALSE(test);
186 }
187
188 TEST(Timekeeper, executor) {
189   class ExecutorTester : public Executor {
190    public:
191     void add(Func f) override {
192       count++;
193       f();
194     }
195     std::atomic<int> count{0};
196   };
197
198   Promise<Unit> p;
199   ExecutorTester tester;
200   auto f = p.getFuture().via(&tester).within(one_ms).then([&](){});
201   p.setValue();
202   f.wait();
203   EXPECT_EQ(2, tester.count);
204 }
205
206 // TODO(5921764)
207 /*
208 TEST(Timekeeper, onTimeoutPropagates) {
209   bool flag = false;
210   EXPECT_THROW(
211     makeFuture(42).delayed(one_ms)
212       .onTimeout(zero_ms, [&]{ flag = true; })
213       .get(),
214     TimedOut);
215   EXPECT_TRUE(flag);
216 }
217 */
218
219 TEST_F(TimekeeperFixture, atBeforeNow) {
220   auto f = timeLord_->at(now() - too_long);
221   EXPECT_TRUE(f.isReady());
222   EXPECT_FALSE(f.hasException());
223 }
224
225 TEST_F(TimekeeperFixture, howToCastDuration) {
226   // I'm not sure whether this rounds up or down but it's irrelevant for the
227   // purpose of this example.
228   auto f = timeLord_->after(std::chrono::duration_cast<Duration>(
229       std::chrono::nanoseconds(1)));
230 }