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