(Wangle) Fix typo
[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, window) {
694   // int -> Future<int>
695   auto fn = [](vector<int> input, size_t window_size, size_t expect) {
696     auto res = reduce(
697       window(
698         input,
699         [](int i) { return makeFuture(i); },
700         2),
701       0,
702       [](int sum, const Try<int>& b) {
703         return sum + *b;
704       }).get();
705     EXPECT_EQ(expect, res);
706   };
707   {
708     // 2 in-flight at a time
709     vector<int> input = {1, 2, 3};
710     fn(input, 2, 6);
711   }
712   {
713     // 4 in-flight at a time
714     vector<int> input = {1, 2, 3};
715     fn(input, 4, 6);
716   }
717   {
718     // empty inpt
719     vector<int> input;
720     fn(input, 1, 0);
721   }
722   {
723     // int -> Future<void>
724     auto res = reduce(
725       window(
726         std::vector<int>({1, 2, 3}),
727         [](int i) { return makeFuture(); },
728         2),
729       0,
730       [](int sum, const Try<void>& b) {
731         EXPECT_TRUE(b.hasValue());
732         return sum + 1;
733       }).get();
734     EXPECT_EQ(3, res);
735   }
736   {
737     // string -> return Future<int>
738     auto res = reduce(
739       window(
740         std::vector<std::string>{"1", "2", "3"},
741         [](std::string s) { return makeFuture<int>(folly::to<int>(s)); },
742         2),
743       0,
744       [](int sum, const Try<int>& b) {
745         return sum + *b;
746       }).get();
747     EXPECT_EQ(6, res);
748   }
749 }
750
751 TEST(Future, collectAll) {
752   // returns a vector variant
753   {
754     vector<Promise<int>> promises(10);
755     vector<Future<int>> futures;
756
757     for (auto& p : promises)
758       futures.push_back(p.getFuture());
759
760     auto allf = collectAll(futures);
761
762     random_shuffle(promises.begin(), promises.end());
763     for (auto& p : promises) {
764       EXPECT_FALSE(allf.isReady());
765       p.setValue(42);
766     }
767
768     EXPECT_TRUE(allf.isReady());
769     auto& results = allf.value();
770     for (auto& t : results) {
771       EXPECT_EQ(42, t.value());
772     }
773   }
774
775   // check error semantics
776   {
777     vector<Promise<int>> promises(4);
778     vector<Future<int>> futures;
779
780     for (auto& p : promises)
781       futures.push_back(p.getFuture());
782
783     auto allf = collectAll(futures);
784
785
786     promises[0].setValue(42);
787     promises[1].setException(eggs);
788
789     EXPECT_FALSE(allf.isReady());
790
791     promises[2].setValue(42);
792
793     EXPECT_FALSE(allf.isReady());
794
795     promises[3].setException(eggs);
796
797     EXPECT_TRUE(allf.isReady());
798     EXPECT_FALSE(allf.getTry().hasException());
799
800     auto& results = allf.value();
801     EXPECT_EQ(42, results[0].value());
802     EXPECT_TRUE(results[1].hasException());
803     EXPECT_EQ(42, results[2].value());
804     EXPECT_TRUE(results[3].hasException());
805   }
806
807   // check that futures are ready in then()
808   {
809     vector<Promise<void>> promises(10);
810     vector<Future<void>> futures;
811
812     for (auto& p : promises)
813       futures.push_back(p.getFuture());
814
815     auto allf = collectAll(futures)
816       .then([](Try<vector<Try<void>>>&& ts) {
817         for (auto& f : ts.value())
818           f.value();
819       });
820
821     random_shuffle(promises.begin(), promises.end());
822     for (auto& p : promises)
823       p.setValue();
824     EXPECT_TRUE(allf.isReady());
825   }
826 }
827
828 TEST(Future, collect) {
829   // success case
830   {
831     vector<Promise<int>> promises(10);
832     vector<Future<int>> futures;
833
834     for (auto& p : promises)
835       futures.push_back(p.getFuture());
836
837     auto allf = collect(futures);
838
839     random_shuffle(promises.begin(), promises.end());
840     for (auto& p : promises) {
841       EXPECT_FALSE(allf.isReady());
842       p.setValue(42);
843     }
844
845     EXPECT_TRUE(allf.isReady());
846     for (auto i : allf.value()) {
847       EXPECT_EQ(42, i);
848     }
849   }
850
851   // failure case
852   {
853     vector<Promise<int>> promises(10);
854     vector<Future<int>> futures;
855
856     for (auto& p : promises)
857       futures.push_back(p.getFuture());
858
859     auto allf = collect(futures);
860
861     random_shuffle(promises.begin(), promises.end());
862     for (int i = 0; i < 10; i++) {
863       if (i < 5) {
864         // everthing goes well so far...
865         EXPECT_FALSE(allf.isReady());
866         promises[i].setValue(42);
867       } else if (i == 5) {
868         // short circuit with an exception
869         EXPECT_FALSE(allf.isReady());
870         promises[i].setException(eggs);
871         EXPECT_TRUE(allf.isReady());
872       } else if (i < 8) {
873         // don't blow up on further values
874         EXPECT_TRUE(allf.isReady());
875         promises[i].setValue(42);
876       } else {
877         // don't blow up on further exceptions
878         EXPECT_TRUE(allf.isReady());
879         promises[i].setException(eggs);
880       }
881     }
882
883     EXPECT_THROW(allf.value(), eggs_t);
884   }
885
886   // void futures success case
887   {
888     vector<Promise<void>> promises(10);
889     vector<Future<void>> futures;
890
891     for (auto& p : promises)
892       futures.push_back(p.getFuture());
893
894     auto allf = collect(futures);
895
896     random_shuffle(promises.begin(), promises.end());
897     for (auto& p : promises) {
898       EXPECT_FALSE(allf.isReady());
899       p.setValue();
900     }
901
902     EXPECT_TRUE(allf.isReady());
903   }
904
905   // void futures failure case
906   {
907     vector<Promise<void>> promises(10);
908     vector<Future<void>> futures;
909
910     for (auto& p : promises)
911       futures.push_back(p.getFuture());
912
913     auto allf = collect(futures);
914
915     random_shuffle(promises.begin(), promises.end());
916     for (int i = 0; i < 10; i++) {
917       if (i < 5) {
918         // everthing goes well so far...
919         EXPECT_FALSE(allf.isReady());
920         promises[i].setValue();
921       } else if (i == 5) {
922         // short circuit with an exception
923         EXPECT_FALSE(allf.isReady());
924         promises[i].setException(eggs);
925         EXPECT_TRUE(allf.isReady());
926       } else if (i < 8) {
927         // don't blow up on further values
928         EXPECT_TRUE(allf.isReady());
929         promises[i].setValue();
930       } else {
931         // don't blow up on further exceptions
932         EXPECT_TRUE(allf.isReady());
933         promises[i].setException(eggs);
934       }
935     }
936
937     EXPECT_THROW(allf.value(), eggs_t);
938   }
939
940   // move only compiles
941   {
942     vector<Promise<unique_ptr<int>>> promises(10);
943     vector<Future<unique_ptr<int>>> futures;
944
945     for (auto& p : promises)
946       futures.push_back(p.getFuture());
947
948     collect(futures);
949   }
950
951 }
952
953 struct NotDefaultConstructible {
954   NotDefaultConstructible() = delete;
955   NotDefaultConstructible(int arg) : i(arg) {}
956   int i;
957 };
958
959 // We have a specialized implementation for non-default-constructible objects
960 // Ensure that it works and preserves order
961 TEST(Future, collectNotDefaultConstructible) {
962   vector<Promise<NotDefaultConstructible>> promises(10);
963   vector<Future<NotDefaultConstructible>> futures;
964   vector<int> indices(10);
965   std::iota(indices.begin(), indices.end(), 0);
966   random_shuffle(indices.begin(), indices.end());
967
968   for (auto& p : promises)
969     futures.push_back(p.getFuture());
970
971   auto allf = collect(futures);
972
973   for (auto i : indices) {
974     EXPECT_FALSE(allf.isReady());
975     promises[i].setValue(NotDefaultConstructible(i));
976   }
977
978   EXPECT_TRUE(allf.isReady());
979   int i = 0;
980   for (auto val : allf.value()) {
981     EXPECT_EQ(i, val.i);
982     i++;
983   }
984 }
985
986 TEST(Future, collectAny) {
987   {
988     vector<Promise<int>> promises(10);
989     vector<Future<int>> 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     /* futures were moved in, so these are invalid now */
1001     EXPECT_FALSE(anyf.isReady());
1002
1003     promises[7].setValue(42);
1004     EXPECT_TRUE(anyf.isReady());
1005     auto& idx_fut = anyf.value();
1006
1007     auto i = idx_fut.first;
1008     EXPECT_EQ(7, i);
1009
1010     auto& f = idx_fut.second;
1011     EXPECT_EQ(42, f.value());
1012   }
1013
1014   // error
1015   {
1016     vector<Promise<void>> promises(10);
1017     vector<Future<void>> futures;
1018
1019     for (auto& p : promises)
1020       futures.push_back(p.getFuture());
1021
1022     for (auto& f : futures) {
1023       EXPECT_FALSE(f.isReady());
1024     }
1025
1026     auto anyf = collectAny(futures);
1027
1028     EXPECT_FALSE(anyf.isReady());
1029
1030     promises[3].setException(eggs);
1031     EXPECT_TRUE(anyf.isReady());
1032     EXPECT_TRUE(anyf.value().second.hasException());
1033   }
1034
1035   // then()
1036   {
1037     vector<Promise<int>> promises(10);
1038     vector<Future<int>> futures;
1039
1040     for (auto& p : promises)
1041       futures.push_back(p.getFuture());
1042
1043     auto anyf = collectAny(futures)
1044       .then([](pair<size_t, Try<int>> p) {
1045         EXPECT_EQ(42, p.second.value());
1046       });
1047
1048     promises[3].setValue(42);
1049     EXPECT_TRUE(anyf.isReady());
1050   }
1051 }
1052
1053
1054 TEST(when, already_completed) {
1055   {
1056     vector<Future<void>> fs;
1057     for (int i = 0; i < 10; i++)
1058       fs.push_back(makeFuture());
1059
1060     collectAll(fs)
1061       .then([&](vector<Try<void>> ts) {
1062         EXPECT_EQ(fs.size(), ts.size());
1063       });
1064   }
1065   {
1066     vector<Future<int>> fs;
1067     for (int i = 0; i < 10; i++)
1068       fs.push_back(makeFuture(i));
1069
1070     collectAny(fs)
1071       .then([&](pair<size_t, Try<int>> p) {
1072         EXPECT_EQ(p.first, p.second.value());
1073       });
1074   }
1075 }
1076
1077 TEST(when, collectN) {
1078   vector<Promise<void>> promises(10);
1079   vector<Future<void>> futures;
1080
1081   for (auto& p : promises)
1082     futures.push_back(p.getFuture());
1083
1084   bool flag = false;
1085   size_t n = 3;
1086   collectN(futures, n)
1087     .then([&](vector<pair<size_t, Try<void>>> v) {
1088       flag = true;
1089       EXPECT_EQ(n, v.size());
1090       for (auto& tt : v)
1091         EXPECT_TRUE(tt.second.hasValue());
1092     });
1093
1094   promises[0].setValue();
1095   EXPECT_FALSE(flag);
1096   promises[1].setValue();
1097   EXPECT_FALSE(flag);
1098   promises[2].setValue();
1099   EXPECT_TRUE(flag);
1100 }
1101
1102 /* Ensure that we can compile when_{all,any} with folly::small_vector */
1103 TEST(when, small_vector) {
1104
1105   static_assert(!FOLLY_IS_TRIVIALLY_COPYABLE(Future<void>),
1106                 "Futures should not be trivially copyable");
1107   static_assert(!FOLLY_IS_TRIVIALLY_COPYABLE(Future<int>),
1108                 "Futures should not be trivially copyable");
1109
1110   using folly::small_vector;
1111   {
1112     small_vector<Future<void>> futures;
1113
1114     for (int i = 0; i < 10; i++)
1115       futures.push_back(makeFuture());
1116
1117     auto anyf = collectAny(futures);
1118   }
1119
1120   {
1121     small_vector<Future<void>> futures;
1122
1123     for (int i = 0; i < 10; i++)
1124       futures.push_back(makeFuture());
1125
1126     auto allf = collectAll(futures);
1127   }
1128 }
1129
1130 TEST(Future, collectAllVariadic) {
1131   Promise<bool> pb;
1132   Promise<int> pi;
1133   Future<bool> fb = pb.getFuture();
1134   Future<int> fi = pi.getFuture();
1135   bool flag = false;
1136   collectAll(std::move(fb), std::move(fi))
1137     .then([&](std::tuple<Try<bool>, Try<int>> tup) {
1138       flag = true;
1139       EXPECT_TRUE(std::get<0>(tup).hasValue());
1140       EXPECT_EQ(std::get<0>(tup).value(), true);
1141       EXPECT_TRUE(std::get<1>(tup).hasValue());
1142       EXPECT_EQ(std::get<1>(tup).value(), 42);
1143     });
1144   pb.setValue(true);
1145   EXPECT_FALSE(flag);
1146   pi.setValue(42);
1147   EXPECT_TRUE(flag);
1148 }
1149
1150 TEST(Future, collectAllVariadicReferences) {
1151   Promise<bool> pb;
1152   Promise<int> pi;
1153   Future<bool> fb = pb.getFuture();
1154   Future<int> fi = pi.getFuture();
1155   bool flag = false;
1156   collectAll(fb, fi)
1157     .then([&](std::tuple<Try<bool>, Try<int>> tup) {
1158       flag = true;
1159       EXPECT_TRUE(std::get<0>(tup).hasValue());
1160       EXPECT_EQ(std::get<0>(tup).value(), true);
1161       EXPECT_TRUE(std::get<1>(tup).hasValue());
1162       EXPECT_EQ(std::get<1>(tup).value(), 42);
1163     });
1164   pb.setValue(true);
1165   EXPECT_FALSE(flag);
1166   pi.setValue(42);
1167   EXPECT_TRUE(flag);
1168 }
1169
1170 TEST(Future, collectAll_none) {
1171   vector<Future<int>> fs;
1172   auto f = collectAll(fs);
1173   EXPECT_TRUE(f.isReady());
1174 }
1175
1176 TEST(Future, throwCaughtInImmediateThen) {
1177   // Neither of these should throw "Promise already satisfied"
1178   makeFuture().then(
1179     [=](Try<void>&&) -> int { throw std::exception(); });
1180   makeFuture().then(
1181     [=](Try<void>&&) -> Future<int> { throw std::exception(); });
1182 }
1183
1184 TEST(Future, throwIfFailed) {
1185   makeFuture<void>(eggs)
1186     .then([=](Try<void>&& t) {
1187       EXPECT_THROW(t.throwIfFailed(), eggs_t);
1188     });
1189   makeFuture()
1190     .then([=](Try<void>&& t) {
1191       EXPECT_NO_THROW(t.throwIfFailed());
1192     });
1193
1194   makeFuture<int>(eggs)
1195     .then([=](Try<int>&& t) {
1196       EXPECT_THROW(t.throwIfFailed(), eggs_t);
1197     });
1198   makeFuture<int>(42)
1199     .then([=](Try<int>&& t) {
1200       EXPECT_NO_THROW(t.throwIfFailed());
1201     });
1202 }
1203
1204 TEST(Future, waitImmediate) {
1205   makeFuture().wait();
1206   auto done = makeFuture(42).wait().value();
1207   EXPECT_EQ(42, done);
1208
1209   vector<int> v{1,2,3};
1210   auto done_v = makeFuture(v).wait().value();
1211   EXPECT_EQ(v.size(), done_v.size());
1212   EXPECT_EQ(v, done_v);
1213
1214   vector<Future<void>> v_f;
1215   v_f.push_back(makeFuture());
1216   v_f.push_back(makeFuture());
1217   auto done_v_f = collectAll(v_f).wait().value();
1218   EXPECT_EQ(2, done_v_f.size());
1219
1220   vector<Future<bool>> v_fb;
1221   v_fb.push_back(makeFuture(true));
1222   v_fb.push_back(makeFuture(false));
1223   auto fut = collectAll(v_fb);
1224   auto done_v_fb = std::move(fut.wait().value());
1225   EXPECT_EQ(2, done_v_fb.size());
1226 }
1227
1228 TEST(Future, wait) {
1229   Promise<int> p;
1230   Future<int> f = p.getFuture();
1231   std::atomic<bool> flag{false};
1232   std::atomic<int> result{1};
1233   std::atomic<std::thread::id> id;
1234
1235   std::thread t([&](Future<int>&& tf){
1236       auto n = tf.then([&](Try<int> && t) {
1237           id = std::this_thread::get_id();
1238           return t.value();
1239         });
1240       flag = true;
1241       result.store(n.wait().value());
1242     },
1243     std::move(f)
1244     );
1245   while(!flag){}
1246   EXPECT_EQ(result.load(), 1);
1247   p.setValue(42);
1248   t.join();
1249   // validate that the callback ended up executing in this thread, which
1250   // is more to ensure that this test actually tests what it should
1251   EXPECT_EQ(id, std::this_thread::get_id());
1252   EXPECT_EQ(result.load(), 42);
1253 }
1254
1255 struct MoveFlag {
1256   MoveFlag() = default;
1257   MoveFlag(const MoveFlag&) = delete;
1258   MoveFlag(MoveFlag&& other) noexcept {
1259     other.moved = true;
1260   }
1261   bool moved{false};
1262 };
1263
1264 TEST(Future, waitReplacesSelf) {
1265   // wait
1266   {
1267     // lvalue
1268     auto f1 = makeFuture(MoveFlag());
1269     f1.wait();
1270     EXPECT_FALSE(f1.value().moved);
1271
1272     // rvalue
1273     auto f2 = makeFuture(MoveFlag()).wait();
1274     EXPECT_FALSE(f2.value().moved);
1275   }
1276
1277   // wait(Duration)
1278   {
1279     // lvalue
1280     auto f1 = makeFuture(MoveFlag());
1281     f1.wait(milliseconds(1));
1282     EXPECT_FALSE(f1.value().moved);
1283
1284     // rvalue
1285     auto f2 = makeFuture(MoveFlag()).wait(milliseconds(1));
1286     EXPECT_FALSE(f2.value().moved);
1287   }
1288
1289   // waitVia
1290   {
1291     folly::EventBase eb;
1292     // lvalue
1293     auto f1 = makeFuture(MoveFlag());
1294     f1.waitVia(&eb);
1295     EXPECT_FALSE(f1.value().moved);
1296
1297     // rvalue
1298     auto f2 = makeFuture(MoveFlag()).waitVia(&eb);
1299     EXPECT_FALSE(f2.value().moved);
1300   }
1301 }
1302
1303 TEST(Future, waitWithDuration) {
1304  {
1305   Promise<int> p;
1306   Future<int> f = p.getFuture();
1307   f.wait(milliseconds(1));
1308   EXPECT_FALSE(f.isReady());
1309   p.setValue(1);
1310   EXPECT_TRUE(f.isReady());
1311  }
1312  {
1313   Promise<int> p;
1314   Future<int> f = p.getFuture();
1315   p.setValue(1);
1316   f.wait(milliseconds(1));
1317   EXPECT_TRUE(f.isReady());
1318  }
1319  {
1320   vector<Future<bool>> v_fb;
1321   v_fb.push_back(makeFuture(true));
1322   v_fb.push_back(makeFuture(false));
1323   auto f = collectAll(v_fb);
1324   f.wait(milliseconds(1));
1325   EXPECT_TRUE(f.isReady());
1326   EXPECT_EQ(2, f.value().size());
1327  }
1328  {
1329   vector<Future<bool>> v_fb;
1330   Promise<bool> p1;
1331   Promise<bool> p2;
1332   v_fb.push_back(p1.getFuture());
1333   v_fb.push_back(p2.getFuture());
1334   auto f = collectAll(v_fb);
1335   f.wait(milliseconds(1));
1336   EXPECT_FALSE(f.isReady());
1337   p1.setValue(true);
1338   EXPECT_FALSE(f.isReady());
1339   p2.setValue(true);
1340   EXPECT_TRUE(f.isReady());
1341  }
1342  {
1343   auto f = makeFuture().wait(milliseconds(1));
1344   EXPECT_TRUE(f.isReady());
1345  }
1346
1347  {
1348    Promise<void> p;
1349    auto start = std::chrono::steady_clock::now();
1350    auto f = p.getFuture().wait(milliseconds(100));
1351    auto elapsed = std::chrono::steady_clock::now() - start;
1352    EXPECT_GE(elapsed, milliseconds(100));
1353    EXPECT_FALSE(f.isReady());
1354    p.setValue();
1355    EXPECT_TRUE(f.isReady());
1356  }
1357
1358  {
1359    // Try to trigger the race where the resultant Future is not yet complete
1360    // even if we didn't hit the timeout, and make sure we deal with it properly
1361    Promise<void> p;
1362    folly::Baton<> b;
1363    auto t = std::thread([&]{
1364      b.post();
1365      /* sleep override */ std::this_thread::sleep_for(milliseconds(100));
1366      p.setValue();
1367    });
1368    b.wait();
1369    auto f = p.getFuture().wait(std::chrono::seconds(3600));
1370    EXPECT_TRUE(f.isReady());
1371    t.join();
1372  }
1373 }
1374
1375 class DummyDrivableExecutor : public DrivableExecutor {
1376  public:
1377   void add(Func f) override {}
1378   void drive() override { ran = true; }
1379   bool ran{false};
1380 };
1381
1382 TEST(Future, getVia) {
1383   {
1384     // non-void
1385     ManualExecutor x;
1386     auto f = via(&x).then([]{ return true; });
1387     EXPECT_TRUE(f.getVia(&x));
1388   }
1389
1390   {
1391     // void
1392     ManualExecutor x;
1393     auto f = via(&x).then();
1394     f.getVia(&x);
1395   }
1396
1397   {
1398     DummyDrivableExecutor x;
1399     auto f = makeFuture(true);
1400     EXPECT_TRUE(f.getVia(&x));
1401     EXPECT_FALSE(x.ran);
1402   }
1403 }
1404
1405 TEST(Future, waitVia) {
1406   {
1407     ManualExecutor x;
1408     auto f = via(&x).then();
1409     EXPECT_FALSE(f.isReady());
1410     f.waitVia(&x);
1411     EXPECT_TRUE(f.isReady());
1412   }
1413
1414   {
1415     // try rvalue as well
1416     ManualExecutor x;
1417     auto f = via(&x).then().waitVia(&x);
1418     EXPECT_TRUE(f.isReady());
1419   }
1420
1421   {
1422     DummyDrivableExecutor x;
1423     makeFuture(true).waitVia(&x);
1424     EXPECT_FALSE(x.ran);
1425   }
1426 }
1427
1428 TEST(Future, viaRaces) {
1429   ManualExecutor x;
1430   Promise<void> p;
1431   auto tid = std::this_thread::get_id();
1432   bool done = false;
1433
1434   std::thread t1([&] {
1435     p.getFuture()
1436       .via(&x)
1437       .then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
1438       .then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
1439       .then([&](Try<void>&&) { done = true; });
1440   });
1441
1442   std::thread t2([&] {
1443     p.setValue();
1444   });
1445
1446   while (!done) x.run();
1447   t1.join();
1448   t2.join();
1449 }
1450
1451 TEST(Future, getFuture_after_setValue) {
1452   Promise<int> p;
1453   p.setValue(42);
1454   EXPECT_EQ(42, p.getFuture().value());
1455 }
1456
1457 TEST(Future, getFuture_after_setException) {
1458   Promise<void> p;
1459   p.setWith([]() -> void { throw std::logic_error("foo"); });
1460   EXPECT_THROW(p.getFuture().value(), std::logic_error);
1461 }
1462
1463 TEST(Future, detachRace) {
1464   // Task #5438209
1465   // This test is designed to detect a race that was in Core::detachOne()
1466   // where detached_ was incremented and then tested, and that
1467   // allowed a race where both Promise and Future would think they were the
1468   // second and both try to delete. This showed up at scale but was very
1469   // difficult to reliably repro in a test. As it is, this only fails about
1470   // once in every 1,000 executions. Doing this 1,000 times is going to make a
1471   // slow test so I won't do that but if it ever fails, take it seriously, and
1472   // run the test binary with "--gtest_repeat=10000 --gtest_filter=*detachRace"
1473   // (Don't forget to enable ASAN)
1474   auto p = folly::make_unique<Promise<bool>>();
1475   auto f = folly::make_unique<Future<bool>>(p->getFuture());
1476   folly::Baton<> baton;
1477   std::thread t1([&]{
1478     baton.post();
1479     p.reset();
1480   });
1481   baton.wait();
1482   f.reset();
1483   t1.join();
1484 }
1485
1486 class TestData : public RequestData {
1487  public:
1488   explicit TestData(int data) : data_(data) {}
1489   virtual ~TestData() {}
1490   int data_;
1491 };
1492
1493 TEST(Future, context) {
1494
1495   // Start a new context
1496   RequestContext::create();
1497
1498   EXPECT_EQ(nullptr, RequestContext::get()->getContextData("test"));
1499
1500   // Set some test data
1501   RequestContext::get()->setContextData(
1502     "test",
1503     std::unique_ptr<TestData>(new TestData(10)));
1504
1505   // Start a future
1506   Promise<void> p;
1507   auto future = p.getFuture().then([&]{
1508     // Check that the context followed the future
1509     EXPECT_TRUE(RequestContext::get() != nullptr);
1510     auto a = dynamic_cast<TestData*>(
1511       RequestContext::get()->getContextData("test"));
1512     auto data = a->data_;
1513     EXPECT_EQ(10, data);
1514   });
1515
1516   // Clear the context
1517   RequestContext::setContext(nullptr);
1518
1519   EXPECT_EQ(nullptr, RequestContext::get()->getContextData("test"));
1520
1521   // Fulfill the promise
1522   p.setValue();
1523 }
1524
1525
1526 // This only fails about 1 in 1k times when the bug is present :(
1527 TEST(Future, t5506504) {
1528   ThreadExecutor x;
1529
1530   auto fn = [&x]{
1531     auto promises = std::make_shared<vector<Promise<void>>>(4);
1532     vector<Future<void>> futures;
1533
1534     for (auto& p : *promises) {
1535       futures.emplace_back(
1536         p.getFuture()
1537         .via(&x)
1538         .then([](Try<void>&&){}));
1539     }
1540
1541     x.waitForStartup();
1542     x.add([promises]{
1543       for (auto& p : *promises) p.setValue();
1544     });
1545
1546     return collectAll(futures);
1547   };
1548
1549   fn().wait();
1550 }
1551
1552 // Test of handling of a circular dependency. It's never recommended
1553 // to have one because of possible memory leaks. Here we test that
1554 // we can handle freeing of the Future while it is running.
1555 TEST(Future, CircularDependencySharedPtrSelfReset) {
1556   Promise<int64_t> promise;
1557   auto ptr = std::make_shared<Future<int64_t>>(promise.getFuture());
1558
1559   ptr->then(
1560     [ptr] (folly::Try<int64_t>&& uid) mutable {
1561       EXPECT_EQ(1, ptr.use_count());
1562
1563       // Leaving no references to ourselves.
1564       ptr.reset();
1565       EXPECT_EQ(0, ptr.use_count());
1566     }
1567   );
1568
1569   EXPECT_EQ(2, ptr.use_count());
1570
1571   ptr.reset();
1572
1573   promise.setWith([]{return 1l;});
1574 }
1575
1576 TEST(Future, Constructor) {
1577   auto f1 = []() -> Future<int> { return Future<int>(3); }();
1578   EXPECT_EQ(f1.value(), 3);
1579   auto f2 = []() -> Future<void> { return Future<void>(); }();
1580   EXPECT_NO_THROW(f2.value());
1581 }
1582
1583 TEST(Future, ImplicitConstructor) {
1584   auto f1 = []() -> Future<int> { return 3; }();
1585   EXPECT_EQ(f1.value(), 3);
1586   // Unfortunately, the C++ standard does not allow the
1587   // following implicit conversion to work:
1588   //auto f2 = []() -> Future<void> { }();
1589 }
1590
1591 TEST(Future, thenDynamic) {
1592   // folly::dynamic has a constructor that takes any T, this test makes
1593   // sure that we call the then lambda with folly::dynamic and not
1594   // Try<folly::dynamic> because that then fails to compile
1595   Promise<folly::dynamic> p;
1596   Future<folly::dynamic> f = p.getFuture().then(
1597       [](const folly::dynamic& d) {
1598         return folly::dynamic(d.asInt() + 3);
1599       }
1600   );
1601   p.setValue(2);
1602   EXPECT_EQ(f.get(), 5);
1603 }
1604
1605 TEST(Future, via_then_get_was_racy) {
1606   ThreadExecutor x;
1607   std::unique_ptr<int> val = folly::via(&x)
1608     .then([] { return folly::make_unique<int>(42); })
1609     .get();
1610   ASSERT_TRUE(!!val);
1611   EXPECT_EQ(42, *val);
1612 }
1613
1614 TEST(Future, ensure) {
1615   size_t count = 0;
1616   auto cob = [&]{ count++; };
1617   auto f = makeFuture(42)
1618     .ensure(cob)
1619     .then([](int) { throw std::runtime_error("ensure"); })
1620     .ensure(cob);
1621
1622   EXPECT_THROW(f.get(), std::runtime_error);
1623   EXPECT_EQ(2, count);
1624 }
1625
1626 TEST(Future, willEqual) {
1627     //both p1 and p2 already fulfilled
1628     {
1629     Promise<int> p1;
1630     Promise<int> p2;
1631     p1.setValue(27);
1632     p2.setValue(27);
1633     auto f1 = p1.getFuture();
1634     auto f2 = p2.getFuture();
1635     EXPECT_TRUE(f1.willEqual(f2).get());
1636     }{
1637     Promise<int> p1;
1638     Promise<int> p2;
1639     p1.setValue(27);
1640     p2.setValue(36);
1641     auto f1 = p1.getFuture();
1642     auto f2 = p2.getFuture();
1643     EXPECT_FALSE(f1.willEqual(f2).get());
1644     }
1645     //both p1 and p2 not yet fulfilled
1646     {
1647     Promise<int> p1;
1648     Promise<int> p2;
1649     auto f1 = p1.getFuture();
1650     auto f2 = p2.getFuture();
1651     auto f3 = f1.willEqual(f2);
1652     p1.setValue(27);
1653     p2.setValue(27);
1654     EXPECT_TRUE(f3.get());
1655     }{
1656     Promise<int> p1;
1657     Promise<int> p2;
1658     auto f1 = p1.getFuture();
1659     auto f2 = p2.getFuture();
1660     auto f3 = f1.willEqual(f2);
1661     p1.setValue(27);
1662     p2.setValue(36);
1663     EXPECT_FALSE(f3.get());
1664     }
1665     //p1 already fulfilled, p2 not yet fulfilled
1666     {
1667     Promise<int> p1;
1668     Promise<int> p2;
1669     p1.setValue(27);
1670     auto f1 = p1.getFuture();
1671     auto f2 = p2.getFuture();
1672     auto f3 = f1.willEqual(f2);
1673     p2.setValue(27);
1674     EXPECT_TRUE(f3.get());
1675     }{
1676     Promise<int> p1;
1677     Promise<int> p2;
1678     p1.setValue(27);
1679     auto f1 = p1.getFuture();
1680     auto f2 = p2.getFuture();
1681     auto f3 = f1.willEqual(f2);
1682     p2.setValue(36);
1683     EXPECT_FALSE(f3.get());
1684     }
1685     //p2 already fulfilled, p1 not yet fulfilled
1686     {
1687     Promise<int> p1;
1688     Promise<int> p2;
1689     p2.setValue(27);
1690     auto f1 = p1.getFuture();
1691     auto f2 = p2.getFuture();
1692     auto f3 = f1.willEqual(f2);
1693     p1.setValue(27);
1694     EXPECT_TRUE(f3.get());
1695     }{
1696     Promise<int> p1;
1697     Promise<int> p2;
1698     p2.setValue(36);
1699     auto f1 = p1.getFuture();
1700     auto f2 = p2.getFuture();
1701     auto f3 = f1.willEqual(f2);
1702     p1.setValue(27);
1703     EXPECT_FALSE(f3.get());
1704     }
1705 }
1706
1707 // Unwrap tests.
1708
1709 // A simple scenario for the unwrap call, when the promise was fulfilled
1710 // before calling to unwrap.
1711 TEST(Future, Unwrap_SimpleScenario) {
1712   Future<int> encapsulated_future = makeFuture(5484);
1713   Future<Future<int>> future = makeFuture(std::move(encapsulated_future));
1714   EXPECT_EQ(5484, future.unwrap().value());
1715 }
1716
1717 // Makes sure that unwrap() works when chaning Future's commands.
1718 TEST(Future, Unwrap_ChainCommands) {
1719   Future<Future<int>> future = makeFuture(makeFuture(5484));
1720   auto unwrapped = future.unwrap().then([](int i){ return i; });
1721   EXPECT_EQ(5484, unwrapped.value());
1722 }
1723
1724 // Makes sure that the unwrap call also works when the promise was not yet
1725 // fulfilled, and that the returned Future<T> becomes ready once the promise
1726 // is fulfilled.
1727 TEST(Future, Unwrap_FutureNotReady) {
1728   Promise<Future<int>> p;
1729   Future<Future<int>> future = p.getFuture();
1730   Future<int> unwrapped = future.unwrap();
1731   // Sanity - should not be ready before the promise is fulfilled.
1732   ASSERT_FALSE(unwrapped.isReady());
1733   // Fulfill the promise and make sure the unwrapped future is now ready.
1734   p.setValue(makeFuture(5484));
1735   ASSERT_TRUE(unwrapped.isReady());
1736   EXPECT_EQ(5484, unwrapped.value());
1737 }
1738
1739 TEST(Reduce, Basic) {
1740   auto makeFutures = [](int count) {
1741     std::vector<Future<int>> fs;
1742     for (int i = 1; i <= count; ++i) {
1743       fs.emplace_back(makeFuture(i));
1744     }
1745     return fs;
1746   };
1747
1748   // Empty (Try)
1749   {
1750     auto fs = makeFutures(0);
1751
1752     Future<double> f1 = reduce(fs, 1.2,
1753       [](double a, Try<int>&& b){
1754         return a + *b + 0.1;
1755       });
1756     EXPECT_EQ(1.2, f1.get());
1757   }
1758
1759   // One (Try)
1760   {
1761     auto fs = makeFutures(1);
1762
1763     Future<double> f1 = reduce(fs, 0.0,
1764       [](double a, Try<int>&& b){
1765         return a + *b + 0.1;
1766       });
1767     EXPECT_EQ(1.1, f1.get());
1768   }
1769
1770   // Returning values (Try)
1771   {
1772     auto fs = makeFutures(3);
1773
1774     Future<double> f1 = reduce(fs, 0.0,
1775       [](double a, Try<int>&& b){
1776         return a + *b + 0.1;
1777       });
1778     EXPECT_EQ(6.3, f1.get());
1779   }
1780
1781   // Returning values
1782   {
1783     auto fs = makeFutures(3);
1784
1785     Future<double> f1 = reduce(fs, 0.0,
1786       [](double a, int&& b){
1787         return a + b + 0.1;
1788       });
1789     EXPECT_EQ(6.3, f1.get());
1790   }
1791
1792   // Returning futures (Try)
1793   {
1794     auto fs = makeFutures(3);
1795
1796     Future<double> f2 = reduce(fs, 0.0,
1797       [](double a, Try<int>&& b){
1798         return makeFuture<double>(a + *b + 0.1);
1799       });
1800     EXPECT_EQ(6.3, f2.get());
1801   }
1802
1803   // Returning futures
1804   {
1805     auto fs = makeFutures(3);
1806
1807     Future<double> f2 = reduce(fs, 0.0,
1808       [](double a, int&& b){
1809         return makeFuture<double>(a + b + 0.1);
1810       });
1811     EXPECT_EQ(6.3, f2.get());
1812   }
1813 }
1814
1815 TEST(Reduce, Chain) {
1816   auto makeFutures = [](int count) {
1817     std::vector<Future<int>> fs;
1818     for (int i = 1; i <= count; ++i) {
1819       fs.emplace_back(makeFuture(i));
1820     }
1821     return fs;
1822   };
1823
1824   {
1825     auto f = collectAll(makeFutures(3)).reduce(0, [](int a, Try<int>&& b){
1826       return a + *b;
1827     });
1828     EXPECT_EQ(6, f.get());
1829   }
1830   {
1831     auto f = collect(makeFutures(3)).reduce(0, [](int a, int&& b){
1832       return a + b;
1833     });
1834     EXPECT_EQ(6, f.get());
1835   }
1836 }
1837
1838 TEST(Reduce, UnorderedReduce) {
1839   {
1840     std::vector<Future<int>> fs;
1841     fs.push_back(makeFuture(1));
1842     fs.push_back(makeFuture(2));
1843     fs.push_back(makeFuture(3));
1844
1845     Future<double> f = unorderedReduce(fs.begin(), fs.end(), 0.0,
1846       [](double a, int&& b){
1847         return double(b);
1848       });
1849     EXPECT_EQ(3.0, f.get());
1850   }
1851   {
1852     Promise<int> p1;
1853     Promise<int> p2;
1854     Promise<int> p3;
1855
1856     std::vector<Future<int>> fs;
1857     fs.push_back(p1.getFuture());
1858     fs.push_back(p2.getFuture());
1859     fs.push_back(p3.getFuture());
1860
1861     Future<double> f = unorderedReduce(fs.begin(), fs.end(), 0.0,
1862       [](double a, int&& b){
1863         return double(b);
1864       });
1865     p3.setValue(3);
1866     p2.setValue(2);
1867     p1.setValue(1);
1868     EXPECT_EQ(1.0, f.get());
1869   }
1870 }
1871
1872 TEST(Reduce, UnorderedReduceException) {
1873   Promise<int> p1;
1874   Promise<int> p2;
1875   Promise<int> p3;
1876
1877   std::vector<Future<int>> fs;
1878   fs.push_back(p1.getFuture());
1879   fs.push_back(p2.getFuture());
1880   fs.push_back(p3.getFuture());
1881
1882   Future<double> f = unorderedReduce(fs.begin(), fs.end(), 0.0,
1883     [](double a, int&& b){
1884       return b + 0.0;
1885     });
1886   p3.setValue(3);
1887   p2.setException(exception_wrapper(std::runtime_error("blah")));
1888   p1.setValue(1);
1889   EXPECT_THROW(f.get(), std::runtime_error);
1890 }
1891
1892 TEST(Map, Basic) {
1893   Promise<int> p1;
1894   Promise<int> p2;
1895   Promise<int> p3;
1896
1897   std::vector<Future<int>> fs;
1898   fs.push_back(p1.getFuture());
1899   fs.push_back(p2.getFuture());
1900   fs.push_back(p3.getFuture());
1901
1902   int c = 0;
1903   std::vector<Future<void>> fs2 = futures::map(fs, [&](int i){
1904     c += i;
1905   });
1906
1907   // Ensure we call the callbacks as the futures complete regardless of order
1908   p2.setValue(1);
1909   EXPECT_EQ(1, c);
1910   p3.setValue(1);
1911   EXPECT_EQ(2, c);
1912   p1.setValue(1);
1913   EXPECT_EQ(3, c);
1914
1915   EXPECT_TRUE(collect(fs2).isReady());
1916 }