(Wangle) window
[folly.git] / folly / futures / test / FutureTest.cpp
1 /*
2  * Copyright 2015 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/dynamic.h>
32 #include <folly/Baton.h>
33 #include <folly/MPMCQueue.h>
34
35 #include <folly/io/async/EventBase.h>
36 #include <folly/io/async/Request.h>
37
38 using namespace folly;
39 using std::pair;
40 using std::string;
41 using std::unique_ptr;
42 using std::vector;
43 using std::chrono::milliseconds;
44
45 #define EXPECT_TYPE(x, T) \
46   EXPECT_TRUE((std::is_same<decltype(x), T>::value))
47
48 /// Simple executor that does work in another thread
49 class ThreadExecutor : public Executor {
50   folly::MPMCQueue<Func> funcs;
51   std::atomic<bool> done {false};
52   std::thread worker;
53   folly::Baton<> baton;
54
55   void work() {
56     baton.post();
57     Func fn;
58     while (!done) {
59       while (!funcs.isEmpty()) {
60         funcs.blockingRead(fn);
61         fn();
62       }
63     }
64   }
65
66  public:
67   explicit ThreadExecutor(size_t n = 1024)
68     : funcs(n) {
69     worker = std::thread(std::bind(&ThreadExecutor::work, this));
70   }
71
72   ~ThreadExecutor() {
73     done = true;
74     funcs.write([]{});
75     worker.join();
76   }
77
78   void add(Func fn) override {
79     funcs.blockingWrite(std::move(fn));
80   }
81
82   void waitForStartup() {
83     baton.wait();
84   }
85 };
86
87 typedef FutureException eggs_t;
88 static eggs_t eggs("eggs");
89
90 // Core
91
92 TEST(Future, coreSize) {
93   // If this number goes down, it's fine!
94   // If it goes up, please seek professional advice ;-)
95   EXPECT_EQ(192, sizeof(detail::Core<void>));
96 }
97
98 // Future
99
100 TEST(Future, onError) {
101   bool theFlag = false;
102   auto flag = [&]{ theFlag = true; };
103 #define EXPECT_FLAG() \
104   do { \
105     EXPECT_TRUE(theFlag); \
106     theFlag = false; \
107   } while(0);
108
109 #define EXPECT_NO_FLAG() \
110   do { \
111     EXPECT_FALSE(theFlag); \
112     theFlag = false; \
113   } while(0);
114
115   // By reference
116   {
117     auto f = makeFuture()
118       .then([] { throw eggs; })
119       .onError([&] (eggs_t& e) { flag(); });
120     EXPECT_FLAG();
121     EXPECT_NO_THROW(f.value());
122   }
123
124   {
125     auto f = makeFuture()
126       .then([] { throw eggs; })
127       .onError([&] (eggs_t& e) { flag(); return makeFuture(); });
128     EXPECT_FLAG();
129     EXPECT_NO_THROW(f.value());
130   }
131
132   // By value
133   {
134     auto f = makeFuture()
135       .then([] { throw eggs; })
136       .onError([&] (eggs_t e) { flag(); });
137     EXPECT_FLAG();
138     EXPECT_NO_THROW(f.value());
139   }
140
141   {
142     auto f = makeFuture()
143       .then([] { throw eggs; })
144       .onError([&] (eggs_t e) { flag(); return makeFuture(); });
145     EXPECT_FLAG();
146     EXPECT_NO_THROW(f.value());
147   }
148
149   // Polymorphic
150   {
151     auto f = makeFuture()
152       .then([] { throw eggs; })
153       .onError([&] (std::exception& e) { flag(); });
154     EXPECT_FLAG();
155     EXPECT_NO_THROW(f.value());
156   }
157
158   {
159     auto f = makeFuture()
160       .then([] { throw eggs; })
161       .onError([&] (std::exception& e) { flag(); return makeFuture(); });
162     EXPECT_FLAG();
163     EXPECT_NO_THROW(f.value());
164   }
165
166   // Non-exceptions
167   {
168     auto f = makeFuture()
169       .then([] { throw -1; })
170       .onError([&] (int e) { flag(); });
171     EXPECT_FLAG();
172     EXPECT_NO_THROW(f.value());
173   }
174
175   {
176     auto f = makeFuture()
177       .then([] { throw -1; })
178       .onError([&] (int e) { flag(); return makeFuture(); });
179     EXPECT_FLAG();
180     EXPECT_NO_THROW(f.value());
181   }
182
183   // Mutable lambda
184   {
185     auto f = makeFuture()
186       .then([] { throw eggs; })
187       .onError([&] (eggs_t& e) mutable { flag(); });
188     EXPECT_FLAG();
189     EXPECT_NO_THROW(f.value());
190   }
191
192   {
193     auto f = makeFuture()
194       .then([] { throw eggs; })
195       .onError([&] (eggs_t& e) mutable { flag(); return makeFuture(); });
196     EXPECT_FLAG();
197     EXPECT_NO_THROW(f.value());
198   }
199
200   // No throw
201   {
202     auto f = makeFuture()
203       .then([] { return 42; })
204       .onError([&] (eggs_t& e) { flag(); return -1; });
205     EXPECT_NO_FLAG();
206     EXPECT_EQ(42, f.value());
207   }
208
209   {
210     auto f = makeFuture()
211       .then([] { return 42; })
212       .onError([&] (eggs_t& e) { flag(); return makeFuture<int>(-1); });
213     EXPECT_NO_FLAG();
214     EXPECT_EQ(42, f.value());
215   }
216
217   // Catch different exception
218   {
219     auto f = makeFuture()
220       .then([] { throw eggs; })
221       .onError([&] (std::runtime_error& e) { flag(); });
222     EXPECT_NO_FLAG();
223     EXPECT_THROW(f.value(), eggs_t);
224   }
225
226   {
227     auto f = makeFuture()
228       .then([] { throw eggs; })
229       .onError([&] (std::runtime_error& e) { flag(); return makeFuture(); });
230     EXPECT_NO_FLAG();
231     EXPECT_THROW(f.value(), eggs_t);
232   }
233
234   // Returned value propagates
235   {
236     auto f = makeFuture()
237       .then([] { throw eggs; return 0; })
238       .onError([&] (eggs_t& e) { return 42; });
239     EXPECT_EQ(42, f.value());
240   }
241
242   // Returned future propagates
243   {
244     auto f = makeFuture()
245       .then([] { throw eggs; return 0; })
246       .onError([&] (eggs_t& e) { return makeFuture<int>(42); });
247     EXPECT_EQ(42, f.value());
248   }
249
250   // Throw in callback
251   {
252     auto f = makeFuture()
253       .then([] { throw eggs; return 0; })
254       .onError([&] (eggs_t& e) { throw e; return -1; });
255     EXPECT_THROW(f.value(), eggs_t);
256   }
257
258   {
259     auto f = makeFuture()
260       .then([] { throw eggs; return 0; })
261       .onError([&] (eggs_t& e) { throw e; return makeFuture<int>(-1); });
262     EXPECT_THROW(f.value(), eggs_t);
263   }
264
265   // exception_wrapper, return Future<T>
266   {
267     auto f = makeFuture()
268       .then([] { throw eggs; })
269       .onError([&] (exception_wrapper e) { flag(); return makeFuture(); });
270     EXPECT_FLAG();
271     EXPECT_NO_THROW(f.value());
272   }
273
274   // exception_wrapper, return Future<T> but throw
275   {
276     auto f = makeFuture()
277       .then([]{ throw eggs; return 0; })
278       .onError([&] (exception_wrapper e) {
279         flag();
280         throw eggs;
281         return makeFuture<int>(-1);
282       });
283     EXPECT_FLAG();
284     EXPECT_THROW(f.value(), eggs_t);
285   }
286
287   // exception_wrapper, return T
288   {
289     auto f = makeFuture()
290       .then([]{ throw eggs; return 0; })
291       .onError([&] (exception_wrapper e) {
292         flag();
293         return -1;
294       });
295     EXPECT_FLAG();
296     EXPECT_EQ(-1, f.value());
297   }
298
299   // exception_wrapper, return T but throw
300   {
301     auto f = makeFuture()
302       .then([]{ throw eggs; return 0; })
303       .onError([&] (exception_wrapper e) {
304         flag();
305         throw eggs;
306         return -1;
307       });
308     EXPECT_FLAG();
309     EXPECT_THROW(f.value(), eggs_t);
310   }
311
312   // const exception_wrapper&
313   {
314     auto f = makeFuture()
315       .then([] { throw eggs; })
316       .onError([&] (const exception_wrapper& e) {
317         flag();
318         return makeFuture();
319       });
320     EXPECT_FLAG();
321     EXPECT_NO_THROW(f.value());
322   }
323
324 }
325
326 TEST(Future, try) {
327   class A {
328    public:
329     A(int x) : x_(x) {}
330
331     int x() const {
332       return x_;
333     }
334    private:
335     int x_;
336   };
337
338   A a(5);
339   Try<A> t_a(std::move(a));
340
341   Try<void> t_void;
342
343   EXPECT_EQ(5, t_a.value().x());
344 }
345
346 TEST(Future, special) {
347   EXPECT_FALSE(std::is_copy_constructible<Future<int>>::value);
348   EXPECT_FALSE(std::is_copy_assignable<Future<int>>::value);
349   EXPECT_TRUE(std::is_move_constructible<Future<int>>::value);
350   EXPECT_TRUE(std::is_move_assignable<Future<int>>::value);
351 }
352
353 TEST(Future, then) {
354   auto f = makeFuture<string>("0")
355     .then([](){ return makeFuture<string>("1"); })
356     .then([](Try<string>&& t) { return makeFuture(t.value() + ";2"); })
357     .then([](const Try<string>&& t) { return makeFuture(t.value() + ";3"); })
358     .then([](Try<string>& t) { return makeFuture(t.value() + ";4"); })
359     .then([](const Try<string>& t) { return makeFuture(t.value() + ";5"); })
360     .then([](Try<string> t) { return makeFuture(t.value() + ";6"); })
361     .then([](const Try<string> t) { return makeFuture(t.value() + ";7"); })
362     .then([](string&& s) { return makeFuture(s + ";8"); })
363     .then([](const string&& s) { return makeFuture(s + ";9"); })
364     .then([](string& s) { return makeFuture(s + ";10"); })
365     .then([](const string& s) { return makeFuture(s + ";11"); })
366     .then([](string s) { return makeFuture(s + ";12"); })
367     .then([](const string s) { return makeFuture(s + ";13"); })
368   ;
369   EXPECT_EQ(f.value(), "1;2;3;4;5;6;7;8;9;10;11;12;13");
370 }
371
372 TEST(Future, thenTry) {
373   bool flag = false;
374
375   makeFuture<int>(42).then([&](Try<int>&& t) {
376                               flag = true;
377                               EXPECT_EQ(42, t.value());
378                             });
379   EXPECT_TRUE(flag); flag = false;
380
381   makeFuture<int>(42)
382     .then([](Try<int>&& t) { return t.value(); })
383     .then([&](Try<int>&& t) { flag = true; EXPECT_EQ(42, t.value()); });
384   EXPECT_TRUE(flag); flag = false;
385
386   makeFuture().then([&](Try<void>&& t) { flag = true; t.value(); });
387   EXPECT_TRUE(flag); flag = false;
388
389   Promise<void> p;
390   auto f = p.getFuture().then([&](Try<void>&& t) { flag = true; });
391   EXPECT_FALSE(flag);
392   EXPECT_FALSE(f.isReady());
393   p.setValue();
394   EXPECT_TRUE(flag);
395   EXPECT_TRUE(f.isReady());
396 }
397
398 TEST(Future, thenValue) {
399   bool flag = false;
400   makeFuture<int>(42).then([&](int i){
401     EXPECT_EQ(42, i);
402     flag = true;
403   });
404   EXPECT_TRUE(flag); flag = false;
405
406   makeFuture<int>(42)
407     .then([](int i){ return i; })
408     .then([&](int i) { flag = true; EXPECT_EQ(42, i); });
409   EXPECT_TRUE(flag); flag = false;
410
411   makeFuture().then([&]{
412     flag = true;
413   });
414   EXPECT_TRUE(flag); flag = false;
415
416   auto f = makeFuture<int>(eggs).then([&](int i){});
417   EXPECT_THROW(f.value(), eggs_t);
418
419   f = makeFuture<void>(eggs).then([&]{});
420   EXPECT_THROW(f.value(), eggs_t);
421 }
422
423 TEST(Future, thenValueFuture) {
424   bool flag = false;
425   makeFuture<int>(42)
426     .then([](int i){ return makeFuture<int>(std::move(i)); })
427     .then([&](Try<int>&& t) { flag = true; EXPECT_EQ(42, t.value()); });
428   EXPECT_TRUE(flag); flag = false;
429
430   makeFuture()
431     .then([]{ return makeFuture(); })
432     .then([&](Try<void>&& t) { flag = true; });
433   EXPECT_TRUE(flag); flag = false;
434 }
435
436 static string doWorkStatic(Try<string>&& t) {
437   return t.value() + ";static";
438 }
439
440 TEST(Future, thenFunction) {
441   struct Worker {
442     string doWork(Try<string>&& t) {
443       return t.value() + ";class";
444     }
445     static string doWorkStatic(Try<string>&& t) {
446       return t.value() + ";class-static";
447     }
448   } w;
449
450   auto f = makeFuture<string>("start")
451     .then(doWorkStatic)
452     .then(Worker::doWorkStatic)
453     .then(&Worker::doWork, &w);
454
455   EXPECT_EQ(f.value(), "start;static;class-static;class");
456 }
457
458 static Future<string> doWorkStaticFuture(Try<string>&& t) {
459   return makeFuture(t.value() + ";static");
460 }
461
462 TEST(Future, thenFunctionFuture) {
463   struct Worker {
464     Future<string> doWorkFuture(Try<string>&& t) {
465       return makeFuture(t.value() + ";class");
466     }
467     static Future<string> doWorkStaticFuture(Try<string>&& t) {
468       return makeFuture(t.value() + ";class-static");
469     }
470   } w;
471
472   auto f = makeFuture<string>("start")
473     .then(doWorkStaticFuture)
474     .then(Worker::doWorkStaticFuture)
475     .then(&Worker::doWorkFuture, &w);
476
477   EXPECT_EQ(f.value(), "start;static;class-static;class");
478 }
479
480 TEST(Future, thenBind) {
481   auto l = []() {
482     return makeFuture("bind");
483   };
484   auto b = std::bind(l);
485   auto f = makeFuture().then(std::move(b));
486   EXPECT_EQ(f.value(), "bind");
487 }
488
489 TEST(Future, thenBindTry) {
490   auto l = [](Try<string>&& t) {
491     return makeFuture(t.value() + ";bind");
492   };
493   auto b = std::bind(l, std::placeholders::_1);
494   auto f = makeFuture<string>("start").then(std::move(b));
495
496   EXPECT_EQ(f.value(), "start;bind");
497 }
498
499 TEST(Future, value) {
500   auto f = makeFuture(unique_ptr<int>(new int(42)));
501   auto up = std::move(f.value());
502   EXPECT_EQ(42, *up);
503
504   EXPECT_THROW(makeFuture<int>(eggs).value(), eggs_t);
505 }
506
507 TEST(Future, isReady) {
508   Promise<int> p;
509   auto f = p.getFuture();
510   EXPECT_FALSE(f.isReady());
511   p.setValue(42);
512   EXPECT_TRUE(f.isReady());
513   }
514
515 TEST(Future, futureNotReady) {
516   Promise<int> p;
517   Future<int> f = p.getFuture();
518   EXPECT_THROW(f.value(), eggs_t);
519 }
520
521 TEST(Future, hasException) {
522   EXPECT_TRUE(makeFuture<int>(eggs).getTry().hasException());
523   EXPECT_FALSE(makeFuture(42).getTry().hasException());
524 }
525
526 TEST(Future, hasValue) {
527   EXPECT_TRUE(makeFuture(42).getTry().hasValue());
528   EXPECT_FALSE(makeFuture<int>(eggs).getTry().hasValue());
529 }
530
531 TEST(Future, makeFuture) {
532   EXPECT_TYPE(makeFuture(42), Future<int>);
533   EXPECT_EQ(42, makeFuture(42).value());
534
535   EXPECT_TYPE(makeFuture<float>(42), Future<float>);
536   EXPECT_EQ(42, makeFuture<float>(42).value());
537
538   auto fun = [] { return 42; };
539   EXPECT_TYPE(makeFutureWith(fun), Future<int>);
540   EXPECT_EQ(42, makeFutureWith(fun).value());
541
542   auto failfun = []() -> int { throw eggs; };
543   EXPECT_TYPE(makeFutureWith(failfun), Future<int>);
544   EXPECT_THROW(makeFutureWith(failfun).value(), eggs_t);
545
546   EXPECT_TYPE(makeFuture(), Future<void>);
547 }
548
549 // Promise
550
551 TEST(Promise, special) {
552   EXPECT_FALSE(std::is_copy_constructible<Promise<int>>::value);
553   EXPECT_FALSE(std::is_copy_assignable<Promise<int>>::value);
554   EXPECT_TRUE(std::is_move_constructible<Promise<int>>::value);
555   EXPECT_TRUE(std::is_move_assignable<Promise<int>>::value);
556 }
557
558 TEST(Promise, getFuture) {
559   Promise<int> p;
560   Future<int> f = p.getFuture();
561   EXPECT_FALSE(f.isReady());
562 }
563
564 TEST(Promise, setValue) {
565   Promise<int> fund;
566   auto ffund = fund.getFuture();
567   fund.setValue(42);
568   EXPECT_EQ(42, ffund.value());
569
570   struct Foo {
571     string name;
572     int value;
573   };
574
575   Promise<Foo> pod;
576   auto fpod = pod.getFuture();
577   Foo f = {"the answer", 42};
578   pod.setValue(f);
579   Foo f2 = fpod.value();
580   EXPECT_EQ(f.name, f2.name);
581   EXPECT_EQ(f.value, f2.value);
582
583   pod = Promise<Foo>();
584   fpod = pod.getFuture();
585   pod.setValue(std::move(f2));
586   Foo f3 = fpod.value();
587   EXPECT_EQ(f.name, f3.name);
588   EXPECT_EQ(f.value, f3.value);
589
590   Promise<unique_ptr<int>> mov;
591   auto fmov = mov.getFuture();
592   mov.setValue(unique_ptr<int>(new int(42)));
593   unique_ptr<int> ptr = std::move(fmov.value());
594   EXPECT_EQ(42, *ptr);
595
596   Promise<void> v;
597   auto fv = v.getFuture();
598   v.setValue();
599   EXPECT_TRUE(fv.isReady());
600 }
601
602 TEST(Promise, setException) {
603   {
604     Promise<void> p;
605     auto f = p.getFuture();
606     p.setException(eggs);
607     EXPECT_THROW(f.value(), eggs_t);
608   }
609   {
610     Promise<void> p;
611     auto f = p.getFuture();
612     try {
613       throw eggs;
614     } catch (...) {
615       p.setException(exception_wrapper(std::current_exception()));
616     }
617     EXPECT_THROW(f.value(), eggs_t);
618   }
619 }
620
621 TEST(Promise, setWith) {
622   {
623     Promise<int> p;
624     auto f = p.getFuture();
625     p.setWith([] { return 42; });
626     EXPECT_EQ(42, f.value());
627   }
628   {
629     Promise<int> p;
630     auto f = p.getFuture();
631     p.setWith([]() -> int { throw eggs; });
632     EXPECT_THROW(f.value(), eggs_t);
633   }
634 }
635
636 TEST(Future, finish) {
637   auto x = std::make_shared<int>(0);
638   {
639     Promise<int> p;
640     auto f = p.getFuture().then([x](Try<int>&& t) { *x = t.value(); });
641
642     // The callback hasn't executed
643     EXPECT_EQ(0, *x);
644
645     // The callback has a reference to x
646     EXPECT_EQ(2, x.use_count());
647
648     p.setValue(42);
649
650     // the callback has executed
651     EXPECT_EQ(42, *x);
652   }
653   // the callback has been destructed
654   // and has released its reference to x
655   EXPECT_EQ(1, x.use_count());
656 }
657
658 TEST(Future, unwrap) {
659   Promise<int> a;
660   Promise<int> b;
661
662   auto fa = a.getFuture();
663   auto fb = b.getFuture();
664
665   bool flag1 = false;
666   bool flag2 = false;
667
668   // do a, then do b, and get the result of a + b.
669   Future<int> f = fa.then([&](Try<int>&& ta) {
670     auto va = ta.value();
671     flag1 = true;
672     return fb.then([va, &flag2](Try<int>&& tb) {
673       flag2 = true;
674       return va + tb.value();
675     });
676   });
677
678   EXPECT_FALSE(flag1);
679   EXPECT_FALSE(flag2);
680   EXPECT_FALSE(f.isReady());
681
682   a.setValue(3);
683   EXPECT_TRUE(flag1);
684   EXPECT_FALSE(flag2);
685   EXPECT_FALSE(f.isReady());
686
687   b.setValue(4);
688   EXPECT_TRUE(flag1);
689   EXPECT_TRUE(flag2);
690   EXPECT_EQ(7, f.value());
691 }
692
693 TEST(Future, stream) {
694   auto fn = [](vector<int> input, size_t window_size, size_t expect) {
695     auto res = reduce(
696       window(
697         input,
698         [](int i) { return makeFuture(i); },
699         2),
700       0,
701       [](int sum, const Try<int>& b) {
702         return sum + *b;
703       }).get();
704     EXPECT_EQ(expect, res);
705   };
706   {
707     // streaming 2 at a time
708     vector<int> input = {1, 2, 3};
709     fn(input, 2, 6);
710   }
711   {
712     // streaming 4 at a time
713     vector<int> input = {1, 2, 3};
714     fn(input, 4, 6);
715   }
716   {
717     // empty inpt
718     vector<int> input;
719     fn(input, 1, 0);
720   }
721 }
722
723 TEST(Future, collectAll) {
724   // returns a vector variant
725   {
726     vector<Promise<int>> promises(10);
727     vector<Future<int>> futures;
728
729     for (auto& p : promises)
730       futures.push_back(p.getFuture());
731
732     auto allf = collectAll(futures);
733
734     random_shuffle(promises.begin(), promises.end());
735     for (auto& p : promises) {
736       EXPECT_FALSE(allf.isReady());
737       p.setValue(42);
738     }
739
740     EXPECT_TRUE(allf.isReady());
741     auto& results = allf.value();
742     for (auto& t : results) {
743       EXPECT_EQ(42, t.value());
744     }
745   }
746
747   // check error semantics
748   {
749     vector<Promise<int>> promises(4);
750     vector<Future<int>> futures;
751
752     for (auto& p : promises)
753       futures.push_back(p.getFuture());
754
755     auto allf = collectAll(futures);
756
757
758     promises[0].setValue(42);
759     promises[1].setException(eggs);
760
761     EXPECT_FALSE(allf.isReady());
762
763     promises[2].setValue(42);
764
765     EXPECT_FALSE(allf.isReady());
766
767     promises[3].setException(eggs);
768
769     EXPECT_TRUE(allf.isReady());
770     EXPECT_FALSE(allf.getTry().hasException());
771
772     auto& results = allf.value();
773     EXPECT_EQ(42, results[0].value());
774     EXPECT_TRUE(results[1].hasException());
775     EXPECT_EQ(42, results[2].value());
776     EXPECT_TRUE(results[3].hasException());
777   }
778
779   // check that futures are ready in then()
780   {
781     vector<Promise<void>> promises(10);
782     vector<Future<void>> futures;
783
784     for (auto& p : promises)
785       futures.push_back(p.getFuture());
786
787     auto allf = collectAll(futures)
788       .then([](Try<vector<Try<void>>>&& ts) {
789         for (auto& f : ts.value())
790           f.value();
791       });
792
793     random_shuffle(promises.begin(), promises.end());
794     for (auto& p : promises)
795       p.setValue();
796     EXPECT_TRUE(allf.isReady());
797   }
798 }
799
800 TEST(Future, collect) {
801   // success case
802   {
803     vector<Promise<int>> promises(10);
804     vector<Future<int>> futures;
805
806     for (auto& p : promises)
807       futures.push_back(p.getFuture());
808
809     auto allf = collect(futures);
810
811     random_shuffle(promises.begin(), promises.end());
812     for (auto& p : promises) {
813       EXPECT_FALSE(allf.isReady());
814       p.setValue(42);
815     }
816
817     EXPECT_TRUE(allf.isReady());
818     for (auto i : allf.value()) {
819       EXPECT_EQ(42, i);
820     }
821   }
822
823   // failure case
824   {
825     vector<Promise<int>> promises(10);
826     vector<Future<int>> futures;
827
828     for (auto& p : promises)
829       futures.push_back(p.getFuture());
830
831     auto allf = collect(futures);
832
833     random_shuffle(promises.begin(), promises.end());
834     for (int i = 0; i < 10; i++) {
835       if (i < 5) {
836         // everthing goes well so far...
837         EXPECT_FALSE(allf.isReady());
838         promises[i].setValue(42);
839       } else if (i == 5) {
840         // short circuit with an exception
841         EXPECT_FALSE(allf.isReady());
842         promises[i].setException(eggs);
843         EXPECT_TRUE(allf.isReady());
844       } else if (i < 8) {
845         // don't blow up on further values
846         EXPECT_TRUE(allf.isReady());
847         promises[i].setValue(42);
848       } else {
849         // don't blow up on further exceptions
850         EXPECT_TRUE(allf.isReady());
851         promises[i].setException(eggs);
852       }
853     }
854
855     EXPECT_THROW(allf.value(), eggs_t);
856   }
857
858   // void futures success case
859   {
860     vector<Promise<void>> promises(10);
861     vector<Future<void>> futures;
862
863     for (auto& p : promises)
864       futures.push_back(p.getFuture());
865
866     auto allf = collect(futures);
867
868     random_shuffle(promises.begin(), promises.end());
869     for (auto& p : promises) {
870       EXPECT_FALSE(allf.isReady());
871       p.setValue();
872     }
873
874     EXPECT_TRUE(allf.isReady());
875   }
876
877   // void futures failure case
878   {
879     vector<Promise<void>> promises(10);
880     vector<Future<void>> futures;
881
882     for (auto& p : promises)
883       futures.push_back(p.getFuture());
884
885     auto allf = collect(futures);
886
887     random_shuffle(promises.begin(), promises.end());
888     for (int i = 0; i < 10; i++) {
889       if (i < 5) {
890         // everthing goes well so far...
891         EXPECT_FALSE(allf.isReady());
892         promises[i].setValue();
893       } else if (i == 5) {
894         // short circuit with an exception
895         EXPECT_FALSE(allf.isReady());
896         promises[i].setException(eggs);
897         EXPECT_TRUE(allf.isReady());
898       } else if (i < 8) {
899         // don't blow up on further values
900         EXPECT_TRUE(allf.isReady());
901         promises[i].setValue();
902       } else {
903         // don't blow up on further exceptions
904         EXPECT_TRUE(allf.isReady());
905         promises[i].setException(eggs);
906       }
907     }
908
909     EXPECT_THROW(allf.value(), eggs_t);
910   }
911
912   // move only compiles
913   {
914     vector<Promise<unique_ptr<int>>> promises(10);
915     vector<Future<unique_ptr<int>>> futures;
916
917     for (auto& p : promises)
918       futures.push_back(p.getFuture());
919
920     collect(futures);
921   }
922
923 }
924
925 struct NotDefaultConstructible {
926   NotDefaultConstructible() = delete;
927   NotDefaultConstructible(int arg) : i(arg) {}
928   int i;
929 };
930
931 // We have a specialized implementation for non-default-constructible objects
932 // Ensure that it works and preserves order
933 TEST(Future, collectNotDefaultConstructible) {
934   vector<Promise<NotDefaultConstructible>> promises(10);
935   vector<Future<NotDefaultConstructible>> futures;
936   vector<int> indices(10);
937   std::iota(indices.begin(), indices.end(), 0);
938   random_shuffle(indices.begin(), indices.end());
939
940   for (auto& p : promises)
941     futures.push_back(p.getFuture());
942
943   auto allf = collect(futures);
944
945   for (auto i : indices) {
946     EXPECT_FALSE(allf.isReady());
947     promises[i].setValue(NotDefaultConstructible(i));
948   }
949
950   EXPECT_TRUE(allf.isReady());
951   int i = 0;
952   for (auto val : allf.value()) {
953     EXPECT_EQ(i, val.i);
954     i++;
955   }
956 }
957
958 TEST(Future, collectAny) {
959   {
960     vector<Promise<int>> promises(10);
961     vector<Future<int>> futures;
962
963     for (auto& p : promises)
964       futures.push_back(p.getFuture());
965
966     for (auto& f : futures) {
967       EXPECT_FALSE(f.isReady());
968     }
969
970     auto anyf = collectAny(futures);
971
972     /* futures were moved in, so these are invalid now */
973     EXPECT_FALSE(anyf.isReady());
974
975     promises[7].setValue(42);
976     EXPECT_TRUE(anyf.isReady());
977     auto& idx_fut = anyf.value();
978
979     auto i = idx_fut.first;
980     EXPECT_EQ(7, i);
981
982     auto& f = idx_fut.second;
983     EXPECT_EQ(42, f.value());
984   }
985
986   // error
987   {
988     vector<Promise<void>> promises(10);
989     vector<Future<void>> futures;
990
991     for (auto& p : promises)
992       futures.push_back(p.getFuture());
993
994     for (auto& f : futures) {
995       EXPECT_FALSE(f.isReady());
996     }
997
998     auto anyf = collectAny(futures);
999
1000     EXPECT_FALSE(anyf.isReady());
1001
1002     promises[3].setException(eggs);
1003     EXPECT_TRUE(anyf.isReady());
1004     EXPECT_TRUE(anyf.value().second.hasException());
1005   }
1006
1007   // then()
1008   {
1009     vector<Promise<int>> promises(10);
1010     vector<Future<int>> futures;
1011
1012     for (auto& p : promises)
1013       futures.push_back(p.getFuture());
1014
1015     auto anyf = collectAny(futures)
1016       .then([](pair<size_t, Try<int>> p) {
1017         EXPECT_EQ(42, p.second.value());
1018       });
1019
1020     promises[3].setValue(42);
1021     EXPECT_TRUE(anyf.isReady());
1022   }
1023 }
1024
1025
1026 TEST(when, already_completed) {
1027   {
1028     vector<Future<void>> fs;
1029     for (int i = 0; i < 10; i++)
1030       fs.push_back(makeFuture());
1031
1032     collectAll(fs)
1033       .then([&](vector<Try<void>> ts) {
1034         EXPECT_EQ(fs.size(), ts.size());
1035       });
1036   }
1037   {
1038     vector<Future<int>> fs;
1039     for (int i = 0; i < 10; i++)
1040       fs.push_back(makeFuture(i));
1041
1042     collectAny(fs)
1043       .then([&](pair<size_t, Try<int>> p) {
1044         EXPECT_EQ(p.first, p.second.value());
1045       });
1046   }
1047 }
1048
1049 TEST(when, collectN) {
1050   vector<Promise<void>> promises(10);
1051   vector<Future<void>> futures;
1052
1053   for (auto& p : promises)
1054     futures.push_back(p.getFuture());
1055
1056   bool flag = false;
1057   size_t n = 3;
1058   collectN(futures, n)
1059     .then([&](vector<pair<size_t, Try<void>>> v) {
1060       flag = true;
1061       EXPECT_EQ(n, v.size());
1062       for (auto& tt : v)
1063         EXPECT_TRUE(tt.second.hasValue());
1064     });
1065
1066   promises[0].setValue();
1067   EXPECT_FALSE(flag);
1068   promises[1].setValue();
1069   EXPECT_FALSE(flag);
1070   promises[2].setValue();
1071   EXPECT_TRUE(flag);
1072 }
1073
1074 /* Ensure that we can compile when_{all,any} with folly::small_vector */
1075 TEST(when, small_vector) {
1076
1077   static_assert(!FOLLY_IS_TRIVIALLY_COPYABLE(Future<void>),
1078                 "Futures should not be trivially copyable");
1079   static_assert(!FOLLY_IS_TRIVIALLY_COPYABLE(Future<int>),
1080                 "Futures should not be trivially copyable");
1081
1082   using folly::small_vector;
1083   {
1084     small_vector<Future<void>> futures;
1085
1086     for (int i = 0; i < 10; i++)
1087       futures.push_back(makeFuture());
1088
1089     auto anyf = collectAny(futures);
1090   }
1091
1092   {
1093     small_vector<Future<void>> futures;
1094
1095     for (int i = 0; i < 10; i++)
1096       futures.push_back(makeFuture());
1097
1098     auto allf = collectAll(futures);
1099   }
1100 }
1101
1102 TEST(Future, collectAllVariadic) {
1103   Promise<bool> pb;
1104   Promise<int> pi;
1105   Future<bool> fb = pb.getFuture();
1106   Future<int> fi = pi.getFuture();
1107   bool flag = false;
1108   collectAll(std::move(fb), std::move(fi))
1109     .then([&](std::tuple<Try<bool>, Try<int>> tup) {
1110       flag = true;
1111       EXPECT_TRUE(std::get<0>(tup).hasValue());
1112       EXPECT_EQ(std::get<0>(tup).value(), true);
1113       EXPECT_TRUE(std::get<1>(tup).hasValue());
1114       EXPECT_EQ(std::get<1>(tup).value(), 42);
1115     });
1116   pb.setValue(true);
1117   EXPECT_FALSE(flag);
1118   pi.setValue(42);
1119   EXPECT_TRUE(flag);
1120 }
1121
1122 TEST(Future, collectAllVariadicReferences) {
1123   Promise<bool> pb;
1124   Promise<int> pi;
1125   Future<bool> fb = pb.getFuture();
1126   Future<int> fi = pi.getFuture();
1127   bool flag = false;
1128   collectAll(fb, fi)
1129     .then([&](std::tuple<Try<bool>, Try<int>> tup) {
1130       flag = true;
1131       EXPECT_TRUE(std::get<0>(tup).hasValue());
1132       EXPECT_EQ(std::get<0>(tup).value(), true);
1133       EXPECT_TRUE(std::get<1>(tup).hasValue());
1134       EXPECT_EQ(std::get<1>(tup).value(), 42);
1135     });
1136   pb.setValue(true);
1137   EXPECT_FALSE(flag);
1138   pi.setValue(42);
1139   EXPECT_TRUE(flag);
1140 }
1141
1142 TEST(Future, collectAll_none) {
1143   vector<Future<int>> fs;
1144   auto f = collectAll(fs);
1145   EXPECT_TRUE(f.isReady());
1146 }
1147
1148 TEST(Future, throwCaughtInImmediateThen) {
1149   // Neither of these should throw "Promise already satisfied"
1150   makeFuture().then(
1151     [=](Try<void>&&) -> int { throw std::exception(); });
1152   makeFuture().then(
1153     [=](Try<void>&&) -> Future<int> { throw std::exception(); });
1154 }
1155
1156 TEST(Future, throwIfFailed) {
1157   makeFuture<void>(eggs)
1158     .then([=](Try<void>&& t) {
1159       EXPECT_THROW(t.throwIfFailed(), eggs_t);
1160     });
1161   makeFuture()
1162     .then([=](Try<void>&& t) {
1163       EXPECT_NO_THROW(t.throwIfFailed());
1164     });
1165
1166   makeFuture<int>(eggs)
1167     .then([=](Try<int>&& t) {
1168       EXPECT_THROW(t.throwIfFailed(), eggs_t);
1169     });
1170   makeFuture<int>(42)
1171     .then([=](Try<int>&& t) {
1172       EXPECT_NO_THROW(t.throwIfFailed());
1173     });
1174 }
1175
1176 TEST(Future, waitImmediate) {
1177   makeFuture().wait();
1178   auto done = makeFuture(42).wait().value();
1179   EXPECT_EQ(42, done);
1180
1181   vector<int> v{1,2,3};
1182   auto done_v = makeFuture(v).wait().value();
1183   EXPECT_EQ(v.size(), done_v.size());
1184   EXPECT_EQ(v, done_v);
1185
1186   vector<Future<void>> v_f;
1187   v_f.push_back(makeFuture());
1188   v_f.push_back(makeFuture());
1189   auto done_v_f = collectAll(v_f).wait().value();
1190   EXPECT_EQ(2, done_v_f.size());
1191
1192   vector<Future<bool>> v_fb;
1193   v_fb.push_back(makeFuture(true));
1194   v_fb.push_back(makeFuture(false));
1195   auto fut = collectAll(v_fb);
1196   auto done_v_fb = std::move(fut.wait().value());
1197   EXPECT_EQ(2, done_v_fb.size());
1198 }
1199
1200 TEST(Future, wait) {
1201   Promise<int> p;
1202   Future<int> f = p.getFuture();
1203   std::atomic<bool> flag{false};
1204   std::atomic<int> result{1};
1205   std::atomic<std::thread::id> id;
1206
1207   std::thread t([&](Future<int>&& tf){
1208       auto n = tf.then([&](Try<int> && t) {
1209           id = std::this_thread::get_id();
1210           return t.value();
1211         });
1212       flag = true;
1213       result.store(n.wait().value());
1214     },
1215     std::move(f)
1216     );
1217   while(!flag){}
1218   EXPECT_EQ(result.load(), 1);
1219   p.setValue(42);
1220   t.join();
1221   // validate that the callback ended up executing in this thread, which
1222   // is more to ensure that this test actually tests what it should
1223   EXPECT_EQ(id, std::this_thread::get_id());
1224   EXPECT_EQ(result.load(), 42);
1225 }
1226
1227 struct MoveFlag {
1228   MoveFlag() = default;
1229   MoveFlag(const MoveFlag&) = delete;
1230   MoveFlag(MoveFlag&& other) noexcept {
1231     other.moved = true;
1232   }
1233   bool moved{false};
1234 };
1235
1236 TEST(Future, waitReplacesSelf) {
1237   // wait
1238   {
1239     // lvalue
1240     auto f1 = makeFuture(MoveFlag());
1241     f1.wait();
1242     EXPECT_FALSE(f1.value().moved);
1243
1244     // rvalue
1245     auto f2 = makeFuture(MoveFlag()).wait();
1246     EXPECT_FALSE(f2.value().moved);
1247   }
1248
1249   // wait(Duration)
1250   {
1251     // lvalue
1252     auto f1 = makeFuture(MoveFlag());
1253     f1.wait(milliseconds(1));
1254     EXPECT_FALSE(f1.value().moved);
1255
1256     // rvalue
1257     auto f2 = makeFuture(MoveFlag()).wait(milliseconds(1));
1258     EXPECT_FALSE(f2.value().moved);
1259   }
1260
1261   // waitVia
1262   {
1263     folly::EventBase eb;
1264     // lvalue
1265     auto f1 = makeFuture(MoveFlag());
1266     f1.waitVia(&eb);
1267     EXPECT_FALSE(f1.value().moved);
1268
1269     // rvalue
1270     auto f2 = makeFuture(MoveFlag()).waitVia(&eb);
1271     EXPECT_FALSE(f2.value().moved);
1272   }
1273 }
1274
1275 TEST(Future, waitWithDuration) {
1276  {
1277   Promise<int> p;
1278   Future<int> f = p.getFuture();
1279   f.wait(milliseconds(1));
1280   EXPECT_FALSE(f.isReady());
1281   p.setValue(1);
1282   EXPECT_TRUE(f.isReady());
1283  }
1284  {
1285   Promise<int> p;
1286   Future<int> f = p.getFuture();
1287   p.setValue(1);
1288   f.wait(milliseconds(1));
1289   EXPECT_TRUE(f.isReady());
1290  }
1291  {
1292   vector<Future<bool>> v_fb;
1293   v_fb.push_back(makeFuture(true));
1294   v_fb.push_back(makeFuture(false));
1295   auto f = collectAll(v_fb);
1296   f.wait(milliseconds(1));
1297   EXPECT_TRUE(f.isReady());
1298   EXPECT_EQ(2, f.value().size());
1299  }
1300  {
1301   vector<Future<bool>> v_fb;
1302   Promise<bool> p1;
1303   Promise<bool> p2;
1304   v_fb.push_back(p1.getFuture());
1305   v_fb.push_back(p2.getFuture());
1306   auto f = collectAll(v_fb);
1307   f.wait(milliseconds(1));
1308   EXPECT_FALSE(f.isReady());
1309   p1.setValue(true);
1310   EXPECT_FALSE(f.isReady());
1311   p2.setValue(true);
1312   EXPECT_TRUE(f.isReady());
1313  }
1314  {
1315   auto f = makeFuture().wait(milliseconds(1));
1316   EXPECT_TRUE(f.isReady());
1317  }
1318
1319  {
1320    Promise<void> p;
1321    auto start = std::chrono::steady_clock::now();
1322    auto f = p.getFuture().wait(milliseconds(100));
1323    auto elapsed = std::chrono::steady_clock::now() - start;
1324    EXPECT_GE(elapsed, milliseconds(100));
1325    EXPECT_FALSE(f.isReady());
1326    p.setValue();
1327    EXPECT_TRUE(f.isReady());
1328  }
1329
1330  {
1331    // Try to trigger the race where the resultant Future is not yet complete
1332    // even if we didn't hit the timeout, and make sure we deal with it properly
1333    Promise<void> p;
1334    folly::Baton<> b;
1335    auto t = std::thread([&]{
1336      b.post();
1337      /* sleep override */ std::this_thread::sleep_for(milliseconds(100));
1338      p.setValue();
1339    });
1340    b.wait();
1341    auto f = p.getFuture().wait(std::chrono::seconds(3600));
1342    EXPECT_TRUE(f.isReady());
1343    t.join();
1344  }
1345 }
1346
1347 class DummyDrivableExecutor : public DrivableExecutor {
1348  public:
1349   void add(Func f) override {}
1350   void drive() override { ran = true; }
1351   bool ran{false};
1352 };
1353
1354 TEST(Future, getVia) {
1355   {
1356     // non-void
1357     ManualExecutor x;
1358     auto f = via(&x).then([]{ return true; });
1359     EXPECT_TRUE(f.getVia(&x));
1360   }
1361
1362   {
1363     // void
1364     ManualExecutor x;
1365     auto f = via(&x).then();
1366     f.getVia(&x);
1367   }
1368
1369   {
1370     DummyDrivableExecutor x;
1371     auto f = makeFuture(true);
1372     EXPECT_TRUE(f.getVia(&x));
1373     EXPECT_FALSE(x.ran);
1374   }
1375 }
1376
1377 TEST(Future, waitVia) {
1378   {
1379     ManualExecutor x;
1380     auto f = via(&x).then();
1381     EXPECT_FALSE(f.isReady());
1382     f.waitVia(&x);
1383     EXPECT_TRUE(f.isReady());
1384   }
1385
1386   {
1387     // try rvalue as well
1388     ManualExecutor x;
1389     auto f = via(&x).then().waitVia(&x);
1390     EXPECT_TRUE(f.isReady());
1391   }
1392
1393   {
1394     DummyDrivableExecutor x;
1395     makeFuture(true).waitVia(&x);
1396     EXPECT_FALSE(x.ran);
1397   }
1398 }
1399
1400 TEST(Future, viaRaces) {
1401   ManualExecutor x;
1402   Promise<void> p;
1403   auto tid = std::this_thread::get_id();
1404   bool done = false;
1405
1406   std::thread t1([&] {
1407     p.getFuture()
1408       .via(&x)
1409       .then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
1410       .then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
1411       .then([&](Try<void>&&) { done = true; });
1412   });
1413
1414   std::thread t2([&] {
1415     p.setValue();
1416   });
1417
1418   while (!done) x.run();
1419   t1.join();
1420   t2.join();
1421 }
1422
1423 TEST(Future, getFuture_after_setValue) {
1424   Promise<int> p;
1425   p.setValue(42);
1426   EXPECT_EQ(42, p.getFuture().value());
1427 }
1428
1429 TEST(Future, getFuture_after_setException) {
1430   Promise<void> p;
1431   p.setWith([]() -> void { throw std::logic_error("foo"); });
1432   EXPECT_THROW(p.getFuture().value(), std::logic_error);
1433 }
1434
1435 TEST(Future, detachRace) {
1436   // Task #5438209
1437   // This test is designed to detect a race that was in Core::detachOne()
1438   // where detached_ was incremented and then tested, and that
1439   // allowed a race where both Promise and Future would think they were the
1440   // second and both try to delete. This showed up at scale but was very
1441   // difficult to reliably repro in a test. As it is, this only fails about
1442   // once in every 1,000 executions. Doing this 1,000 times is going to make a
1443   // slow test so I won't do that but if it ever fails, take it seriously, and
1444   // run the test binary with "--gtest_repeat=10000 --gtest_filter=*detachRace"
1445   // (Don't forget to enable ASAN)
1446   auto p = folly::make_unique<Promise<bool>>();
1447   auto f = folly::make_unique<Future<bool>>(p->getFuture());
1448   folly::Baton<> baton;
1449   std::thread t1([&]{
1450     baton.post();
1451     p.reset();
1452   });
1453   baton.wait();
1454   f.reset();
1455   t1.join();
1456 }
1457
1458 class TestData : public RequestData {
1459  public:
1460   explicit TestData(int data) : data_(data) {}
1461   virtual ~TestData() {}
1462   int data_;
1463 };
1464
1465 TEST(Future, context) {
1466
1467   // Start a new context
1468   RequestContext::create();
1469
1470   EXPECT_EQ(nullptr, RequestContext::get()->getContextData("test"));
1471
1472   // Set some test data
1473   RequestContext::get()->setContextData(
1474     "test",
1475     std::unique_ptr<TestData>(new TestData(10)));
1476
1477   // Start a future
1478   Promise<void> p;
1479   auto future = p.getFuture().then([&]{
1480     // Check that the context followed the future
1481     EXPECT_TRUE(RequestContext::get() != nullptr);
1482     auto a = dynamic_cast<TestData*>(
1483       RequestContext::get()->getContextData("test"));
1484     auto data = a->data_;
1485     EXPECT_EQ(10, data);
1486   });
1487
1488   // Clear the context
1489   RequestContext::setContext(nullptr);
1490
1491   EXPECT_EQ(nullptr, RequestContext::get()->getContextData("test"));
1492
1493   // Fulfill the promise
1494   p.setValue();
1495 }
1496
1497
1498 // This only fails about 1 in 1k times when the bug is present :(
1499 TEST(Future, t5506504) {
1500   ThreadExecutor x;
1501
1502   auto fn = [&x]{
1503     auto promises = std::make_shared<vector<Promise<void>>>(4);
1504     vector<Future<void>> futures;
1505
1506     for (auto& p : *promises) {
1507       futures.emplace_back(
1508         p.getFuture()
1509         .via(&x)
1510         .then([](Try<void>&&){}));
1511     }
1512
1513     x.waitForStartup();
1514     x.add([promises]{
1515       for (auto& p : *promises) p.setValue();
1516     });
1517
1518     return collectAll(futures);
1519   };
1520
1521   fn().wait();
1522 }
1523
1524 // Test of handling of a circular dependency. It's never recommended
1525 // to have one because of possible memory leaks. Here we test that
1526 // we can handle freeing of the Future while it is running.
1527 TEST(Future, CircularDependencySharedPtrSelfReset) {
1528   Promise<int64_t> promise;
1529   auto ptr = std::make_shared<Future<int64_t>>(promise.getFuture());
1530
1531   ptr->then(
1532     [ptr] (folly::Try<int64_t>&& uid) mutable {
1533       EXPECT_EQ(1, ptr.use_count());
1534
1535       // Leaving no references to ourselves.
1536       ptr.reset();
1537       EXPECT_EQ(0, ptr.use_count());
1538     }
1539   );
1540
1541   EXPECT_EQ(2, ptr.use_count());
1542
1543   ptr.reset();
1544
1545   promise.setWith([]{return 1l;});
1546 }
1547
1548 TEST(Future, Constructor) {
1549   auto f1 = []() -> Future<int> { return Future<int>(3); }();
1550   EXPECT_EQ(f1.value(), 3);
1551   auto f2 = []() -> Future<void> { return Future<void>(); }();
1552   EXPECT_NO_THROW(f2.value());
1553 }
1554
1555 TEST(Future, ImplicitConstructor) {
1556   auto f1 = []() -> Future<int> { return 3; }();
1557   EXPECT_EQ(f1.value(), 3);
1558   // Unfortunately, the C++ standard does not allow the
1559   // following implicit conversion to work:
1560   //auto f2 = []() -> Future<void> { }();
1561 }
1562
1563 TEST(Future, thenDynamic) {
1564   // folly::dynamic has a constructor that takes any T, this test makes
1565   // sure that we call the then lambda with folly::dynamic and not
1566   // Try<folly::dynamic> because that then fails to compile
1567   Promise<folly::dynamic> p;
1568   Future<folly::dynamic> f = p.getFuture().then(
1569       [](const folly::dynamic& d) {
1570         return folly::dynamic(d.asInt() + 3);
1571       }
1572   );
1573   p.setValue(2);
1574   EXPECT_EQ(f.get(), 5);
1575 }
1576
1577 TEST(Future, via_then_get_was_racy) {
1578   ThreadExecutor x;
1579   std::unique_ptr<int> val = folly::via(&x)
1580     .then([] { return folly::make_unique<int>(42); })
1581     .get();
1582   ASSERT_TRUE(!!val);
1583   EXPECT_EQ(42, *val);
1584 }
1585
1586 TEST(Future, ensure) {
1587   size_t count = 0;
1588   auto cob = [&]{ count++; };
1589   auto f = makeFuture(42)
1590     .ensure(cob)
1591     .then([](int) { throw std::runtime_error("ensure"); })
1592     .ensure(cob);
1593
1594   EXPECT_THROW(f.get(), std::runtime_error);
1595   EXPECT_EQ(2, count);
1596 }
1597
1598 TEST(Future, willEqual) {
1599     //both p1 and p2 already fulfilled
1600     {
1601     Promise<int> p1;
1602     Promise<int> p2;
1603     p1.setValue(27);
1604     p2.setValue(27);
1605     auto f1 = p1.getFuture();
1606     auto f2 = p2.getFuture();
1607     EXPECT_TRUE(f1.willEqual(f2).get());
1608     }{
1609     Promise<int> p1;
1610     Promise<int> p2;
1611     p1.setValue(27);
1612     p2.setValue(36);
1613     auto f1 = p1.getFuture();
1614     auto f2 = p2.getFuture();
1615     EXPECT_FALSE(f1.willEqual(f2).get());
1616     }
1617     //both p1 and p2 not yet fulfilled
1618     {
1619     Promise<int> p1;
1620     Promise<int> p2;
1621     auto f1 = p1.getFuture();
1622     auto f2 = p2.getFuture();
1623     auto f3 = f1.willEqual(f2);
1624     p1.setValue(27);
1625     p2.setValue(27);
1626     EXPECT_TRUE(f3.get());
1627     }{
1628     Promise<int> p1;
1629     Promise<int> p2;
1630     auto f1 = p1.getFuture();
1631     auto f2 = p2.getFuture();
1632     auto f3 = f1.willEqual(f2);
1633     p1.setValue(27);
1634     p2.setValue(36);
1635     EXPECT_FALSE(f3.get());
1636     }
1637     //p1 already fulfilled, p2 not yet fulfilled
1638     {
1639     Promise<int> p1;
1640     Promise<int> p2;
1641     p1.setValue(27);
1642     auto f1 = p1.getFuture();
1643     auto f2 = p2.getFuture();
1644     auto f3 = f1.willEqual(f2);
1645     p2.setValue(27);
1646     EXPECT_TRUE(f3.get());
1647     }{
1648     Promise<int> p1;
1649     Promise<int> p2;
1650     p1.setValue(27);
1651     auto f1 = p1.getFuture();
1652     auto f2 = p2.getFuture();
1653     auto f3 = f1.willEqual(f2);
1654     p2.setValue(36);
1655     EXPECT_FALSE(f3.get());
1656     }
1657     //p2 already fulfilled, p1 not yet fulfilled
1658     {
1659     Promise<int> p1;
1660     Promise<int> p2;
1661     p2.setValue(27);
1662     auto f1 = p1.getFuture();
1663     auto f2 = p2.getFuture();
1664     auto f3 = f1.willEqual(f2);
1665     p1.setValue(27);
1666     EXPECT_TRUE(f3.get());
1667     }{
1668     Promise<int> p1;
1669     Promise<int> p2;
1670     p2.setValue(36);
1671     auto f1 = p1.getFuture();
1672     auto f2 = p2.getFuture();
1673     auto f3 = f1.willEqual(f2);
1674     p1.setValue(27);
1675     EXPECT_FALSE(f3.get());
1676     }
1677 }
1678
1679 // Unwrap tests.
1680
1681 // A simple scenario for the unwrap call, when the promise was fulfilled
1682 // before calling to unwrap.
1683 TEST(Future, Unwrap_SimpleScenario) {
1684   Future<int> encapsulated_future = makeFuture(5484);
1685   Future<Future<int>> future = makeFuture(std::move(encapsulated_future));
1686   EXPECT_EQ(5484, future.unwrap().value());
1687 }
1688
1689 // Makes sure that unwrap() works when chaning Future's commands.
1690 TEST(Future, Unwrap_ChainCommands) {
1691   Future<Future<int>> future = makeFuture(makeFuture(5484));
1692   auto unwrapped = future.unwrap().then([](int i){ return i; });
1693   EXPECT_EQ(5484, unwrapped.value());
1694 }
1695
1696 // Makes sure that the unwrap call also works when the promise was not yet
1697 // fulfilled, and that the returned Future<T> becomes ready once the promise
1698 // is fulfilled.
1699 TEST(Future, Unwrap_FutureNotReady) {
1700   Promise<Future<int>> p;
1701   Future<Future<int>> future = p.getFuture();
1702   Future<int> unwrapped = future.unwrap();
1703   // Sanity - should not be ready before the promise is fulfilled.
1704   ASSERT_FALSE(unwrapped.isReady());
1705   // Fulfill the promise and make sure the unwrapped future is now ready.
1706   p.setValue(makeFuture(5484));
1707   ASSERT_TRUE(unwrapped.isReady());
1708   EXPECT_EQ(5484, unwrapped.value());
1709 }
1710
1711 TEST(Reduce, Basic) {
1712   auto makeFutures = [](int count) {
1713     std::vector<Future<int>> fs;
1714     for (int i = 1; i <= count; ++i) {
1715       fs.emplace_back(makeFuture(i));
1716     }
1717     return fs;
1718   };
1719
1720   // Empty (Try)
1721   {
1722     auto fs = makeFutures(0);
1723
1724     Future<double> f1 = reduce(fs, 1.2,
1725       [](double a, Try<int>&& b){
1726         return a + *b + 0.1;
1727       });
1728     EXPECT_EQ(1.2, f1.get());
1729   }
1730
1731   // One (Try)
1732   {
1733     auto fs = makeFutures(1);
1734
1735     Future<double> f1 = reduce(fs, 0.0,
1736       [](double a, Try<int>&& b){
1737         return a + *b + 0.1;
1738       });
1739     EXPECT_EQ(1.1, f1.get());
1740   }
1741
1742   // Returning values (Try)
1743   {
1744     auto fs = makeFutures(3);
1745
1746     Future<double> f1 = reduce(fs, 0.0,
1747       [](double a, Try<int>&& b){
1748         return a + *b + 0.1;
1749       });
1750     EXPECT_EQ(6.3, f1.get());
1751   }
1752
1753   // Returning values
1754   {
1755     auto fs = makeFutures(3);
1756
1757     Future<double> f1 = reduce(fs, 0.0,
1758       [](double a, int&& b){
1759         return a + b + 0.1;
1760       });
1761     EXPECT_EQ(6.3, f1.get());
1762   }
1763
1764   // Returning futures (Try)
1765   {
1766     auto fs = makeFutures(3);
1767
1768     Future<double> f2 = reduce(fs, 0.0,
1769       [](double a, Try<int>&& b){
1770         return makeFuture<double>(a + *b + 0.1);
1771       });
1772     EXPECT_EQ(6.3, f2.get());
1773   }
1774
1775   // Returning futures
1776   {
1777     auto fs = makeFutures(3);
1778
1779     Future<double> f2 = reduce(fs, 0.0,
1780       [](double a, int&& b){
1781         return makeFuture<double>(a + b + 0.1);
1782       });
1783     EXPECT_EQ(6.3, f2.get());
1784   }
1785 }
1786
1787 TEST(Reduce, Chain) {
1788   auto makeFutures = [](int count) {
1789     std::vector<Future<int>> fs;
1790     for (int i = 1; i <= count; ++i) {
1791       fs.emplace_back(makeFuture(i));
1792     }
1793     return fs;
1794   };
1795
1796   {
1797     auto f = collectAll(makeFutures(3)).reduce(0, [](int a, Try<int>&& b){
1798       return a + *b;
1799     });
1800     EXPECT_EQ(6, f.get());
1801   }
1802   {
1803     auto f = collect(makeFutures(3)).reduce(0, [](int a, int&& b){
1804       return a + b;
1805     });
1806     EXPECT_EQ(6, f.get());
1807   }
1808 }
1809
1810 TEST(Map, Basic) {
1811   Promise<int> p1;
1812   Promise<int> p2;
1813   Promise<int> p3;
1814
1815   std::vector<Future<int>> fs;
1816   fs.push_back(p1.getFuture());
1817   fs.push_back(p2.getFuture());
1818   fs.push_back(p3.getFuture());
1819
1820   int c = 0;
1821   std::vector<Future<void>> fs2 = futures::map(fs, [&](int i){
1822     c += i;
1823   });
1824
1825   // Ensure we call the callbacks as the futures complete regardless of order
1826   p2.setValue(1);
1827   EXPECT_EQ(1, c);
1828   p3.setValue(1);
1829   EXPECT_EQ(2, c);
1830   p1.setValue(1);
1831   EXPECT_EQ(3, c);
1832
1833   EXPECT_TRUE(collect(fs2).isReady());
1834 }