c20668c08a5ea444bc287622141f54c5c75b13ef
[folly.git] / folly / futures / test / TimekeeperTest.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 <gtest/gtest.h>
18
19 #include <folly/futures/Timekeeper.h>
20 #include <folly/portability/Unistd.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, futureDelayed) {
84   auto t1 = now();
85   auto dur = makeFuture()
86     .delayed(one_ms)
87     .then([=]{ return now() - t1; })
88     .get();
89
90   EXPECT_GE(dur, one_ms);
91 }
92
93 TEST(Timekeeper, futureWithinThrows) {
94   Promise<int> p;
95   auto f = p.getFuture()
96     .within(one_ms)
97     .onError([](TimedOut&) { return -1; });
98
99   EXPECT_EQ(-1, f.get());
100 }
101
102 TEST(Timekeeper, futureWithinAlreadyComplete) {
103   auto f = makeFuture(42)
104     .within(one_ms)
105     .onError([&](TimedOut&){ return -1; });
106
107   EXPECT_EQ(42, f.get());
108 }
109
110 TEST(Timekeeper, futureWithinFinishesInTime) {
111   Promise<int> p;
112   auto f = p.getFuture()
113     .within(std::chrono::minutes(1))
114     .onError([&](TimedOut&){ return -1; });
115   p.setValue(42);
116
117   EXPECT_EQ(42, f.get());
118 }
119
120 TEST(Timekeeper, futureWithinVoidSpecialization) {
121   makeFuture().within(one_ms);
122 }
123
124 TEST(Timekeeper, futureWithinException) {
125   Promise<Unit> p;
126   auto f = p.getFuture().within(awhile, std::runtime_error("expected"));
127   EXPECT_THROW(f.get(), std::runtime_error);
128 }
129
130 TEST(Timekeeper, onTimeout) {
131   bool flag = false;
132   makeFuture(42).delayed(one_ms)
133     .onTimeout(zero_ms, [&]{ flag = true; return -1; })
134     .get();
135   EXPECT_TRUE(flag);
136 }
137
138 TEST(Timekeeper, onTimeoutReturnsFuture) {
139   bool flag = false;
140   makeFuture(42).delayed(one_ms)
141     .onTimeout(zero_ms, [&]{ flag = true; return makeFuture(-1); })
142     .get();
143   EXPECT_TRUE(flag);
144 }
145
146 TEST(Timekeeper, onTimeoutVoid) {
147   makeFuture().delayed(one_ms)
148     .onTimeout(zero_ms, [&]{
149      });
150   makeFuture().delayed(one_ms)
151     .onTimeout(zero_ms, [&]{
152        return makeFuture<Unit>(std::runtime_error("expected"));
153      });
154   // just testing compilation here
155 }
156
157 TEST(Timekeeper, interruptDoesntCrash) {
158   auto f = futures::sleep(too_long);
159   f.cancel();
160 }
161
162 TEST(Timekeeper, chainedInterruptTest) {
163   bool test = false;
164   auto f = futures::sleep(milliseconds(100)).then([&](){
165     test = true;
166   });
167   f.cancel();
168   f.wait();
169   EXPECT_FALSE(test);
170 }
171
172 TEST(Timekeeper, executor) {
173   class ExecutorTester : public Executor {
174    public:
175     void add(Func f) override {
176       count++;
177       f();
178     }
179     std::atomic<int> count{0};
180   };
181
182   auto f = makeFuture();
183   ExecutorTester tester;
184   f.via(&tester).within(one_ms).then([&](){}).wait();
185   EXPECT_EQ(2, tester.count);
186 }
187
188 // TODO(5921764)
189 /*
190 TEST(Timekeeper, onTimeoutPropagates) {
191   bool flag = false;
192   EXPECT_THROW(
193     makeFuture(42).delayed(one_ms)
194       .onTimeout(zero_ms, [&]{ flag = true; })
195       .get(),
196     TimedOut);
197   EXPECT_TRUE(flag);
198 }
199 */
200
201 TEST_F(TimekeeperFixture, atBeforeNow) {
202   auto f = timeLord_->at(now() - too_long);
203   EXPECT_TRUE(f.isReady());
204   EXPECT_FALSE(f.hasException());
205 }
206
207 TEST_F(TimekeeperFixture, howToCastDuration) {
208   // I'm not sure whether this rounds up or down but it's irrelevant for the
209   // purpose of this example.
210   auto f = timeLord_->after(std::chrono::duration_cast<Duration>(
211       std::chrono::nanoseconds(1)));
212 }