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