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