kill remaining Futures-related Wangle references
[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([](Try<pair<size_t, Try<int>>>&& f) {
717         EXPECT_EQ(42, f.value().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([&](Try<vector<Try<void>>>&& t) {
734         EXPECT_EQ(fs.size(), t.value().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([&](Try<pair<size_t, Try<int>>>&& t) {
744         auto& p = t.value();
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([&](Try<vector<pair<size_t, Try<void>>>>&& t) {
761       flag = true;
762       auto v = t.value();
763       EXPECT_EQ(n, v.size());
764       for (auto& tt : v)
765         EXPECT_TRUE(tt.second.hasValue());
766     });
767
768   promises[0].setValue();
769   EXPECT_FALSE(flag);
770   promises[1].setValue();
771   EXPECT_FALSE(flag);
772   promises[2].setValue();
773   EXPECT_TRUE(flag);
774 }
775
776 /* Ensure that we can compile when_{all,any} with folly::small_vector */
777 TEST(when, small_vector) {
778
779   static_assert(!FOLLY_IS_TRIVIALLY_COPYABLE(Future<void>),
780                 "Futures should not be trivially copyable");
781   static_assert(!FOLLY_IS_TRIVIALLY_COPYABLE(Future<int>),
782                 "Futures should not be trivially copyable");
783
784   using folly::small_vector;
785   {
786     small_vector<Future<void>> futures;
787
788     for (int i = 0; i < 10; i++)
789       futures.push_back(makeFuture());
790
791     auto anyf = whenAny(futures.begin(), futures.end());
792   }
793
794   {
795     small_vector<Future<void>> futures;
796
797     for (int i = 0; i < 10; i++)
798       futures.push_back(makeFuture());
799
800     auto allf = whenAll(futures.begin(), futures.end());
801   }
802 }
803
804 TEST(Future, whenAllVariadic) {
805   Promise<bool> pb;
806   Promise<int> pi;
807   Future<bool> fb = pb.getFuture();
808   Future<int> fi = pi.getFuture();
809   bool flag = false;
810   whenAll(std::move(fb), std::move(fi))
811     .then([&](Try<std::tuple<Try<bool>, Try<int>>>&& t) {
812       flag = true;
813       EXPECT_TRUE(t.hasValue());
814       EXPECT_TRUE(std::get<0>(t.value()).hasValue());
815       EXPECT_EQ(std::get<0>(t.value()).value(), true);
816       EXPECT_TRUE(std::get<1>(t.value()).hasValue());
817       EXPECT_EQ(std::get<1>(t.value()).value(), 42);
818     });
819   pb.setValue(true);
820   EXPECT_FALSE(flag);
821   pi.setValue(42);
822   EXPECT_TRUE(flag);
823 }
824
825 TEST(Future, whenAllVariadicReferences) {
826   Promise<bool> pb;
827   Promise<int> pi;
828   Future<bool> fb = pb.getFuture();
829   Future<int> fi = pi.getFuture();
830   bool flag = false;
831   whenAll(fb, fi)
832     .then([&](Try<std::tuple<Try<bool>, Try<int>>>&& t) {
833       flag = true;
834       EXPECT_TRUE(t.hasValue());
835       EXPECT_TRUE(std::get<0>(t.value()).hasValue());
836       EXPECT_EQ(std::get<0>(t.value()).value(), true);
837       EXPECT_TRUE(std::get<1>(t.value()).hasValue());
838       EXPECT_EQ(std::get<1>(t.value()).value(), 42);
839     });
840   pb.setValue(true);
841   EXPECT_FALSE(flag);
842   pi.setValue(42);
843   EXPECT_TRUE(flag);
844 }
845
846 TEST(Future, whenAll_none) {
847   vector<Future<int>> fs;
848   auto f = whenAll(fs.begin(), fs.end());
849   EXPECT_TRUE(f.isReady());
850 }
851
852 TEST(Future, throwCaughtInImmediateThen) {
853   // Neither of these should throw "Promise already satisfied"
854   makeFuture().then(
855     [=](Try<void>&&) -> int { throw std::exception(); });
856   makeFuture().then(
857     [=](Try<void>&&) -> Future<int> { throw std::exception(); });
858 }
859
860 TEST(Future, throwIfFailed) {
861   makeFuture<void>(eggs)
862     .then([=](Try<void>&& t) {
863       EXPECT_THROW(t.throwIfFailed(), eggs_t);
864     });
865   makeFuture()
866     .then([=](Try<void>&& t) {
867       EXPECT_NO_THROW(t.throwIfFailed());
868     });
869
870   makeFuture<int>(eggs)
871     .then([=](Try<int>&& t) {
872       EXPECT_THROW(t.throwIfFailed(), eggs_t);
873     });
874   makeFuture<int>(42)
875     .then([=](Try<int>&& t) {
876       EXPECT_NO_THROW(t.throwIfFailed());
877     });
878 }
879
880 TEST(Future, waitWithSemaphoreImmediate) {
881   waitWithSemaphore(makeFuture());
882   auto done = waitWithSemaphore(makeFuture(42)).value();
883   EXPECT_EQ(42, done);
884
885   vector<int> v{1,2,3};
886   auto done_v = waitWithSemaphore(makeFuture(v)).value();
887   EXPECT_EQ(v.size(), done_v.size());
888   EXPECT_EQ(v, done_v);
889
890   vector<Future<void>> v_f;
891   v_f.push_back(makeFuture());
892   v_f.push_back(makeFuture());
893   auto done_v_f = waitWithSemaphore(whenAll(v_f.begin(), v_f.end())).value();
894   EXPECT_EQ(2, done_v_f.size());
895
896   vector<Future<bool>> v_fb;
897   v_fb.push_back(makeFuture(true));
898   v_fb.push_back(makeFuture(false));
899   auto fut = whenAll(v_fb.begin(), v_fb.end());
900   auto done_v_fb = std::move(waitWithSemaphore(std::move(fut)).value());
901   EXPECT_EQ(2, done_v_fb.size());
902 }
903
904 TEST(Future, waitWithSemaphore) {
905   Promise<int> p;
906   Future<int> f = p.getFuture();
907   std::atomic<bool> flag{false};
908   std::atomic<int> result{1};
909   std::atomic<std::thread::id> id;
910
911   std::thread t([&](Future<int>&& tf){
912       auto n = tf.then([&](Try<int> && t) {
913           id = std::this_thread::get_id();
914           return t.value();
915         });
916       flag = true;
917       result.store(waitWithSemaphore(std::move(n)).value());
918     },
919     std::move(f)
920     );
921   while(!flag){}
922   EXPECT_EQ(result.load(), 1);
923   p.setValue(42);
924   t.join();
925   // validate that the callback ended up executing in this thread, which
926   // is more to ensure that this test actually tests what it should
927   EXPECT_EQ(id, std::this_thread::get_id());
928   EXPECT_EQ(result.load(), 42);
929 }
930
931 TEST(Future, waitWithSemaphoreForTime) {
932  {
933   Promise<int> p;
934   Future<int> f = p.getFuture();
935   auto t = waitWithSemaphore(std::move(f),
936     std::chrono::microseconds(1));
937   EXPECT_FALSE(t.isReady());
938   p.setValue(1);
939   EXPECT_TRUE(t.isReady());
940  }
941  {
942   Promise<int> p;
943   Future<int> f = p.getFuture();
944   p.setValue(1);
945   auto t = waitWithSemaphore(std::move(f),
946     std::chrono::milliseconds(1));
947   EXPECT_TRUE(t.isReady());
948  }
949  {
950   vector<Future<bool>> v_fb;
951   v_fb.push_back(makeFuture(true));
952   v_fb.push_back(makeFuture(false));
953   auto f = whenAll(v_fb.begin(), v_fb.end());
954   auto t = waitWithSemaphore(std::move(f),
955     std::chrono::milliseconds(1));
956   EXPECT_TRUE(t.isReady());
957   EXPECT_EQ(2, t.value().size());
958  }
959  {
960   vector<Future<bool>> v_fb;
961   Promise<bool> p1;
962   Promise<bool> p2;
963   v_fb.push_back(p1.getFuture());
964   v_fb.push_back(p2.getFuture());
965   auto f = whenAll(v_fb.begin(), v_fb.end());
966   auto t = waitWithSemaphore(std::move(f),
967     std::chrono::milliseconds(1));
968   EXPECT_FALSE(t.isReady());
969   p1.setValue(true);
970   EXPECT_FALSE(t.isReady());
971   p2.setValue(true);
972   EXPECT_TRUE(t.isReady());
973  }
974  {
975   auto t = waitWithSemaphore(makeFuture(),
976     std::chrono::milliseconds(1));
977   EXPECT_TRUE(t.isReady());
978  }
979 }
980
981 TEST(Future, callbackAfterActivate) {
982   Promise<void> p;
983   auto f = p.getFuture();
984   f.deactivate();
985
986   size_t count = 0;
987   f.then([&](Try<void>&&) { count++; });
988
989   p.setValue();
990   EXPECT_EQ(0, count);
991
992   f.activate();
993   EXPECT_EQ(1, count);
994 }
995
996 TEST(Future, activateOnDestruct) {
997   auto f = std::make_shared<Future<void>>(makeFuture());
998   f->deactivate();
999
1000   size_t count = 0;
1001   f->then([&](Try<void>&&) { count++; });
1002   EXPECT_EQ(0, count);
1003
1004   f.reset();
1005   EXPECT_EQ(1, count);
1006 }
1007
1008 TEST(Future, viaActsCold) {
1009   ManualExecutor x;
1010   size_t count = 0;
1011
1012   auto fv = via(&x);
1013   fv.then([&](Try<void>&&) { count++; });
1014
1015   EXPECT_EQ(0, count);
1016
1017   fv.activate();
1018
1019   EXPECT_EQ(1, x.run());
1020   EXPECT_EQ(1, count);
1021 }
1022
1023 TEST(Future, viaIsCold) {
1024   ManualExecutor x;
1025   EXPECT_FALSE(via(&x).isActive());
1026 }
1027
1028 TEST(Future, viaRaces) {
1029   ManualExecutor x;
1030   Promise<void> p;
1031   auto tid = std::this_thread::get_id();
1032   bool done = false;
1033
1034   std::thread t1([&] {
1035     p.getFuture()
1036       .via(&x)
1037       .then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
1038       .then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
1039       .then([&](Try<void>&&) { done = true; });
1040   });
1041
1042   std::thread t2([&] {
1043     p.setValue();
1044   });
1045
1046   while (!done) x.run();
1047   t1.join();
1048   t2.join();
1049 }
1050
1051 // TODO(#4920689)
1052 TEST(Future, viaRaces_2stage) {
1053   ManualExecutor x;
1054   Promise<void> p;
1055   auto tid = std::this_thread::get_id();
1056   bool done = false;
1057
1058   std::thread t1([&] {
1059     auto f2 = p.getFuture().via(&x);
1060     f2.then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
1061       .then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
1062       .then([&](Try<void>&&) { done = true; });
1063
1064     // the bug was in the promise being fulfilled before f2 is reactivated. we
1065     // could sleep, but yielding should cause this to fail with reasonable
1066     // probability
1067     std::this_thread::yield();
1068     f2.activate();
1069   });
1070
1071   std::thread t2([&] {
1072     p.setValue();
1073   });
1074
1075   while (!done) x.run();
1076   t1.join();
1077   t2.join();
1078 }
1079
1080 TEST(Future, getFuture_after_setValue) {
1081   Promise<int> p;
1082   p.setValue(42);
1083   EXPECT_EQ(42, p.getFuture().value());
1084 }
1085
1086 TEST(Future, getFuture_after_setException) {
1087   Promise<void> p;
1088   p.fulfil([]() -> void { throw std::logic_error("foo"); });
1089   EXPECT_THROW(p.getFuture().value(), std::logic_error);
1090 }
1091
1092 TEST(Future, detachRace) {
1093   // Task #5438209
1094   // This test is designed to detect a race that was in Core::detachOne()
1095   // where detached_ was incremented and then tested, and that
1096   // allowed a race where both Promise and Future would think they were the
1097   // second and both try to delete. This showed up at scale but was very
1098   // difficult to reliably repro in a test. As it is, this only fails about
1099   // once in every 1,000 executions. Doing this 1,000 times is going to make a
1100   // slow test so I won't do that but if it ever fails, take it seriously, and
1101   // run the test binary with "--gtest_repeat=10000 --gtest_filter=*detachRace"
1102   // (Don't forget to enable ASAN)
1103   auto p = folly::make_unique<Promise<bool>>();
1104   auto f = folly::make_unique<Future<bool>>(p->getFuture());
1105   folly::Baton<> baton;
1106   std::thread t1([&]{
1107     baton.post();
1108     p.reset();
1109   });
1110   baton.wait();
1111   f.reset();
1112   t1.join();
1113 }
1114
1115 class TestData : public RequestData {
1116  public:
1117   explicit TestData(int data) : data_(data) {}
1118   virtual ~TestData() {}
1119   int data_;
1120 };
1121
1122 TEST(Future, context) {
1123
1124   // Start a new context
1125   RequestContext::create();
1126
1127   EXPECT_EQ(nullptr, RequestContext::get()->getContextData("test"));
1128
1129   // Set some test data
1130   RequestContext::get()->setContextData(
1131     "test",
1132     std::unique_ptr<TestData>(new TestData(10)));
1133
1134   // Start a future
1135   Promise<void> p;
1136   auto future = p.getFuture().then([&]{
1137     // Check that the context followed the future
1138     EXPECT_TRUE(RequestContext::get() != nullptr);
1139     auto a = dynamic_cast<TestData*>(
1140       RequestContext::get()->getContextData("test"));
1141     auto data = a->data_;
1142     EXPECT_EQ(10, data);
1143   });
1144
1145   // Clear the context
1146   RequestContext::setContext(nullptr);
1147
1148   EXPECT_EQ(nullptr, RequestContext::get()->getContextData("test"));
1149
1150   // Fulfil the promise
1151   p.setValue();
1152 }
1153
1154
1155 // This only fails about 1 in 1k times when the bug is present :(
1156 TEST(Future, t5506504) {
1157   ThreadExecutor x;
1158
1159   auto fn = [&x]{
1160     auto promises = std::make_shared<vector<Promise<void>>>(4);
1161     vector<Future<void>> futures;
1162
1163     for (auto& p : *promises) {
1164       futures.emplace_back(
1165         p.getFuture()
1166         .via(&x)
1167         .then([](Try<void>&&){}));
1168     }
1169
1170     x.waitForStartup();
1171     x.add([promises]{
1172       for (auto& p : *promises) p.setValue();
1173     });
1174
1175     return whenAll(futures.begin(), futures.end());
1176   };
1177
1178   waitWithSemaphore(fn());
1179 }
1180
1181 // Test of handling of a circular dependency. It's never recommended
1182 // to have one because of possible memory leaks. Here we test that
1183 // we can handle freeing of the Future while it is running.
1184 TEST(Future, CircularDependencySharedPtrSelfReset) {
1185   Promise<int64_t> promise;
1186   auto ptr = std::make_shared<Future<int64_t>>(promise.getFuture());
1187
1188   ptr->then(
1189     [ptr] (folly::Try<int64_t>&& uid) mutable {
1190       EXPECT_EQ(1, ptr.use_count());
1191
1192       // Leaving no references to ourselves.
1193       ptr.reset();
1194       EXPECT_EQ(0, ptr.use_count());
1195     }
1196   );
1197
1198   EXPECT_EQ(2, ptr.use_count());
1199
1200   ptr.reset();
1201
1202   promise.fulfil([]{return 1l;});
1203 }