save/restore request context in future
[folly.git] / folly / wangle / test / FutureTest.cpp
1 /*
2  * Copyright 2014 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 <algorithm>
18 #include <atomic>
19 #include <folly/small_vector.h>
20 #include <gtest/gtest.h>
21 #include <memory>
22 #include <string>
23 #include <thread>
24 #include <type_traits>
25 #include <unistd.h>
26 #include <folly/Memory.h>
27 #include <folly/wangle/Executor.h>
28 #include <folly/wangle/Future.h>
29 #include <folly/wangle/ManualExecutor.h>
30
31 #include <folly/io/async/Request.h>
32
33 using namespace folly;
34 using namespace folly::wangle;
35 using std::pair;
36 using std::string;
37 using std::unique_ptr;
38 using std::vector;
39
40 #define EXPECT_TYPE(x, T) \
41   EXPECT_TRUE((std::is_same<decltype(x), T>::value))
42
43 typedef WangleException eggs_t;
44 static eggs_t eggs("eggs");
45
46 // Future
47
48 TEST(Future, try) {
49   class A {
50    public:
51     A(int x) : x_(x) {}
52
53     int x() const {
54       return x_;
55     }
56    private:
57     int x_;
58   };
59
60   A a(5);
61   Try<A> t_a(std::move(a));
62
63   Try<void> t_void;
64
65   EXPECT_EQ(5, t_a.value().x());
66 }
67
68 TEST(Future, special) {
69   EXPECT_FALSE(std::is_copy_constructible<Future<int>>::value);
70   EXPECT_FALSE(std::is_copy_assignable<Future<int>>::value);
71   EXPECT_TRUE(std::is_move_constructible<Future<int>>::value);
72   EXPECT_TRUE(std::is_move_assignable<Future<int>>::value);
73 }
74
75 TEST(Future, thenTry) {
76   bool flag = false;
77
78   makeFuture<int>(42).then([&](Try<int>&& t) {
79                               flag = true;
80                               EXPECT_EQ(42, t.value());
81                             });
82   EXPECT_TRUE(flag); flag = false;
83
84   makeFuture<int>(42)
85     .then([](Try<int>&& t) { return t.value(); })
86     .then([&](Try<int>&& t) { flag = true; EXPECT_EQ(42, t.value()); });
87   EXPECT_TRUE(flag); flag = false;
88
89   makeFuture().then([&](Try<void>&& t) { flag = true; t.value(); });
90   EXPECT_TRUE(flag); flag = false;
91
92   Promise<void> p;
93   auto f = p.getFuture().then([&](Try<void>&& t) { flag = true; });
94   EXPECT_FALSE(flag);
95   EXPECT_FALSE(f.isReady());
96   p.setValue();
97   EXPECT_TRUE(flag);
98   EXPECT_TRUE(f.isReady());
99 }
100
101 TEST(Future, thenValue) {
102   bool flag = false;
103   makeFuture<int>(42).then([&](int i){
104     EXPECT_EQ(42, i);
105     flag = true;
106   });
107   EXPECT_TRUE(flag); flag = false;
108
109   makeFuture<int>(42)
110     .then([](int i){ return i; })
111     .then([&](int i) { flag = true; EXPECT_EQ(42, i); });
112   EXPECT_TRUE(flag); flag = false;
113
114   makeFuture().then([&]{
115     flag = true;
116   });
117   EXPECT_TRUE(flag); flag = false;
118
119   auto f = makeFuture<int>(eggs).then([&](int i){});
120   EXPECT_THROW(f.value(), eggs_t);
121
122   f = makeFuture<void>(eggs).then([&]{});
123   EXPECT_THROW(f.value(), eggs_t);
124 }
125
126 TEST(Future, thenValueFuture) {
127   bool flag = false;
128   makeFuture<int>(42)
129     .then([](int i){ return makeFuture<int>(std::move(i)); })
130     .then([&](Try<int>&& t) { flag = true; EXPECT_EQ(42, t.value()); });
131   EXPECT_TRUE(flag); flag = false;
132
133   makeFuture()
134     .then([]{ return makeFuture(); })
135     .then([&](Try<void>&& t) { flag = true; });
136   EXPECT_TRUE(flag); flag = false;
137 }
138
139 static string doWorkStatic(Try<string>&& t) {
140   return t.value() + ";static";
141 }
142
143 TEST(Future, thenFunction) {
144   struct Worker {
145     string doWork(Try<string>&& t) {
146       return t.value() + ";class";
147     }
148     static string doWorkStatic(Try<string>&& t) {
149       return t.value() + ";class-static";
150     }
151   } w;
152
153   auto f = makeFuture<string>("start")
154     .then(doWorkStatic)
155     .then(Worker::doWorkStatic)
156     .then(&w, &Worker::doWork);
157
158   EXPECT_EQ(f.value(), "start;static;class-static;class");
159 }
160
161 static Future<string> doWorkStaticFuture(Try<string>&& t) {
162   return makeFuture(t.value() + ";static");
163 }
164
165 TEST(Future, thenFunctionFuture) {
166   struct Worker {
167     Future<string> doWorkFuture(Try<string>&& t) {
168       return makeFuture(t.value() + ";class");
169     }
170     static Future<string> doWorkStaticFuture(Try<string>&& t) {
171       return makeFuture(t.value() + ";class-static");
172     }
173   } w;
174
175   auto f = makeFuture<string>("start")
176     .then(doWorkStaticFuture)
177     .then(Worker::doWorkStaticFuture)
178     .then(&w, &Worker::doWorkFuture);
179
180   EXPECT_EQ(f.value(), "start;static;class-static;class");
181 }
182
183 TEST(Future, value) {
184   auto f = makeFuture(unique_ptr<int>(new int(42)));
185   auto up = std::move(f.value());
186   EXPECT_EQ(42, *up);
187
188   EXPECT_THROW(makeFuture<int>(eggs).value(), eggs_t);
189 }
190
191 TEST(Future, isReady) {
192   Promise<int> p;
193   auto f = p.getFuture();
194   EXPECT_FALSE(f.isReady());
195   p.setValue(42);
196   EXPECT_TRUE(f.isReady());
197   }
198
199 TEST(Future, futureNotReady) {
200   Promise<int> p;
201   Future<int> f = p.getFuture();
202   EXPECT_THROW(f.value(), eggs_t);
203 }
204
205 TEST(Future, hasException) {
206   EXPECT_TRUE(makeFuture<int>(eggs).getTry().hasException());
207   EXPECT_FALSE(makeFuture(42).getTry().hasException());
208 }
209
210 TEST(Future, hasValue) {
211   EXPECT_TRUE(makeFuture(42).getTry().hasValue());
212   EXPECT_FALSE(makeFuture<int>(eggs).getTry().hasValue());
213 }
214
215 TEST(Future, makeFuture) {
216   EXPECT_TYPE(makeFuture(42), Future<int>);
217   EXPECT_EQ(42, makeFuture(42).value());
218
219   EXPECT_TYPE(makeFuture<float>(42), Future<float>);
220   EXPECT_EQ(42, makeFuture<float>(42).value());
221
222   auto fun = [] { return 42; };
223   EXPECT_TYPE(makeFutureTry(fun), Future<int>);
224   EXPECT_EQ(42, makeFutureTry(fun).value());
225
226   auto failfun = []() -> int { throw eggs; };
227   EXPECT_TYPE(makeFutureTry(failfun), Future<int>);
228   EXPECT_THROW(makeFutureTry(failfun).value(), eggs_t);
229
230   EXPECT_TYPE(makeFuture(), Future<void>);
231 }
232
233 // Promise
234
235 TEST(Promise, special) {
236   EXPECT_FALSE(std::is_copy_constructible<Promise<int>>::value);
237   EXPECT_FALSE(std::is_copy_assignable<Promise<int>>::value);
238   EXPECT_TRUE(std::is_move_constructible<Promise<int>>::value);
239   EXPECT_TRUE(std::is_move_assignable<Promise<int>>::value);
240 }
241
242 TEST(Promise, getFuture) {
243   Promise<int> p;
244   Future<int> f = p.getFuture();
245   EXPECT_FALSE(f.isReady());
246 }
247
248 TEST(Promise, setValue) {
249   Promise<int> fund;
250   auto ffund = fund.getFuture();
251   fund.setValue(42);
252   EXPECT_EQ(42, ffund.value());
253
254   struct Foo {
255     string name;
256     int value;
257   };
258
259   Promise<Foo> pod;
260   auto fpod = pod.getFuture();
261   Foo f = {"the answer", 42};
262   pod.setValue(f);
263   Foo f2 = fpod.value();
264   EXPECT_EQ(f.name, f2.name);
265   EXPECT_EQ(f.value, f2.value);
266
267   pod = Promise<Foo>();
268   fpod = pod.getFuture();
269   pod.setValue(std::move(f2));
270   Foo f3 = fpod.value();
271   EXPECT_EQ(f.name, f3.name);
272   EXPECT_EQ(f.value, f3.value);
273
274   Promise<unique_ptr<int>> mov;
275   auto fmov = mov.getFuture();
276   mov.setValue(unique_ptr<int>(new int(42)));
277   unique_ptr<int> ptr = std::move(fmov.value());
278   EXPECT_EQ(42, *ptr);
279
280   Promise<void> v;
281   auto fv = v.getFuture();
282   v.setValue();
283   EXPECT_TRUE(fv.isReady());
284 }
285
286 TEST(Promise, setException) {
287   {
288     Promise<void> p;
289     auto f = p.getFuture();
290     p.setException(eggs);
291     EXPECT_THROW(f.value(), eggs_t);
292   }
293   {
294     Promise<void> p;
295     auto f = p.getFuture();
296     try {
297       throw eggs;
298     } catch (...) {
299       p.setException(std::current_exception());
300     }
301     EXPECT_THROW(f.value(), eggs_t);
302   }
303 }
304
305 TEST(Promise, fulfil) {
306   {
307     Promise<int> p;
308     auto f = p.getFuture();
309     p.fulfil([] { return 42; });
310     EXPECT_EQ(42, f.value());
311   }
312   {
313     Promise<int> p;
314     auto f = p.getFuture();
315     p.fulfil([]() -> int { throw eggs; });
316     EXPECT_THROW(f.value(), eggs_t);
317   }
318 }
319
320 TEST(Future, finish) {
321   auto x = std::make_shared<int>(0);
322   {
323     Promise<int> p;
324     auto f = p.getFuture().then([x](Try<int>&& t) { *x = t.value(); });
325
326     // The callback hasn't executed
327     EXPECT_EQ(0, *x);
328
329     // The callback has a reference to x
330     EXPECT_EQ(2, x.use_count());
331
332     p.setValue(42);
333
334     // the callback has executed
335     EXPECT_EQ(42, *x);
336   }
337   // the callback has been destructed
338   // and has released its reference to x
339   EXPECT_EQ(1, x.use_count());
340 }
341
342 TEST(Future, unwrap) {
343   Promise<int> a;
344   Promise<int> b;
345
346   auto fa = a.getFuture();
347   auto fb = b.getFuture();
348
349   bool flag1 = false;
350   bool flag2 = false;
351
352   // do a, then do b, and get the result of a + b.
353   Future<int> f = fa.then([&](Try<int>&& ta) {
354     auto va = ta.value();
355     flag1 = true;
356     return fb.then([va, &flag2](Try<int>&& tb) {
357       flag2 = true;
358       return va + tb.value();
359     });
360   });
361
362   EXPECT_FALSE(flag1);
363   EXPECT_FALSE(flag2);
364   EXPECT_FALSE(f.isReady());
365
366   a.setValue(3);
367   EXPECT_TRUE(flag1);
368   EXPECT_FALSE(flag2);
369   EXPECT_FALSE(f.isReady());
370
371   b.setValue(4);
372   EXPECT_TRUE(flag1);
373   EXPECT_TRUE(flag2);
374   EXPECT_EQ(7, f.value());
375 }
376
377 TEST(Future, whenAll) {
378   // returns a vector variant
379   {
380     vector<Promise<int>> promises(10);
381     vector<Future<int>> futures;
382
383     for (auto& p : promises)
384       futures.push_back(p.getFuture());
385
386     auto allf = whenAll(futures.begin(), futures.end());
387
388     random_shuffle(promises.begin(), promises.end());
389     for (auto& p : promises) {
390       EXPECT_FALSE(allf.isReady());
391       p.setValue(42);
392     }
393
394     EXPECT_TRUE(allf.isReady());
395     auto& results = allf.value();
396     for (auto& t : results) {
397       EXPECT_EQ(42, t.value());
398     }
399   }
400
401   // check error semantics
402   {
403     vector<Promise<int>> promises(4);
404     vector<Future<int>> futures;
405
406     for (auto& p : promises)
407       futures.push_back(p.getFuture());
408
409     auto allf = whenAll(futures.begin(), futures.end());
410
411
412     promises[0].setValue(42);
413     promises[1].setException(eggs);
414
415     EXPECT_FALSE(allf.isReady());
416
417     promises[2].setValue(42);
418
419     EXPECT_FALSE(allf.isReady());
420
421     promises[3].setException(eggs);
422
423     EXPECT_TRUE(allf.isReady());
424     EXPECT_FALSE(allf.getTry().hasException());
425
426     auto& results = allf.value();
427     EXPECT_EQ(42, results[0].value());
428     EXPECT_TRUE(results[1].hasException());
429     EXPECT_EQ(42, results[2].value());
430     EXPECT_TRUE(results[3].hasException());
431   }
432
433   // check that futures are ready in then()
434   {
435     vector<Promise<void>> promises(10);
436     vector<Future<void>> futures;
437
438     for (auto& p : promises)
439       futures.push_back(p.getFuture());
440
441     auto allf = whenAll(futures.begin(), futures.end())
442       .then([](Try<vector<Try<void>>>&& ts) {
443         for (auto& f : ts.value())
444           f.value();
445       });
446
447     random_shuffle(promises.begin(), promises.end());
448     for (auto& p : promises)
449       p.setValue();
450     EXPECT_TRUE(allf.isReady());
451   }
452 }
453
454
455 TEST(Future, whenAny) {
456   {
457     vector<Promise<int>> promises(10);
458     vector<Future<int>> futures;
459
460     for (auto& p : promises)
461       futures.push_back(p.getFuture());
462
463     for (auto& f : futures) {
464       EXPECT_FALSE(f.isReady());
465     }
466
467     auto anyf = whenAny(futures.begin(), futures.end());
468
469     /* futures were moved in, so these are invalid now */
470     EXPECT_FALSE(anyf.isReady());
471
472     promises[7].setValue(42);
473     EXPECT_TRUE(anyf.isReady());
474     auto& idx_fut = anyf.value();
475
476     auto i = idx_fut.first;
477     EXPECT_EQ(7, i);
478
479     auto& f = idx_fut.second;
480     EXPECT_EQ(42, f.value());
481   }
482
483   // error
484   {
485     vector<Promise<void>> promises(10);
486     vector<Future<void>> futures;
487
488     for (auto& p : promises)
489       futures.push_back(p.getFuture());
490
491     for (auto& f : futures) {
492       EXPECT_FALSE(f.isReady());
493     }
494
495     auto anyf = whenAny(futures.begin(), futures.end());
496
497     EXPECT_FALSE(anyf.isReady());
498
499     promises[3].setException(eggs);
500     EXPECT_TRUE(anyf.isReady());
501     EXPECT_TRUE(anyf.value().second.hasException());
502   }
503
504   // then()
505   {
506     vector<Promise<int>> promises(10);
507     vector<Future<int>> futures;
508
509     for (auto& p : promises)
510       futures.push_back(p.getFuture());
511
512     auto anyf = whenAny(futures.begin(), futures.end())
513       .then([](Try<pair<size_t, Try<int>>>&& f) {
514         EXPECT_EQ(42, f.value().second.value());
515       });
516
517     promises[3].setValue(42);
518     EXPECT_TRUE(anyf.isReady());
519   }
520 }
521
522
523 TEST(when, already_completed) {
524   {
525     vector<Future<void>> fs;
526     for (int i = 0; i < 10; i++)
527       fs.push_back(makeFuture());
528
529     whenAll(fs.begin(), fs.end())
530       .then([&](Try<vector<Try<void>>>&& t) {
531         EXPECT_EQ(fs.size(), t.value().size());
532       });
533   }
534   {
535     vector<Future<int>> fs;
536     for (int i = 0; i < 10; i++)
537       fs.push_back(makeFuture(i));
538
539     whenAny(fs.begin(), fs.end())
540       .then([&](Try<pair<size_t, Try<int>>>&& t) {
541         auto& p = t.value();
542         EXPECT_EQ(p.first, p.second.value());
543       });
544   }
545 }
546
547 TEST(when, whenN) {
548   vector<Promise<void>> promises(10);
549   vector<Future<void>> futures;
550
551   for (auto& p : promises)
552     futures.push_back(p.getFuture());
553
554   bool flag = false;
555   size_t n = 3;
556   whenN(futures.begin(), futures.end(), n)
557     .then([&](Try<vector<pair<size_t, Try<void>>>>&& t) {
558       flag = true;
559       auto v = t.value();
560       EXPECT_EQ(n, v.size());
561       for (auto& tt : v)
562         EXPECT_TRUE(tt.second.hasValue());
563     });
564
565   promises[0].setValue();
566   EXPECT_FALSE(flag);
567   promises[1].setValue();
568   EXPECT_FALSE(flag);
569   promises[2].setValue();
570   EXPECT_TRUE(flag);
571 }
572
573 /* Ensure that we can compile when_{all,any} with folly::small_vector */
574 TEST(when, small_vector) {
575
576   static_assert(!FOLLY_IS_TRIVIALLY_COPYABLE(Future<void>),
577                 "Futures should not be trivially copyable");
578   static_assert(!FOLLY_IS_TRIVIALLY_COPYABLE(Future<int>),
579                 "Futures should not be trivially copyable");
580
581   using folly::small_vector;
582   {
583     small_vector<Future<void>> futures;
584
585     for (int i = 0; i < 10; i++)
586       futures.push_back(makeFuture());
587
588     auto anyf = whenAny(futures.begin(), futures.end());
589   }
590
591   {
592     small_vector<Future<void>> futures;
593
594     for (int i = 0; i < 10; i++)
595       futures.push_back(makeFuture());
596
597     auto allf = whenAll(futures.begin(), futures.end());
598   }
599 }
600
601 TEST(Future, whenAllVariadic) {
602   Promise<bool> pb;
603   Promise<int> pi;
604   Future<bool> fb = pb.getFuture();
605   Future<int> fi = pi.getFuture();
606   bool flag = false;
607   whenAll(std::move(fb), std::move(fi))
608     .then([&](Try<std::tuple<Try<bool>, Try<int>>>&& t) {
609       flag = true;
610       EXPECT_TRUE(t.hasValue());
611       EXPECT_TRUE(std::get<0>(t.value()).hasValue());
612       EXPECT_EQ(std::get<0>(t.value()).value(), true);
613       EXPECT_TRUE(std::get<1>(t.value()).hasValue());
614       EXPECT_EQ(std::get<1>(t.value()).value(), 42);
615     });
616   pb.setValue(true);
617   EXPECT_FALSE(flag);
618   pi.setValue(42);
619   EXPECT_TRUE(flag);
620 }
621
622 TEST(Future, whenAllVariadicReferences) {
623   Promise<bool> pb;
624   Promise<int> pi;
625   Future<bool> fb = pb.getFuture();
626   Future<int> fi = pi.getFuture();
627   bool flag = false;
628   whenAll(fb, fi)
629     .then([&](Try<std::tuple<Try<bool>, Try<int>>>&& t) {
630       flag = true;
631       EXPECT_TRUE(t.hasValue());
632       EXPECT_TRUE(std::get<0>(t.value()).hasValue());
633       EXPECT_EQ(std::get<0>(t.value()).value(), true);
634       EXPECT_TRUE(std::get<1>(t.value()).hasValue());
635       EXPECT_EQ(std::get<1>(t.value()).value(), 42);
636     });
637   pb.setValue(true);
638   EXPECT_FALSE(flag);
639   pi.setValue(42);
640   EXPECT_TRUE(flag);
641 }
642
643 TEST(Future, whenAll_none) {
644   vector<Future<int>> fs;
645   auto f = whenAll(fs.begin(), fs.end());
646   EXPECT_TRUE(f.isReady());
647 }
648
649 TEST(Future, throwCaughtInImmediateThen) {
650   // Neither of these should throw "Promise already satisfied"
651   makeFuture().then(
652     [=](Try<void>&&) -> int { throw std::exception(); });
653   makeFuture().then(
654     [=](Try<void>&&) -> Future<int> { throw std::exception(); });
655 }
656
657 TEST(Future, throwIfFailed) {
658   makeFuture<void>(eggs)
659     .then([=](Try<void>&& t) {
660       EXPECT_THROW(t.throwIfFailed(), eggs_t);
661     });
662   makeFuture()
663     .then([=](Try<void>&& t) {
664       EXPECT_NO_THROW(t.throwIfFailed());
665     });
666
667   makeFuture<int>(eggs)
668     .then([=](Try<int>&& t) {
669       EXPECT_THROW(t.throwIfFailed(), eggs_t);
670     });
671   makeFuture<int>(42)
672     .then([=](Try<int>&& t) {
673       EXPECT_NO_THROW(t.throwIfFailed());
674     });
675 }
676
677 TEST(Future, waitWithSemaphoreImmediate) {
678   waitWithSemaphore(makeFuture());
679   auto done = waitWithSemaphore(makeFuture(42)).value();
680   EXPECT_EQ(42, done);
681
682   vector<int> v{1,2,3};
683   auto done_v = waitWithSemaphore(makeFuture(v)).value();
684   EXPECT_EQ(v.size(), done_v.size());
685   EXPECT_EQ(v, done_v);
686
687   vector<Future<void>> v_f;
688   v_f.push_back(makeFuture());
689   v_f.push_back(makeFuture());
690   auto done_v_f = waitWithSemaphore(whenAll(v_f.begin(), v_f.end())).value();
691   EXPECT_EQ(2, done_v_f.size());
692
693   vector<Future<bool>> v_fb;
694   v_fb.push_back(makeFuture(true));
695   v_fb.push_back(makeFuture(false));
696   auto fut = whenAll(v_fb.begin(), v_fb.end());
697   auto done_v_fb = std::move(waitWithSemaphore(std::move(fut)).value());
698   EXPECT_EQ(2, done_v_fb.size());
699 }
700
701 TEST(Future, waitWithSemaphore) {
702   Promise<int> p;
703   Future<int> f = p.getFuture();
704   std::atomic<bool> flag{false};
705   std::atomic<int> result{1};
706   std::atomic<std::thread::id> id;
707
708   std::thread t([&](Future<int>&& tf){
709       auto n = tf.then([&](Try<int> && t) {
710           id = std::this_thread::get_id();
711           return t.value();
712         });
713       flag = true;
714       result.store(waitWithSemaphore(std::move(n)).value());
715     },
716     std::move(f)
717     );
718   while(!flag){}
719   EXPECT_EQ(result.load(), 1);
720   p.setValue(42);
721   t.join();
722   // validate that the callback ended up executing in this thread, which
723   // is more to ensure that this test actually tests what it should
724   EXPECT_EQ(id, std::this_thread::get_id());
725   EXPECT_EQ(result.load(), 42);
726 }
727
728 TEST(Future, waitWithSemaphoreForTime) {
729  {
730   Promise<int> p;
731   Future<int> f = p.getFuture();
732   auto t = waitWithSemaphore(std::move(f),
733     std::chrono::microseconds(1));
734   EXPECT_FALSE(t.isReady());
735   p.setValue(1);
736   EXPECT_TRUE(t.isReady());
737  }
738  {
739   Promise<int> p;
740   Future<int> f = p.getFuture();
741   p.setValue(1);
742   auto t = waitWithSemaphore(std::move(f),
743     std::chrono::milliseconds(1));
744   EXPECT_TRUE(t.isReady());
745  }
746  {
747   vector<Future<bool>> v_fb;
748   v_fb.push_back(makeFuture(true));
749   v_fb.push_back(makeFuture(false));
750   auto f = whenAll(v_fb.begin(), v_fb.end());
751   auto t = waitWithSemaphore(std::move(f),
752     std::chrono::milliseconds(1));
753   EXPECT_TRUE(t.isReady());
754   EXPECT_EQ(2, t.value().size());
755  }
756  {
757   vector<Future<bool>> v_fb;
758   Promise<bool> p1;
759   Promise<bool> p2;
760   v_fb.push_back(p1.getFuture());
761   v_fb.push_back(p2.getFuture());
762   auto f = whenAll(v_fb.begin(), v_fb.end());
763   auto t = waitWithSemaphore(std::move(f),
764     std::chrono::milliseconds(1));
765   EXPECT_FALSE(t.isReady());
766   p1.setValue(true);
767   EXPECT_FALSE(t.isReady());
768   p2.setValue(true);
769   EXPECT_TRUE(t.isReady());
770  }
771  {
772   auto t = waitWithSemaphore(makeFuture(),
773     std::chrono::milliseconds(1));
774   EXPECT_TRUE(t.isReady());
775  }
776 }
777
778 TEST(Future, callbackAfterActivate) {
779   Promise<void> p;
780   auto f = p.getFuture();
781   f.deactivate();
782
783   size_t count = 0;
784   f.then([&](Try<void>&&) { count++; });
785
786   p.setValue();
787   EXPECT_EQ(0, count);
788
789   f.activate();
790   EXPECT_EQ(1, count);
791 }
792
793 TEST(Future, activateOnDestruct) {
794   Promise<void> p;
795   auto f = p.getFuture();
796   f.deactivate();
797
798   size_t count = 0;
799   f.then([&](Try<void>&&) { count++; });
800
801   p.setValue();
802   EXPECT_EQ(0, count);
803
804   f = makeFuture(); // force destruction of old f
805   EXPECT_EQ(1, count);
806 }
807
808 TEST(Future, viaActsCold) {
809   ManualExecutor x;
810   size_t count = 0;
811
812   auto fv = makeFuture().via(&x);
813   fv.then([&](Try<void>&&) { count++; });
814
815   EXPECT_EQ(0, count);
816
817   fv.activate();
818
819   EXPECT_EQ(1, x.run());
820   EXPECT_EQ(1, count);
821 }
822
823 TEST(Future, viaIsCold) {
824   ManualExecutor x;
825   EXPECT_FALSE(makeFuture().via(&x).isActive());
826 }
827
828 TEST(Future, viaRaces) {
829   ManualExecutor x;
830   Promise<void> p;
831   auto tid = std::this_thread::get_id();
832   bool done = false;
833
834   std::thread t1([&] {
835     p.getFuture()
836       .via(&x)
837       .then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
838       .then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
839       .then([&](Try<void>&&) { done = true; });
840   });
841
842   std::thread t2([&] {
843     p.setValue();
844   });
845
846   while (!done) x.run();
847   t1.join();
848   t2.join();
849 }
850
851 // TODO(#4920689)
852 TEST(Future, viaRaces_2stage) {
853   ManualExecutor x;
854   Promise<void> p;
855   auto tid = std::this_thread::get_id();
856   bool done = false;
857
858   std::thread t1([&] {
859     auto f2 = p.getFuture().via(&x);
860     f2.then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
861       .then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
862       .then([&](Try<void>&&) { done = true; });
863
864     // the bug was in the promise being fulfilled before f2 is reactivated. we
865     // could sleep, but yielding should cause this to fail with reasonable
866     // probability
867     std::this_thread::yield();
868     f2.activate();
869   });
870
871   std::thread t2([&] {
872     p.setValue();
873   });
874
875   while (!done) x.run();
876   t1.join();
877   t2.join();
878 }
879
880 TEST(Future, getFuture_after_setValue) {
881   Promise<int> p;
882   p.setValue(42);
883   EXPECT_EQ(42, p.getFuture().value());
884 }
885
886 TEST(Future, getFuture_after_setException) {
887   Promise<void> p;
888   p.fulfil([]() -> void { throw std::logic_error("foo"); });
889   EXPECT_THROW(p.getFuture().value(), std::logic_error);
890 }
891
892 TEST(Future, detachRace) {
893   // Task #5438209
894   // This test is designed to detect a race that was in Core::detachOne()
895   // where detached_ was incremented and then tested, and that
896   // allowed a race where both Promise and Future would think they were the
897   // second and both try to delete. This showed up at scale but was very
898   // difficult to reliably repro in a test. As it is, this only fails about
899   // once in every 1,000 executions. Doing this 1,000 times is going to make a
900   // slow test so I won't do that but if it ever fails, take it seriously, and
901   // run the test binary with "--gtest_repeat=10000 --gtest_filter=*detachRace"
902   // (Don't forget to enable ASAN)
903   auto p = folly::make_unique<Promise<bool>>();
904   auto f = folly::make_unique<Future<bool>>(p->getFuture());
905   folly::Baton<> baton;
906   std::thread t1([&]{
907     baton.post();
908     p.reset();
909   });
910   baton.wait();
911   f.reset();
912   t1.join();
913 }
914
915 class TestData : public RequestData {
916  public:
917   explicit TestData(int data) : data_(data) {}
918   virtual ~TestData() {}
919   int data_;
920 };
921
922 TEST(Future, context) {
923
924   // Start a new context
925   RequestContext::create();
926
927   EXPECT_EQ(nullptr, RequestContext::get()->getContextData("test"));
928
929   // Set some test data
930   RequestContext::get()->setContextData(
931     "test",
932     std::unique_ptr<TestData>(new TestData(10)));
933
934   // Start a future
935   Promise<void> p;
936   auto future = p.getFuture().then([&]{
937     // Check that the context followed the future
938     EXPECT_TRUE(RequestContext::get() != nullptr);
939     auto a = dynamic_cast<TestData*>(
940       RequestContext::get()->getContextData("test"));
941     auto data = a->data_;
942     EXPECT_EQ(10, data);
943   });
944
945   // Clear the context
946   RequestContext::setContext(nullptr);
947
948   EXPECT_EQ(nullptr, RequestContext::get()->getContextData("test"));
949
950   // Fulfil the promise
951   p.setValue();
952 }