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