waitWithSemaphore -> Future<T>::wait()
[folly.git] / folly / futures / 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/Executor.h>
28 #include <folly/futures/Future.h>
29 #include <folly/futures/ManualExecutor.h>
30 #include <folly/MPMCQueue.h>
31
32 #include <folly/io/async/Request.h>
33
34 using namespace folly;
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 /// Simple executor that does work in another thread
44 class ThreadExecutor : public Executor {
45   folly::MPMCQueue<Func> funcs;
46   std::atomic<bool> done {false};
47   std::thread worker;
48   folly::Baton<> baton;
49
50   void work() {
51     baton.post();
52     Func fn;
53     while (!done) {
54       while (!funcs.isEmpty()) {
55         funcs.blockingRead(fn);
56         fn();
57       }
58     }
59   }
60
61  public:
62   explicit ThreadExecutor(size_t n = 1024)
63     : funcs(n), worker(std::bind(&ThreadExecutor::work, this)) {}
64
65   ~ThreadExecutor() {
66     done = true;
67     funcs.write([]{});
68     worker.join();
69   }
70
71   void add(Func fn) override {
72     funcs.blockingWrite(std::move(fn));
73   }
74
75   void waitForStartup() {
76     baton.wait();
77   }
78 };
79
80 typedef FutureException eggs_t;
81 static eggs_t eggs("eggs");
82
83 // Future
84
85 TEST(Future, onError) {
86   bool theFlag = false;
87   auto flag = [&]{ theFlag = true; };
88 #define EXPECT_FLAG() \
89   do { \
90     EXPECT_TRUE(theFlag); \
91     theFlag = false; \
92   } while(0);
93
94 #define EXPECT_NO_FLAG() \
95   do { \
96     EXPECT_FALSE(theFlag); \
97     theFlag = false; \
98   } while(0);
99
100   // By reference
101   {
102     auto f = makeFuture()
103       .then([] { throw eggs; })
104       .onError([&] (eggs_t& e) { flag(); });
105     EXPECT_FLAG();
106     EXPECT_NO_THROW(f.value());
107   }
108
109   {
110     auto f = makeFuture()
111       .then([] { throw eggs; })
112       .onError([&] (eggs_t& e) { flag(); return makeFuture(); });
113     EXPECT_FLAG();
114     EXPECT_NO_THROW(f.value());
115   }
116
117   // By value
118   {
119     auto f = makeFuture()
120       .then([] { throw eggs; })
121       .onError([&] (eggs_t e) { flag(); });
122     EXPECT_FLAG();
123     EXPECT_NO_THROW(f.value());
124   }
125
126   {
127     auto f = makeFuture()
128       .then([] { throw eggs; })
129       .onError([&] (eggs_t e) { flag(); return makeFuture(); });
130     EXPECT_FLAG();
131     EXPECT_NO_THROW(f.value());
132   }
133
134   // Polymorphic
135   {
136     auto f = makeFuture()
137       .then([] { throw eggs; })
138       .onError([&] (std::exception& e) { flag(); });
139     EXPECT_FLAG();
140     EXPECT_NO_THROW(f.value());
141   }
142
143   {
144     auto f = makeFuture()
145       .then([] { throw eggs; })
146       .onError([&] (std::exception& e) { flag(); return makeFuture(); });
147     EXPECT_FLAG();
148     EXPECT_NO_THROW(f.value());
149   }
150
151   // Non-exceptions
152   {
153     auto f = makeFuture()
154       .then([] { throw -1; })
155       .onError([&] (int e) { flag(); });
156     EXPECT_FLAG();
157     EXPECT_NO_THROW(f.value());
158   }
159
160   {
161     auto f = makeFuture()
162       .then([] { throw -1; })
163       .onError([&] (int e) { flag(); return makeFuture(); });
164     EXPECT_FLAG();
165     EXPECT_NO_THROW(f.value());
166   }
167
168   // Mutable lambda
169   {
170     auto f = makeFuture()
171       .then([] { throw eggs; })
172       .onError([&] (eggs_t& e) mutable { flag(); });
173     EXPECT_FLAG();
174     EXPECT_NO_THROW(f.value());
175   }
176
177   {
178     auto f = makeFuture()
179       .then([] { throw eggs; })
180       .onError([&] (eggs_t& e) mutable { flag(); return makeFuture(); });
181     EXPECT_FLAG();
182     EXPECT_NO_THROW(f.value());
183   }
184
185   // No throw
186   {
187     auto f = makeFuture()
188       .then([] { return 42; })
189       .onError([&] (eggs_t& e) { flag(); return -1; });
190     EXPECT_NO_FLAG();
191     EXPECT_EQ(42, f.value());
192   }
193
194   {
195     auto f = makeFuture()
196       .then([] { return 42; })
197       .onError([&] (eggs_t& e) { flag(); return makeFuture<int>(-1); });
198     EXPECT_NO_FLAG();
199     EXPECT_EQ(42, f.value());
200   }
201
202   // Catch different exception
203   {
204     auto f = makeFuture()
205       .then([] { throw eggs; })
206       .onError([&] (std::runtime_error& e) { flag(); });
207     EXPECT_NO_FLAG();
208     EXPECT_THROW(f.value(), eggs_t);
209   }
210
211   {
212     auto f = makeFuture()
213       .then([] { throw eggs; })
214       .onError([&] (std::runtime_error& e) { flag(); return makeFuture(); });
215     EXPECT_NO_FLAG();
216     EXPECT_THROW(f.value(), eggs_t);
217   }
218
219   // Returned value propagates
220   {
221     auto f = makeFuture()
222       .then([] { throw eggs; return 0; })
223       .onError([&] (eggs_t& e) { return 42; });
224     EXPECT_EQ(42, f.value());
225   }
226
227   // Returned future propagates
228   {
229     auto f = makeFuture()
230       .then([] { throw eggs; return 0; })
231       .onError([&] (eggs_t& e) { return makeFuture<int>(42); });
232     EXPECT_EQ(42, f.value());
233   }
234
235   // Throw in callback
236   {
237     auto f = makeFuture()
238       .then([] { throw eggs; return 0; })
239       .onError([&] (eggs_t& e) { throw e; return -1; });
240     EXPECT_THROW(f.value(), eggs_t);
241   }
242
243   {
244     auto f = makeFuture()
245       .then([] { throw eggs; return 0; })
246       .onError([&] (eggs_t& e) { throw e; return makeFuture<int>(-1); });
247     EXPECT_THROW(f.value(), eggs_t);
248   }
249 }
250
251 TEST(Future, try) {
252   class A {
253    public:
254     A(int x) : x_(x) {}
255
256     int x() const {
257       return x_;
258     }
259    private:
260     int x_;
261   };
262
263   A a(5);
264   Try<A> t_a(std::move(a));
265
266   Try<void> t_void;
267
268   EXPECT_EQ(5, t_a.value().x());
269 }
270
271 TEST(Future, special) {
272   EXPECT_FALSE(std::is_copy_constructible<Future<int>>::value);
273   EXPECT_FALSE(std::is_copy_assignable<Future<int>>::value);
274   EXPECT_TRUE(std::is_move_constructible<Future<int>>::value);
275   EXPECT_TRUE(std::is_move_assignable<Future<int>>::value);
276 }
277
278 TEST(Future, thenTry) {
279   bool flag = false;
280
281   makeFuture<int>(42).then([&](Try<int>&& t) {
282                               flag = true;
283                               EXPECT_EQ(42, t.value());
284                             });
285   EXPECT_TRUE(flag); flag = false;
286
287   makeFuture<int>(42)
288     .then([](Try<int>&& t) { return t.value(); })
289     .then([&](Try<int>&& t) { flag = true; EXPECT_EQ(42, t.value()); });
290   EXPECT_TRUE(flag); flag = false;
291
292   makeFuture().then([&](Try<void>&& t) { flag = true; t.value(); });
293   EXPECT_TRUE(flag); flag = false;
294
295   Promise<void> p;
296   auto f = p.getFuture().then([&](Try<void>&& t) { flag = true; });
297   EXPECT_FALSE(flag);
298   EXPECT_FALSE(f.isReady());
299   p.setValue();
300   EXPECT_TRUE(flag);
301   EXPECT_TRUE(f.isReady());
302 }
303
304 TEST(Future, thenValue) {
305   bool flag = false;
306   makeFuture<int>(42).then([&](int i){
307     EXPECT_EQ(42, i);
308     flag = true;
309   });
310   EXPECT_TRUE(flag); flag = false;
311
312   makeFuture<int>(42)
313     .then([](int i){ return i; })
314     .then([&](int i) { flag = true; EXPECT_EQ(42, i); });
315   EXPECT_TRUE(flag); flag = false;
316
317   makeFuture().then([&]{
318     flag = true;
319   });
320   EXPECT_TRUE(flag); flag = false;
321
322   auto f = makeFuture<int>(eggs).then([&](int i){});
323   EXPECT_THROW(f.value(), eggs_t);
324
325   f = makeFuture<void>(eggs).then([&]{});
326   EXPECT_THROW(f.value(), eggs_t);
327 }
328
329 TEST(Future, thenValueFuture) {
330   bool flag = false;
331   makeFuture<int>(42)
332     .then([](int i){ return makeFuture<int>(std::move(i)); })
333     .then([&](Try<int>&& t) { flag = true; EXPECT_EQ(42, t.value()); });
334   EXPECT_TRUE(flag); flag = false;
335
336   makeFuture()
337     .then([]{ return makeFuture(); })
338     .then([&](Try<void>&& t) { flag = true; });
339   EXPECT_TRUE(flag); flag = false;
340 }
341
342 static string doWorkStatic(Try<string>&& t) {
343   return t.value() + ";static";
344 }
345
346 TEST(Future, thenFunction) {
347   struct Worker {
348     string doWork(Try<string>&& t) {
349       return t.value() + ";class";
350     }
351     static string doWorkStatic(Try<string>&& t) {
352       return t.value() + ";class-static";
353     }
354   } w;
355
356   auto f = makeFuture<string>("start")
357     .then(doWorkStatic)
358     .then(Worker::doWorkStatic)
359     .then(&w, &Worker::doWork);
360
361   EXPECT_EQ(f.value(), "start;static;class-static;class");
362 }
363
364 static Future<string> doWorkStaticFuture(Try<string>&& t) {
365   return makeFuture(t.value() + ";static");
366 }
367
368 TEST(Future, thenFunctionFuture) {
369   struct Worker {
370     Future<string> doWorkFuture(Try<string>&& t) {
371       return makeFuture(t.value() + ";class");
372     }
373     static Future<string> doWorkStaticFuture(Try<string>&& t) {
374       return makeFuture(t.value() + ";class-static");
375     }
376   } w;
377
378   auto f = makeFuture<string>("start")
379     .then(doWorkStaticFuture)
380     .then(Worker::doWorkStaticFuture)
381     .then(&w, &Worker::doWorkFuture);
382
383   EXPECT_EQ(f.value(), "start;static;class-static;class");
384 }
385
386 TEST(Future, value) {
387   auto f = makeFuture(unique_ptr<int>(new int(42)));
388   auto up = std::move(f.value());
389   EXPECT_EQ(42, *up);
390
391   EXPECT_THROW(makeFuture<int>(eggs).value(), eggs_t);
392 }
393
394 TEST(Future, isReady) {
395   Promise<int> p;
396   auto f = p.getFuture();
397   EXPECT_FALSE(f.isReady());
398   p.setValue(42);
399   EXPECT_TRUE(f.isReady());
400   }
401
402 TEST(Future, futureNotReady) {
403   Promise<int> p;
404   Future<int> f = p.getFuture();
405   EXPECT_THROW(f.value(), eggs_t);
406 }
407
408 TEST(Future, hasException) {
409   EXPECT_TRUE(makeFuture<int>(eggs).getTry().hasException());
410   EXPECT_FALSE(makeFuture(42).getTry().hasException());
411 }
412
413 TEST(Future, hasValue) {
414   EXPECT_TRUE(makeFuture(42).getTry().hasValue());
415   EXPECT_FALSE(makeFuture<int>(eggs).getTry().hasValue());
416 }
417
418 TEST(Future, makeFuture) {
419   EXPECT_TYPE(makeFuture(42), Future<int>);
420   EXPECT_EQ(42, makeFuture(42).value());
421
422   EXPECT_TYPE(makeFuture<float>(42), Future<float>);
423   EXPECT_EQ(42, makeFuture<float>(42).value());
424
425   auto fun = [] { return 42; };
426   EXPECT_TYPE(makeFutureTry(fun), Future<int>);
427   EXPECT_EQ(42, makeFutureTry(fun).value());
428
429   auto failfun = []() -> int { throw eggs; };
430   EXPECT_TYPE(makeFutureTry(failfun), Future<int>);
431   EXPECT_THROW(makeFutureTry(failfun).value(), eggs_t);
432
433   EXPECT_TYPE(makeFuture(), Future<void>);
434 }
435
436 // Promise
437
438 TEST(Promise, special) {
439   EXPECT_FALSE(std::is_copy_constructible<Promise<int>>::value);
440   EXPECT_FALSE(std::is_copy_assignable<Promise<int>>::value);
441   EXPECT_TRUE(std::is_move_constructible<Promise<int>>::value);
442   EXPECT_TRUE(std::is_move_assignable<Promise<int>>::value);
443 }
444
445 TEST(Promise, getFuture) {
446   Promise<int> p;
447   Future<int> f = p.getFuture();
448   EXPECT_FALSE(f.isReady());
449 }
450
451 TEST(Promise, setValue) {
452   Promise<int> fund;
453   auto ffund = fund.getFuture();
454   fund.setValue(42);
455   EXPECT_EQ(42, ffund.value());
456
457   struct Foo {
458     string name;
459     int value;
460   };
461
462   Promise<Foo> pod;
463   auto fpod = pod.getFuture();
464   Foo f = {"the answer", 42};
465   pod.setValue(f);
466   Foo f2 = fpod.value();
467   EXPECT_EQ(f.name, f2.name);
468   EXPECT_EQ(f.value, f2.value);
469
470   pod = Promise<Foo>();
471   fpod = pod.getFuture();
472   pod.setValue(std::move(f2));
473   Foo f3 = fpod.value();
474   EXPECT_EQ(f.name, f3.name);
475   EXPECT_EQ(f.value, f3.value);
476
477   Promise<unique_ptr<int>> mov;
478   auto fmov = mov.getFuture();
479   mov.setValue(unique_ptr<int>(new int(42)));
480   unique_ptr<int> ptr = std::move(fmov.value());
481   EXPECT_EQ(42, *ptr);
482
483   Promise<void> v;
484   auto fv = v.getFuture();
485   v.setValue();
486   EXPECT_TRUE(fv.isReady());
487 }
488
489 TEST(Promise, setException) {
490   {
491     Promise<void> p;
492     auto f = p.getFuture();
493     p.setException(eggs);
494     EXPECT_THROW(f.value(), eggs_t);
495   }
496   {
497     Promise<void> p;
498     auto f = p.getFuture();
499     try {
500       throw eggs;
501     } catch (...) {
502       p.setException(exception_wrapper(std::current_exception()));
503     }
504     EXPECT_THROW(f.value(), eggs_t);
505   }
506 }
507
508 TEST(Promise, fulfil) {
509   {
510     Promise<int> p;
511     auto f = p.getFuture();
512     p.fulfil([] { return 42; });
513     EXPECT_EQ(42, f.value());
514   }
515   {
516     Promise<int> p;
517     auto f = p.getFuture();
518     p.fulfil([]() -> int { throw eggs; });
519     EXPECT_THROW(f.value(), eggs_t);
520   }
521 }
522
523 TEST(Future, finish) {
524   auto x = std::make_shared<int>(0);
525   {
526     Promise<int> p;
527     auto f = p.getFuture().then([x](Try<int>&& t) { *x = t.value(); });
528
529     // The callback hasn't executed
530     EXPECT_EQ(0, *x);
531
532     // The callback has a reference to x
533     EXPECT_EQ(2, x.use_count());
534
535     p.setValue(42);
536
537     // the callback has executed
538     EXPECT_EQ(42, *x);
539   }
540   // the callback has been destructed
541   // and has released its reference to x
542   EXPECT_EQ(1, x.use_count());
543 }
544
545 TEST(Future, unwrap) {
546   Promise<int> a;
547   Promise<int> b;
548
549   auto fa = a.getFuture();
550   auto fb = b.getFuture();
551
552   bool flag1 = false;
553   bool flag2 = false;
554
555   // do a, then do b, and get the result of a + b.
556   Future<int> f = fa.then([&](Try<int>&& ta) {
557     auto va = ta.value();
558     flag1 = true;
559     return fb.then([va, &flag2](Try<int>&& tb) {
560       flag2 = true;
561       return va + tb.value();
562     });
563   });
564
565   EXPECT_FALSE(flag1);
566   EXPECT_FALSE(flag2);
567   EXPECT_FALSE(f.isReady());
568
569   a.setValue(3);
570   EXPECT_TRUE(flag1);
571   EXPECT_FALSE(flag2);
572   EXPECT_FALSE(f.isReady());
573
574   b.setValue(4);
575   EXPECT_TRUE(flag1);
576   EXPECT_TRUE(flag2);
577   EXPECT_EQ(7, f.value());
578 }
579
580 TEST(Future, whenAll) {
581   // returns a vector variant
582   {
583     vector<Promise<int>> promises(10);
584     vector<Future<int>> futures;
585
586     for (auto& p : promises)
587       futures.push_back(p.getFuture());
588
589     auto allf = whenAll(futures.begin(), futures.end());
590
591     random_shuffle(promises.begin(), promises.end());
592     for (auto& p : promises) {
593       EXPECT_FALSE(allf.isReady());
594       p.setValue(42);
595     }
596
597     EXPECT_TRUE(allf.isReady());
598     auto& results = allf.value();
599     for (auto& t : results) {
600       EXPECT_EQ(42, t.value());
601     }
602   }
603
604   // check error semantics
605   {
606     vector<Promise<int>> promises(4);
607     vector<Future<int>> futures;
608
609     for (auto& p : promises)
610       futures.push_back(p.getFuture());
611
612     auto allf = whenAll(futures.begin(), futures.end());
613
614
615     promises[0].setValue(42);
616     promises[1].setException(eggs);
617
618     EXPECT_FALSE(allf.isReady());
619
620     promises[2].setValue(42);
621
622     EXPECT_FALSE(allf.isReady());
623
624     promises[3].setException(eggs);
625
626     EXPECT_TRUE(allf.isReady());
627     EXPECT_FALSE(allf.getTry().hasException());
628
629     auto& results = allf.value();
630     EXPECT_EQ(42, results[0].value());
631     EXPECT_TRUE(results[1].hasException());
632     EXPECT_EQ(42, results[2].value());
633     EXPECT_TRUE(results[3].hasException());
634   }
635
636   // check that futures are ready in then()
637   {
638     vector<Promise<void>> promises(10);
639     vector<Future<void>> futures;
640
641     for (auto& p : promises)
642       futures.push_back(p.getFuture());
643
644     auto allf = whenAll(futures.begin(), futures.end())
645       .then([](Try<vector<Try<void>>>&& ts) {
646         for (auto& f : ts.value())
647           f.value();
648       });
649
650     random_shuffle(promises.begin(), promises.end());
651     for (auto& p : promises)
652       p.setValue();
653     EXPECT_TRUE(allf.isReady());
654   }
655 }
656
657
658 TEST(Future, whenAny) {
659   {
660     vector<Promise<int>> promises(10);
661     vector<Future<int>> futures;
662
663     for (auto& p : promises)
664       futures.push_back(p.getFuture());
665
666     for (auto& f : futures) {
667       EXPECT_FALSE(f.isReady());
668     }
669
670     auto anyf = whenAny(futures.begin(), futures.end());
671
672     /* futures were moved in, so these are invalid now */
673     EXPECT_FALSE(anyf.isReady());
674
675     promises[7].setValue(42);
676     EXPECT_TRUE(anyf.isReady());
677     auto& idx_fut = anyf.value();
678
679     auto i = idx_fut.first;
680     EXPECT_EQ(7, i);
681
682     auto& f = idx_fut.second;
683     EXPECT_EQ(42, f.value());
684   }
685
686   // error
687   {
688     vector<Promise<void>> promises(10);
689     vector<Future<void>> futures;
690
691     for (auto& p : promises)
692       futures.push_back(p.getFuture());
693
694     for (auto& f : futures) {
695       EXPECT_FALSE(f.isReady());
696     }
697
698     auto anyf = whenAny(futures.begin(), futures.end());
699
700     EXPECT_FALSE(anyf.isReady());
701
702     promises[3].setException(eggs);
703     EXPECT_TRUE(anyf.isReady());
704     EXPECT_TRUE(anyf.value().second.hasException());
705   }
706
707   // then()
708   {
709     vector<Promise<int>> promises(10);
710     vector<Future<int>> futures;
711
712     for (auto& p : promises)
713       futures.push_back(p.getFuture());
714
715     auto anyf = whenAny(futures.begin(), futures.end())
716       .then([](pair<size_t, Try<int>> p) {
717         EXPECT_EQ(42, p.second.value());
718       });
719
720     promises[3].setValue(42);
721     EXPECT_TRUE(anyf.isReady());
722   }
723 }
724
725
726 TEST(when, already_completed) {
727   {
728     vector<Future<void>> fs;
729     for (int i = 0; i < 10; i++)
730       fs.push_back(makeFuture());
731
732     whenAll(fs.begin(), fs.end())
733       .then([&](vector<Try<void>> ts) {
734         EXPECT_EQ(fs.size(), ts.size());
735       });
736   }
737   {
738     vector<Future<int>> fs;
739     for (int i = 0; i < 10; i++)
740       fs.push_back(makeFuture(i));
741
742     whenAny(fs.begin(), fs.end())
743       .then([&](pair<size_t, Try<int>> p) {
744         EXPECT_EQ(p.first, p.second.value());
745       });
746   }
747 }
748
749 TEST(when, whenN) {
750   vector<Promise<void>> promises(10);
751   vector<Future<void>> futures;
752
753   for (auto& p : promises)
754     futures.push_back(p.getFuture());
755
756   bool flag = false;
757   size_t n = 3;
758   whenN(futures.begin(), futures.end(), n)
759     .then([&](vector<pair<size_t, Try<void>>> v) {
760       flag = true;
761       EXPECT_EQ(n, v.size());
762       for (auto& tt : v)
763         EXPECT_TRUE(tt.second.hasValue());
764     });
765
766   promises[0].setValue();
767   EXPECT_FALSE(flag);
768   promises[1].setValue();
769   EXPECT_FALSE(flag);
770   promises[2].setValue();
771   EXPECT_TRUE(flag);
772 }
773
774 /* Ensure that we can compile when_{all,any} with folly::small_vector */
775 TEST(when, small_vector) {
776
777   static_assert(!FOLLY_IS_TRIVIALLY_COPYABLE(Future<void>),
778                 "Futures should not be trivially copyable");
779   static_assert(!FOLLY_IS_TRIVIALLY_COPYABLE(Future<int>),
780                 "Futures should not be trivially copyable");
781
782   using folly::small_vector;
783   {
784     small_vector<Future<void>> futures;
785
786     for (int i = 0; i < 10; i++)
787       futures.push_back(makeFuture());
788
789     auto anyf = whenAny(futures.begin(), futures.end());
790   }
791
792   {
793     small_vector<Future<void>> futures;
794
795     for (int i = 0; i < 10; i++)
796       futures.push_back(makeFuture());
797
798     auto allf = whenAll(futures.begin(), futures.end());
799   }
800 }
801
802 TEST(Future, whenAllVariadic) {
803   Promise<bool> pb;
804   Promise<int> pi;
805   Future<bool> fb = pb.getFuture();
806   Future<int> fi = pi.getFuture();
807   bool flag = false;
808   whenAll(std::move(fb), std::move(fi))
809     .then([&](std::tuple<Try<bool>, Try<int>> tup) {
810       flag = true;
811       EXPECT_TRUE(std::get<0>(tup).hasValue());
812       EXPECT_EQ(std::get<0>(tup).value(), true);
813       EXPECT_TRUE(std::get<1>(tup).hasValue());
814       EXPECT_EQ(std::get<1>(tup).value(), 42);
815     });
816   pb.setValue(true);
817   EXPECT_FALSE(flag);
818   pi.setValue(42);
819   EXPECT_TRUE(flag);
820 }
821
822 TEST(Future, whenAllVariadicReferences) {
823   Promise<bool> pb;
824   Promise<int> pi;
825   Future<bool> fb = pb.getFuture();
826   Future<int> fi = pi.getFuture();
827   bool flag = false;
828   whenAll(fb, fi)
829     .then([&](std::tuple<Try<bool>, Try<int>> tup) {
830       flag = true;
831       EXPECT_TRUE(std::get<0>(tup).hasValue());
832       EXPECT_EQ(std::get<0>(tup).value(), true);
833       EXPECT_TRUE(std::get<1>(tup).hasValue());
834       EXPECT_EQ(std::get<1>(tup).value(), 42);
835     });
836   pb.setValue(true);
837   EXPECT_FALSE(flag);
838   pi.setValue(42);
839   EXPECT_TRUE(flag);
840 }
841
842 TEST(Future, whenAll_none) {
843   vector<Future<int>> fs;
844   auto f = whenAll(fs.begin(), fs.end());
845   EXPECT_TRUE(f.isReady());
846 }
847
848 TEST(Future, throwCaughtInImmediateThen) {
849   // Neither of these should throw "Promise already satisfied"
850   makeFuture().then(
851     [=](Try<void>&&) -> int { throw std::exception(); });
852   makeFuture().then(
853     [=](Try<void>&&) -> Future<int> { throw std::exception(); });
854 }
855
856 TEST(Future, throwIfFailed) {
857   makeFuture<void>(eggs)
858     .then([=](Try<void>&& t) {
859       EXPECT_THROW(t.throwIfFailed(), eggs_t);
860     });
861   makeFuture()
862     .then([=](Try<void>&& t) {
863       EXPECT_NO_THROW(t.throwIfFailed());
864     });
865
866   makeFuture<int>(eggs)
867     .then([=](Try<int>&& t) {
868       EXPECT_THROW(t.throwIfFailed(), eggs_t);
869     });
870   makeFuture<int>(42)
871     .then([=](Try<int>&& t) {
872       EXPECT_NO_THROW(t.throwIfFailed());
873     });
874 }
875
876 TEST(Future, waitImmediate) {
877   makeFuture().wait();
878   auto done = makeFuture(42).wait().value();
879   EXPECT_EQ(42, done);
880
881   vector<int> v{1,2,3};
882   auto done_v = makeFuture(v).wait().value();
883   EXPECT_EQ(v.size(), done_v.size());
884   EXPECT_EQ(v, done_v);
885
886   vector<Future<void>> v_f;
887   v_f.push_back(makeFuture());
888   v_f.push_back(makeFuture());
889   auto done_v_f = whenAll(v_f.begin(), v_f.end()).wait().value();
890   EXPECT_EQ(2, done_v_f.size());
891
892   vector<Future<bool>> v_fb;
893   v_fb.push_back(makeFuture(true));
894   v_fb.push_back(makeFuture(false));
895   auto fut = whenAll(v_fb.begin(), v_fb.end());
896   auto done_v_fb = std::move(fut.wait().value());
897   EXPECT_EQ(2, done_v_fb.size());
898 }
899
900 TEST(Future, wait) {
901   Promise<int> p;
902   Future<int> f = p.getFuture();
903   std::atomic<bool> flag{false};
904   std::atomic<int> result{1};
905   std::atomic<std::thread::id> id;
906
907   std::thread t([&](Future<int>&& tf){
908       auto n = tf.then([&](Try<int> && t) {
909           id = std::this_thread::get_id();
910           return t.value();
911         });
912       flag = true;
913       result.store(n.wait().value());
914     },
915     std::move(f)
916     );
917   while(!flag){}
918   EXPECT_EQ(result.load(), 1);
919   p.setValue(42);
920   t.join();
921   // validate that the callback ended up executing in this thread, which
922   // is more to ensure that this test actually tests what it should
923   EXPECT_EQ(id, std::this_thread::get_id());
924   EXPECT_EQ(result.load(), 42);
925 }
926
927 TEST(Future, waitWithDuration) {
928  {
929   Promise<int> p;
930   Future<int> f = p.getFuture();
931   auto t = f.wait(std::chrono::milliseconds(1));
932   EXPECT_FALSE(t.isReady());
933   p.setValue(1);
934   EXPECT_TRUE(t.isReady());
935  }
936  {
937   Promise<int> p;
938   Future<int> f = p.getFuture();
939   p.setValue(1);
940   auto t = f.wait(std::chrono::milliseconds(1));
941   EXPECT_TRUE(t.isReady());
942  }
943  {
944   vector<Future<bool>> v_fb;
945   v_fb.push_back(makeFuture(true));
946   v_fb.push_back(makeFuture(false));
947   auto f = whenAll(v_fb.begin(), v_fb.end());
948   auto t = f.wait(std::chrono::milliseconds(1));
949   EXPECT_TRUE(t.isReady());
950   EXPECT_EQ(2, t.value().size());
951  }
952  {
953   vector<Future<bool>> v_fb;
954   Promise<bool> p1;
955   Promise<bool> p2;
956   v_fb.push_back(p1.getFuture());
957   v_fb.push_back(p2.getFuture());
958   auto f = whenAll(v_fb.begin(), v_fb.end());
959   auto t = f.wait(std::chrono::milliseconds(1));
960   EXPECT_FALSE(t.isReady());
961   p1.setValue(true);
962   EXPECT_FALSE(t.isReady());
963   p2.setValue(true);
964   EXPECT_TRUE(t.isReady());
965  }
966  {
967   auto t = makeFuture().wait(std::chrono::milliseconds(1));
968   EXPECT_TRUE(t.isReady());
969  }
970 }
971
972 TEST(Future, callbackAfterActivate) {
973   Promise<void> p;
974   auto f = p.getFuture();
975   f.deactivate();
976
977   size_t count = 0;
978   f.then([&](Try<void>&&) { count++; });
979
980   p.setValue();
981   EXPECT_EQ(0, count);
982
983   f.activate();
984   EXPECT_EQ(1, count);
985 }
986
987 TEST(Future, activateOnDestruct) {
988   auto f = std::make_shared<Future<void>>(makeFuture());
989   f->deactivate();
990
991   size_t count = 0;
992   f->then([&](Try<void>&&) { count++; });
993   EXPECT_EQ(0, count);
994
995   f.reset();
996   EXPECT_EQ(1, count);
997 }
998
999 TEST(Future, viaActsCold) {
1000   ManualExecutor x;
1001   size_t count = 0;
1002
1003   auto fv = via(&x);
1004   fv.then([&](Try<void>&&) { count++; });
1005
1006   EXPECT_EQ(0, count);
1007
1008   fv.activate();
1009
1010   EXPECT_EQ(1, x.run());
1011   EXPECT_EQ(1, count);
1012 }
1013
1014 TEST(Future, viaIsCold) {
1015   ManualExecutor x;
1016   EXPECT_FALSE(via(&x).isActive());
1017 }
1018
1019 TEST(Future, viaRaces) {
1020   ManualExecutor x;
1021   Promise<void> p;
1022   auto tid = std::this_thread::get_id();
1023   bool done = false;
1024
1025   std::thread t1([&] {
1026     p.getFuture()
1027       .via(&x)
1028       .then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
1029       .then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
1030       .then([&](Try<void>&&) { done = true; });
1031   });
1032
1033   std::thread t2([&] {
1034     p.setValue();
1035   });
1036
1037   while (!done) x.run();
1038   t1.join();
1039   t2.join();
1040 }
1041
1042 // TODO(#4920689)
1043 TEST(Future, viaRaces_2stage) {
1044   ManualExecutor x;
1045   Promise<void> p;
1046   auto tid = std::this_thread::get_id();
1047   bool done = false;
1048
1049   std::thread t1([&] {
1050     auto f2 = p.getFuture().via(&x);
1051     f2.then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
1052       .then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
1053       .then([&](Try<void>&&) { done = true; });
1054
1055     // the bug was in the promise being fulfilled before f2 is reactivated. we
1056     // could sleep, but yielding should cause this to fail with reasonable
1057     // probability
1058     std::this_thread::yield();
1059     f2.activate();
1060   });
1061
1062   std::thread t2([&] {
1063     p.setValue();
1064   });
1065
1066   while (!done) x.run();
1067   t1.join();
1068   t2.join();
1069 }
1070
1071 TEST(Future, getFuture_after_setValue) {
1072   Promise<int> p;
1073   p.setValue(42);
1074   EXPECT_EQ(42, p.getFuture().value());
1075 }
1076
1077 TEST(Future, getFuture_after_setException) {
1078   Promise<void> p;
1079   p.fulfil([]() -> void { throw std::logic_error("foo"); });
1080   EXPECT_THROW(p.getFuture().value(), std::logic_error);
1081 }
1082
1083 TEST(Future, detachRace) {
1084   // Task #5438209
1085   // This test is designed to detect a race that was in Core::detachOne()
1086   // where detached_ was incremented and then tested, and that
1087   // allowed a race where both Promise and Future would think they were the
1088   // second and both try to delete. This showed up at scale but was very
1089   // difficult to reliably repro in a test. As it is, this only fails about
1090   // once in every 1,000 executions. Doing this 1,000 times is going to make a
1091   // slow test so I won't do that but if it ever fails, take it seriously, and
1092   // run the test binary with "--gtest_repeat=10000 --gtest_filter=*detachRace"
1093   // (Don't forget to enable ASAN)
1094   auto p = folly::make_unique<Promise<bool>>();
1095   auto f = folly::make_unique<Future<bool>>(p->getFuture());
1096   folly::Baton<> baton;
1097   std::thread t1([&]{
1098     baton.post();
1099     p.reset();
1100   });
1101   baton.wait();
1102   f.reset();
1103   t1.join();
1104 }
1105
1106 class TestData : public RequestData {
1107  public:
1108   explicit TestData(int data) : data_(data) {}
1109   virtual ~TestData() {}
1110   int data_;
1111 };
1112
1113 TEST(Future, context) {
1114
1115   // Start a new context
1116   RequestContext::create();
1117
1118   EXPECT_EQ(nullptr, RequestContext::get()->getContextData("test"));
1119
1120   // Set some test data
1121   RequestContext::get()->setContextData(
1122     "test",
1123     std::unique_ptr<TestData>(new TestData(10)));
1124
1125   // Start a future
1126   Promise<void> p;
1127   auto future = p.getFuture().then([&]{
1128     // Check that the context followed the future
1129     EXPECT_TRUE(RequestContext::get() != nullptr);
1130     auto a = dynamic_cast<TestData*>(
1131       RequestContext::get()->getContextData("test"));
1132     auto data = a->data_;
1133     EXPECT_EQ(10, data);
1134   });
1135
1136   // Clear the context
1137   RequestContext::setContext(nullptr);
1138
1139   EXPECT_EQ(nullptr, RequestContext::get()->getContextData("test"));
1140
1141   // Fulfil the promise
1142   p.setValue();
1143 }
1144
1145
1146 // This only fails about 1 in 1k times when the bug is present :(
1147 TEST(Future, t5506504) {
1148   ThreadExecutor x;
1149
1150   auto fn = [&x]{
1151     auto promises = std::make_shared<vector<Promise<void>>>(4);
1152     vector<Future<void>> futures;
1153
1154     for (auto& p : *promises) {
1155       futures.emplace_back(
1156         p.getFuture()
1157         .via(&x)
1158         .then([](Try<void>&&){}));
1159     }
1160
1161     x.waitForStartup();
1162     x.add([promises]{
1163       for (auto& p : *promises) p.setValue();
1164     });
1165
1166     return whenAll(futures.begin(), futures.end());
1167   };
1168
1169   fn().wait();
1170 }
1171
1172 // Test of handling of a circular dependency. It's never recommended
1173 // to have one because of possible memory leaks. Here we test that
1174 // we can handle freeing of the Future while it is running.
1175 TEST(Future, CircularDependencySharedPtrSelfReset) {
1176   Promise<int64_t> promise;
1177   auto ptr = std::make_shared<Future<int64_t>>(promise.getFuture());
1178
1179   ptr->then(
1180     [ptr] (folly::Try<int64_t>&& uid) mutable {
1181       EXPECT_EQ(1, ptr.use_count());
1182
1183       // Leaving no references to ourselves.
1184       ptr.reset();
1185       EXPECT_EQ(0, ptr.use_count());
1186     }
1187   );
1188
1189   EXPECT_EQ(2, ptr.use_count());
1190
1191   ptr.reset();
1192
1193   promise.fulfil([]{return 1l;});
1194 }