4dd3f2dc574239d9c6c5d76c5b567c0fbe6e23cb
[folly.git] / folly / futures / test / FutureTest.cpp
1 /*
2  * Copyright 2017 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 <folly/futures/Future.h>
18 #include <folly/Unit.h>
19 #include <folly/Memory.h>
20 #include <folly/Executor.h>
21 #include <folly/dynamic.h>
22 #include <folly/Baton.h>
23 #include <folly/portability/GTest.h>
24
25 #include <algorithm>
26 #include <atomic>
27 #include <memory>
28 #include <numeric>
29 #include <string>
30 #include <thread>
31 #include <type_traits>
32
33 using namespace folly;
34
35 #define EXPECT_TYPE(x, T) \
36   EXPECT_TRUE((std::is_same<decltype(x), T>::value))
37
38 typedef FutureException eggs_t;
39 static eggs_t eggs("eggs");
40
41 // Future
42
43 TEST(Future, makeEmpty) {
44   auto f = Future<int>::makeEmpty();
45   EXPECT_THROW(f.isReady(), NoState);
46 }
47
48 TEST(Future, futureDefaultCtor) {
49   Future<Unit>();
50 }
51
52 TEST(Future, futureToUnit) {
53   Future<Unit> fu = makeFuture(42).unit();
54   fu.value();
55   EXPECT_TRUE(makeFuture<int>(eggs).unit().hasException());
56 }
57
58 TEST(Future, voidFutureToUnit) {
59   Future<Unit> fu = makeFuture().unit();
60   fu.value();
61   EXPECT_TRUE(makeFuture<Unit>(eggs).unit().hasException());
62 }
63
64 TEST(Future, unitFutureToUnitIdentity) {
65   Future<Unit> fu = makeFuture(Unit{}).unit();
66   fu.value();
67   EXPECT_TRUE(makeFuture<Unit>(eggs).unit().hasException());
68 }
69
70 TEST(Future, toUnitWhileInProgress) {
71   Promise<int> p;
72   Future<Unit> fu = p.getFuture().unit();
73   EXPECT_FALSE(fu.isReady());
74   p.setValue(42);
75   EXPECT_TRUE(fu.isReady());
76 }
77
78 TEST(Future, makeFutureWithUnit) {
79   int count = 0;
80   Future<Unit> fu = makeFutureWith([&] { count++; });
81   EXPECT_EQ(1, count);
82 }
83
84 namespace {
85 Future<int> onErrorHelperEggs(const eggs_t&) {
86   return makeFuture(10);
87 }
88 Future<int> onErrorHelperGeneric(const std::exception&) {
89   return makeFuture(20);
90 }
91 }
92
93 TEST(Future, onError) {
94   bool theFlag = false;
95   auto flag = [&]{ theFlag = true; };
96 #define EXPECT_FLAG() \
97   do { \
98     EXPECT_TRUE(theFlag); \
99     theFlag = false; \
100   } while(0);
101
102 #define EXPECT_NO_FLAG() \
103   do { \
104     EXPECT_FALSE(theFlag); \
105     theFlag = false; \
106   } while(0);
107
108   // By reference
109   {
110     auto f = makeFuture().then([] {
111       throw eggs;
112     }).onError([&](eggs_t& /* e */) { flag(); });
113     EXPECT_FLAG();
114     EXPECT_NO_THROW(f.value());
115   }
116
117   {
118     auto f = makeFuture()
119                  .then([] { throw eggs; })
120                  .onError([&](eggs_t& /* e */) {
121                    flag();
122                    return makeFuture();
123                  });
124     EXPECT_FLAG();
125     EXPECT_NO_THROW(f.value());
126   }
127
128   // By value
129   {
130     auto f = makeFuture().then([] {
131       throw eggs;
132     }).onError([&](eggs_t /* e */) { flag(); });
133     EXPECT_FLAG();
134     EXPECT_NO_THROW(f.value());
135   }
136
137   {
138     auto f = makeFuture()
139                  .then([] { throw eggs; })
140                  .onError([&](eggs_t /* e */) {
141                    flag();
142                    return makeFuture();
143                  });
144     EXPECT_FLAG();
145     EXPECT_NO_THROW(f.value());
146   }
147
148   // Polymorphic
149   {
150     auto f = makeFuture().then([] {
151       throw eggs;
152     }).onError([&](std::exception& /* e */) { flag(); });
153     EXPECT_FLAG();
154     EXPECT_NO_THROW(f.value());
155   }
156
157   {
158     auto f = makeFuture()
159                  .then([] { throw eggs; })
160                  .onError([&](std::exception& /* e */) {
161                    flag();
162                    return makeFuture();
163                  });
164     EXPECT_FLAG();
165     EXPECT_NO_THROW(f.value());
166   }
167
168   // Non-exceptions
169   {
170     auto f = makeFuture().then([] {
171       throw - 1;
172     }).onError([&](int /* e */) { flag(); });
173     EXPECT_FLAG();
174     EXPECT_NO_THROW(f.value());
175   }
176
177   {
178     auto f = makeFuture()
179                  .then([] { throw - 1; })
180                  .onError([&](int /* e */) {
181                    flag();
182                    return makeFuture();
183                  });
184     EXPECT_FLAG();
185     EXPECT_NO_THROW(f.value());
186   }
187
188   // Mutable lambda
189   {
190     auto f = makeFuture().then([] {
191       throw eggs;
192     }).onError([&](eggs_t& /* e */) mutable { flag(); });
193     EXPECT_FLAG();
194     EXPECT_NO_THROW(f.value());
195   }
196
197   {
198     auto f = makeFuture()
199                  .then([] { throw eggs; })
200                  .onError([&](eggs_t& /* e */) mutable {
201                    flag();
202                    return makeFuture();
203                  });
204     EXPECT_FLAG();
205     EXPECT_NO_THROW(f.value());
206   }
207
208   // Function pointer
209   {
210     auto f = makeFuture()
211                  .then([]() -> int { throw eggs; })
212                  .onError(onErrorHelperEggs)
213                  .onError(onErrorHelperGeneric);
214     EXPECT_EQ(10, f.value());
215   }
216   {
217     auto f = makeFuture()
218                  .then([]() -> int { throw std::runtime_error("test"); })
219                  .onError(onErrorHelperEggs)
220                  .onError(onErrorHelperGeneric);
221     EXPECT_EQ(20, f.value());
222   }
223   {
224     auto f = makeFuture()
225                  .then([]() -> int { throw std::runtime_error("test"); })
226                  .onError(onErrorHelperEggs);
227     EXPECT_THROW(f.value(), std::runtime_error);
228   }
229
230   // No throw
231   {
232     auto f = makeFuture()
233                  .then([] { return 42; })
234                  .onError([&](eggs_t& /* e */) {
235                    flag();
236                    return -1;
237                  });
238     EXPECT_NO_FLAG();
239     EXPECT_EQ(42, f.value());
240   }
241
242   {
243     auto f = makeFuture()
244                  .then([] { return 42; })
245                  .onError([&](eggs_t& /* e */) {
246                    flag();
247                    return makeFuture<int>(-1);
248                  });
249     EXPECT_NO_FLAG();
250     EXPECT_EQ(42, f.value());
251   }
252
253   // Catch different exception
254   {
255     auto f = makeFuture().then([] {
256       throw eggs;
257     }).onError([&](std::runtime_error& /* e */) { flag(); });
258     EXPECT_NO_FLAG();
259     EXPECT_THROW(f.value(), eggs_t);
260   }
261
262   {
263     auto f = makeFuture()
264                  .then([] { throw eggs; })
265                  .onError([&](std::runtime_error& /* e */) {
266                    flag();
267                    return makeFuture();
268                  });
269     EXPECT_NO_FLAG();
270     EXPECT_THROW(f.value(), eggs_t);
271   }
272
273   // Returned value propagates
274   {
275     auto f = makeFuture().then([]() -> int {
276       throw eggs;
277     }).onError([&](eggs_t& /* e */) { return 42; });
278     EXPECT_EQ(42, f.value());
279   }
280
281   // Returned future propagates
282   {
283     auto f = makeFuture().then([]() -> int {
284       throw eggs;
285     }).onError([&](eggs_t& /* e */) { return makeFuture<int>(42); });
286     EXPECT_EQ(42, f.value());
287   }
288
289   // Throw in callback
290   {
291     auto f = makeFuture()
292       .then([]() -> int { throw eggs; })
293       .onError([&] (eggs_t& e) -> int { throw e; });
294     EXPECT_THROW(f.value(), eggs_t);
295   }
296
297   {
298     auto f = makeFuture()
299       .then([]() -> int { throw eggs; })
300       .onError([&] (eggs_t& e) -> Future<int> { throw e; });
301     EXPECT_THROW(f.value(), eggs_t);
302   }
303
304   // exception_wrapper, return Future<T>
305   {
306     auto f = makeFuture()
307                  .then([] { throw eggs; })
308                  .onError([&](exception_wrapper /* e */) {
309                    flag();
310                    return makeFuture();
311                  });
312     EXPECT_FLAG();
313     EXPECT_NO_THROW(f.value());
314   }
315
316   // exception_wrapper, return Future<T> but throw
317   {
318     auto f = makeFuture()
319                  .then([]() -> int {
320                    throw eggs;
321                  })
322                  .onError([&](exception_wrapper /* e */) -> Future<int> {
323                    flag();
324                    throw eggs;
325                  });
326     EXPECT_FLAG();
327     EXPECT_THROW(f.value(), eggs_t);
328   }
329
330   // exception_wrapper, return T
331   {
332     auto f = makeFuture()
333                  .then([]() -> int {
334                    throw eggs;
335                  })
336                  .onError([&](exception_wrapper /* e */) {
337                    flag();
338                    return -1;
339                  });
340     EXPECT_FLAG();
341     EXPECT_EQ(-1, f.value());
342   }
343
344   // exception_wrapper, return T but throw
345   {
346     auto f = makeFuture()
347                  .then([]() -> int {
348                    throw eggs;
349                  })
350                  .onError([&](exception_wrapper /* e */) -> int {
351                    flag();
352                    throw eggs;
353                  });
354     EXPECT_FLAG();
355     EXPECT_THROW(f.value(), eggs_t);
356   }
357
358   // const exception_wrapper&
359   {
360     auto f = makeFuture()
361                  .then([] { throw eggs; })
362                  .onError([&](const exception_wrapper& /* e */) {
363                    flag();
364                    return makeFuture();
365                  });
366     EXPECT_FLAG();
367     EXPECT_NO_THROW(f.value());
368   }
369
370 }
371
372 TEST(Future, special) {
373   EXPECT_FALSE(std::is_copy_constructible<Future<int>>::value);
374   EXPECT_FALSE(std::is_copy_assignable<Future<int>>::value);
375   EXPECT_TRUE(std::is_move_constructible<Future<int>>::value);
376   EXPECT_TRUE(std::is_move_assignable<Future<int>>::value);
377 }
378
379 TEST(Future, then) {
380   auto f = makeFuture<std::string>("0")
381     .then([](){
382       return makeFuture<std::string>("1"); })
383     .then([](Try<std::string>&& t) {
384       return makeFuture(t.value() + ";2"); })
385     .then([](const Try<std::string>&& t) {
386       return makeFuture(t.value() + ";3"); })
387     .then([](Try<std::string>& t) {
388       return makeFuture(t.value() + ";4"); })
389     .then([](const Try<std::string>& t) {
390       return makeFuture(t.value() + ";5"); })
391     .then([](Try<std::string> t) {
392       return makeFuture(t.value() + ";6"); })
393     .then([](const Try<std::string> t) {
394       return makeFuture(t.value() + ";7"); })
395     .then([](std::string&& s) {
396       return makeFuture(s + ";8"); })
397     .then([](const std::string&& s) {
398       return makeFuture(s + ";9"); })
399     .then([](std::string& s) {
400       return makeFuture(s + ";10"); })
401     .then([](const std::string& s) {
402       return makeFuture(s + ";11"); })
403     .then([](std::string s) {
404       return makeFuture(s + ";12"); })
405     .then([](const std::string s) {
406       return makeFuture(s + ";13"); })
407   ;
408   EXPECT_EQ(f.value(), "1;2;3;4;5;6;7;8;9;10;11;12;13");
409 }
410
411 TEST(Future, thenTry) {
412   bool flag = false;
413
414   makeFuture<int>(42).then([&](Try<int>&& t) {
415                               flag = true;
416                               EXPECT_EQ(42, t.value());
417                             });
418   EXPECT_TRUE(flag); flag = false;
419
420   makeFuture<int>(42)
421     .then([](Try<int>&& t) { return t.value(); })
422     .then([&](Try<int>&& t) { flag = true; EXPECT_EQ(42, t.value()); });
423   EXPECT_TRUE(flag); flag = false;
424
425   makeFuture().then([&](Try<Unit>&& t) { flag = true; t.value(); });
426   EXPECT_TRUE(flag); flag = false;
427
428   Promise<Unit> p;
429   auto f = p.getFuture().then([&](Try<Unit>&& /* t */) { flag = true; });
430   EXPECT_FALSE(flag);
431   EXPECT_FALSE(f.isReady());
432   p.setValue();
433   EXPECT_TRUE(flag);
434   EXPECT_TRUE(f.isReady());
435 }
436
437 TEST(Future, thenValue) {
438   bool flag = false;
439   makeFuture<int>(42).then([&](int i){
440     EXPECT_EQ(42, i);
441     flag = true;
442   });
443   EXPECT_TRUE(flag); flag = false;
444
445   makeFuture<int>(42)
446     .then([](int i){ return i; })
447     .then([&](int i) { flag = true; EXPECT_EQ(42, i); });
448   EXPECT_TRUE(flag); flag = false;
449
450   makeFuture().then([&]{
451     flag = true;
452   });
453   EXPECT_TRUE(flag); flag = false;
454
455   auto f = makeFuture<int>(eggs).then([&](int /* i */) {});
456   EXPECT_THROW(f.value(), eggs_t);
457
458   f = makeFuture<Unit>(eggs).then([&]{});
459   EXPECT_THROW(f.value(), eggs_t);
460 }
461
462 TEST(Future, thenValueFuture) {
463   bool flag = false;
464   makeFuture<int>(42)
465     .then([](int i){ return makeFuture<int>(std::move(i)); })
466     .then([&](Try<int>&& t) { flag = true; EXPECT_EQ(42, t.value()); });
467   EXPECT_TRUE(flag); flag = false;
468
469   makeFuture().then([] {
470     return makeFuture();
471   }).then([&](Try<Unit>&& /* t */) { flag = true; });
472   EXPECT_TRUE(flag); flag = false;
473 }
474
475 static std::string doWorkStatic(Try<std::string>&& t) {
476   return t.value() + ";static";
477 }
478
479 TEST(Future, thenFunction) {
480   struct Worker {
481     std::string doWork(Try<std::string>&& t) {
482       return t.value() + ";class";
483     }
484     static std::string doWorkStatic(Try<std::string>&& t) {
485       return t.value() + ";class-static";
486     }
487   } w;
488
489   auto f = makeFuture<std::string>("start")
490     .then(doWorkStatic)
491     .then(Worker::doWorkStatic)
492     .then(&Worker::doWork, &w);
493
494   EXPECT_EQ(f.value(), "start;static;class-static;class");
495 }
496
497 static Future<std::string> doWorkStaticFuture(Try<std::string>&& t) {
498   return makeFuture(t.value() + ";static");
499 }
500
501 TEST(Future, thenFunctionFuture) {
502   struct Worker {
503     Future<std::string> doWorkFuture(Try<std::string>&& t) {
504       return makeFuture(t.value() + ";class");
505     }
506     static Future<std::string> doWorkStaticFuture(Try<std::string>&& t) {
507       return makeFuture(t.value() + ";class-static");
508     }
509   } w;
510
511   auto f = makeFuture<std::string>("start")
512     .then(doWorkStaticFuture)
513     .then(Worker::doWorkStaticFuture)
514     .then(&Worker::doWorkFuture, &w);
515
516   EXPECT_EQ(f.value(), "start;static;class-static;class");
517 }
518
519 TEST(Future, thenStdFunction) {
520   {
521     std::function<int()> fn = [](){ return 42; };
522     auto f = makeFuture().then(std::move(fn));
523     EXPECT_EQ(f.value(), 42);
524   }
525   {
526     std::function<int(int)> fn = [](int i){ return i + 23; };
527     auto f = makeFuture(19).then(std::move(fn));
528     EXPECT_EQ(f.value(), 42);
529   }
530   {
531     std::function<int(Try<int>&)> fn = [](Try<int>& t){ return t.value() + 2; };
532     auto f = makeFuture(1).then(std::move(fn));
533     EXPECT_EQ(f.value(), 3);
534   }
535   {
536     bool flag = false;
537     std::function<void()> fn = [&flag](){ flag = true; };
538     auto f = makeFuture().then(std::move(fn));
539     EXPECT_TRUE(f.isReady());
540     EXPECT_TRUE(flag);
541   }
542 }
543
544 TEST(Future, thenBind) {
545   auto l = []() {
546     return makeFuture("bind");
547   };
548   auto b = std::bind(l);
549   auto f = makeFuture().then(std::move(b));
550   EXPECT_EQ(f.value(), "bind");
551 }
552
553 TEST(Future, thenBindTry) {
554   auto l = [](Try<std::string>&& t) {
555     return makeFuture(t.value() + ";bind");
556   };
557   auto b = std::bind(l, std::placeholders::_1);
558   auto f = makeFuture<std::string>("start").then(std::move(b));
559
560   EXPECT_EQ(f.value(), "start;bind");
561 }
562
563 TEST(Future, value) {
564   auto f = makeFuture(std::unique_ptr<int>(new int(42)));
565   auto up = std::move(f.value());
566   EXPECT_EQ(42, *up);
567
568   EXPECT_THROW(makeFuture<int>(eggs).value(), eggs_t);
569 }
570
571 TEST(Future, isReady) {
572   Promise<int> p;
573   auto f = p.getFuture();
574   EXPECT_FALSE(f.isReady());
575   p.setValue(42);
576   EXPECT_TRUE(f.isReady());
577   }
578
579 TEST(Future, futureNotReady) {
580   Promise<int> p;
581   Future<int> f = p.getFuture();
582   EXPECT_THROW(f.value(), eggs_t);
583 }
584
585 TEST(Future, hasException) {
586   EXPECT_TRUE(makeFuture<int>(eggs).getTry().hasException());
587   EXPECT_FALSE(makeFuture(42).getTry().hasException());
588 }
589
590 TEST(Future, hasValue) {
591   EXPECT_TRUE(makeFuture(42).getTry().hasValue());
592   EXPECT_FALSE(makeFuture<int>(eggs).getTry().hasValue());
593 }
594
595 TEST(Future, makeFuture) {
596   EXPECT_TYPE(makeFuture(42), Future<int>);
597   EXPECT_EQ(42, makeFuture(42).value());
598
599   EXPECT_TYPE(makeFuture<float>(42), Future<float>);
600   EXPECT_EQ(42, makeFuture<float>(42).value());
601
602   auto fun = [] { return 42; };
603   EXPECT_TYPE(makeFutureWith(fun), Future<int>);
604   EXPECT_EQ(42, makeFutureWith(fun).value());
605
606   auto funf = [] { return makeFuture<int>(43); };
607   EXPECT_TYPE(makeFutureWith(funf), Future<int>);
608   EXPECT_EQ(43, makeFutureWith(funf).value());
609
610   auto failfun = []() -> int { throw eggs; };
611   EXPECT_TYPE(makeFutureWith(failfun), Future<int>);
612   EXPECT_NO_THROW(makeFutureWith(failfun));
613   EXPECT_THROW(makeFutureWith(failfun).value(), eggs_t);
614
615   auto failfunf = []() -> Future<int> { throw eggs; };
616   EXPECT_TYPE(makeFutureWith(failfunf), Future<int>);
617   EXPECT_NO_THROW(makeFutureWith(failfunf));
618   EXPECT_THROW(makeFutureWith(failfunf).value(), eggs_t);
619
620   EXPECT_TYPE(makeFuture(), Future<Unit>);
621 }
622
623 TEST(Future, finish) {
624   auto x = std::make_shared<int>(0);
625
626   Promise<int> p;
627   auto f = p.getFuture().then([x](Try<int>&& t) { *x = t.value(); });
628
629   // The callback hasn't executed
630   EXPECT_EQ(0, *x);
631
632   // The callback has a reference to x
633   EXPECT_EQ(2, x.use_count());
634
635   p.setValue(42);
636
637   // the callback has executed
638   EXPECT_EQ(42, *x);
639
640   // the callback has been destructed
641   // and has released its reference to x
642   EXPECT_EQ(1, x.use_count());
643 }
644
645 TEST(Future, finishBigLambda) {
646   auto x = std::make_shared<int>(0);
647
648   // bulk_data, to be captured in the lambda passed to Future::then.
649   // This is meant to force that the lambda can't be stored inside
650   // the Future object.
651   std::array<char, sizeof(detail::Core<int>)> bulk_data = {{0}};
652
653   // suppress gcc warning about bulk_data not being used
654   EXPECT_EQ(bulk_data[0], 0);
655
656   Promise<int> p;
657   auto f = p.getFuture().then([x, bulk_data](Try<int>&& t) {
658     (void)bulk_data;
659     *x = t.value();
660   });
661
662   // The callback hasn't executed
663   EXPECT_EQ(0, *x);
664
665   // The callback has a reference to x
666   EXPECT_EQ(2, x.use_count());
667
668   p.setValue(42);
669
670   // the callback has executed
671   EXPECT_EQ(42, *x);
672
673   // the callback has been destructed
674   // and has released its reference to x
675   EXPECT_EQ(1, x.use_count());
676 }
677
678 TEST(Future, unwrap) {
679   Promise<int> a;
680   Promise<int> b;
681
682   auto fa = a.getFuture();
683   auto fb = b.getFuture();
684
685   bool flag1 = false;
686   bool flag2 = false;
687
688   // do a, then do b, and get the result of a + b.
689   Future<int> f = fa.then([&](Try<int>&& ta) {
690     auto va = ta.value();
691     flag1 = true;
692     return fb.then([va, &flag2](Try<int>&& tb) {
693       flag2 = true;
694       return va + tb.value();
695     });
696   });
697
698   EXPECT_FALSE(flag1);
699   EXPECT_FALSE(flag2);
700   EXPECT_FALSE(f.isReady());
701
702   a.setValue(3);
703   EXPECT_TRUE(flag1);
704   EXPECT_FALSE(flag2);
705   EXPECT_FALSE(f.isReady());
706
707   b.setValue(4);
708   EXPECT_TRUE(flag1);
709   EXPECT_TRUE(flag2);
710   EXPECT_EQ(7, f.value());
711 }
712
713 TEST(Future, throwCaughtInImmediateThen) {
714   // Neither of these should throw "Promise already satisfied"
715   makeFuture().then(
716     [=](Try<Unit>&&) -> int { throw std::exception(); });
717   makeFuture().then(
718     [=](Try<Unit>&&) -> Future<int> { throw std::exception(); });
719 }
720
721 TEST(Future, throwIfFailed) {
722   makeFuture<Unit>(eggs)
723     .then([=](Try<Unit>&& t) {
724       EXPECT_THROW(t.throwIfFailed(), eggs_t);
725     });
726   makeFuture()
727     .then([=](Try<Unit>&& t) {
728       EXPECT_NO_THROW(t.throwIfFailed());
729     });
730
731   makeFuture<int>(eggs)
732     .then([=](Try<int>&& t) {
733       EXPECT_THROW(t.throwIfFailed(), eggs_t);
734     });
735   makeFuture<int>(42)
736     .then([=](Try<int>&& t) {
737       EXPECT_NO_THROW(t.throwIfFailed());
738     });
739 }
740
741 TEST(Future, getFutureAfterSetValue) {
742   Promise<int> p;
743   p.setValue(42);
744   EXPECT_EQ(42, p.getFuture().value());
745 }
746
747 TEST(Future, getFutureAfterSetException) {
748   Promise<Unit> p;
749   p.setWith([]() -> void { throw std::logic_error("foo"); });
750   EXPECT_THROW(p.getFuture().value(), std::logic_error);
751 }
752
753 TEST(Future, detachRace) {
754   // Task #5438209
755   // This test is designed to detect a race that was in Core::detachOne()
756   // where detached_ was incremented and then tested, and that
757   // allowed a race where both Promise and Future would think they were the
758   // second and both try to delete. This showed up at scale but was very
759   // difficult to reliably repro in a test. As it is, this only fails about
760   // once in every 1,000 executions. Doing this 1,000 times is going to make a
761   // slow test so I won't do that but if it ever fails, take it seriously, and
762   // run the test binary with "--gtest_repeat=10000 --gtest_filter=*detachRace"
763   // (Don't forget to enable ASAN)
764   auto p = std::make_unique<Promise<bool>>();
765   auto f = std::make_unique<Future<bool>>(p->getFuture());
766   folly::Baton<> baton;
767   std::thread t1([&]{
768     baton.post();
769     p.reset();
770   });
771   baton.wait();
772   f.reset();
773   t1.join();
774 }
775
776 // Test of handling of a circular dependency. It's never recommended
777 // to have one because of possible memory leaks. Here we test that
778 // we can handle freeing of the Future while it is running.
779 TEST(Future, CircularDependencySharedPtrSelfReset) {
780   Promise<int64_t> promise;
781   auto ptr = std::make_shared<Future<int64_t>>(promise.getFuture());
782
783   ptr->then([ptr](folly::Try<int64_t>&& /* uid */) mutable {
784     EXPECT_EQ(1, ptr.use_count());
785
786     // Leaving no references to ourselves.
787     ptr.reset();
788     EXPECT_EQ(0, ptr.use_count());
789   });
790
791   EXPECT_EQ(2, ptr.use_count());
792
793   ptr.reset();
794
795   promise.setValue(1);
796 }
797
798 TEST(Future, Constructor) {
799   auto f1 = []() -> Future<int> { return Future<int>(3); }();
800   EXPECT_EQ(f1.value(), 3);
801   auto f2 = []() -> Future<Unit> { return Future<Unit>(); }();
802   EXPECT_NO_THROW(f2.value());
803 }
804
805 TEST(Future, ImplicitConstructor) {
806   auto f1 = []() -> Future<int> { return 3; }();
807   EXPECT_EQ(f1.value(), 3);
808   // Unfortunately, the C++ standard does not allow the
809   // following implicit conversion to work:
810   //auto f2 = []() -> Future<Unit> { }();
811 }
812
813 TEST(Future, InPlaceConstructor) {
814   auto f = Future<std::pair<int, double>>(in_place, 5, 3.2);
815   EXPECT_EQ(5, f.value().first);
816 }
817
818 TEST(Future, thenDynamic) {
819   // folly::dynamic has a constructor that takes any T, this test makes
820   // sure that we call the then lambda with folly::dynamic and not
821   // Try<folly::dynamic> because that then fails to compile
822   Promise<folly::dynamic> p;
823   Future<folly::dynamic> f = p.getFuture().then(
824       [](const folly::dynamic& d) {
825         return folly::dynamic(d.asInt() + 3);
826       }
827   );
828   p.setValue(2);
829   EXPECT_EQ(f.get(), 5);
830 }
831
832 TEST(Future, RequestContext) {
833   class NewThreadExecutor : public Executor {
834    public:
835     ~NewThreadExecutor() override {
836       std::for_each(v_.begin(), v_.end(), [](std::thread& t){ t.join(); });
837     }
838     void add(Func f) override {
839       if (throwsOnAdd_) { throw std::exception(); }
840       v_.emplace_back(std::move(f));
841     }
842     void addWithPriority(Func f, int8_t /* prio */) override {
843       add(std::move(f));
844     }
845     uint8_t getNumPriorities() const override { return numPriorities_; }
846
847     void setHandlesPriorities() { numPriorities_ = 2; }
848     void setThrowsOnAdd() { throwsOnAdd_ = true; }
849    private:
850     std::vector<std::thread> v_;
851     uint8_t numPriorities_ = 1;
852     bool throwsOnAdd_ = false;
853   };
854
855   struct MyRequestData : RequestData {
856     MyRequestData(bool value = false) : value(value) {}
857     bool value;
858   };
859
860   Promise<int> p1, p2;
861   NewThreadExecutor e;
862   {
863     folly::RequestContextScopeGuard rctx;
864     RequestContext::get()->setContextData(
865         "key", std::make_unique<MyRequestData>(true));
866     auto checker = [](int lineno) {
867       return [lineno](Try<int>&& /* t */) {
868         auto d = static_cast<MyRequestData*>(
869             RequestContext::get()->getContextData("key"));
870         EXPECT_TRUE(d && d->value) << "on line " << lineno;
871       };
872     };
873
874     makeFuture(1).via(&e).then(checker(__LINE__));
875
876     e.setHandlesPriorities();
877     makeFuture(2).via(&e).then(checker(__LINE__));
878
879     p1.getFuture().then(checker(__LINE__));
880
881     e.setThrowsOnAdd();
882     p2.getFuture().via(&e).then(checker(__LINE__));
883   }
884   // Assert that no RequestContext is set
885   EXPECT_FALSE(RequestContext::saveContext());
886   p1.setValue(3);
887   p2.setValue(4);
888 }
889
890 TEST(Future, makeFutureNoThrow) {
891   makeFuture().value();
892 }
893
894 TEST(Future, invokeCallbackReturningValueAsRvalue) {
895   struct Foo {
896     int operator()(int x) & {
897       return x + 1;
898     }
899     int operator()(int x) const& {
900       return x + 2;
901     }
902     int operator()(int x) && {
903       return x + 3;
904     }
905   };
906
907   Foo foo;
908   Foo const cfoo;
909
910   // The callback will be copied when given as lvalue or const ref, and moved
911   // if provided as rvalue. Either way, it should be executed as rvalue.
912   EXPECT_EQ(103, makeFuture<int>(100).then(foo).value());
913   EXPECT_EQ(203, makeFuture<int>(200).then(cfoo).value());
914   EXPECT_EQ(303, makeFuture<int>(300).then(Foo()).value());
915 }
916
917 TEST(Future, invokeCallbackReturningFutureAsRvalue) {
918   struct Foo {
919     Future<int> operator()(int x) & {
920       return x + 1;
921     }
922     Future<int> operator()(int x) const& {
923       return x + 2;
924     }
925     Future<int> operator()(int x) && {
926       return x + 3;
927     }
928   };
929
930   Foo foo;
931   Foo const cfoo;
932
933   // The callback will be copied when given as lvalue or const ref, and moved
934   // if provided as rvalue. Either way, it should be executed as rvalue.
935   EXPECT_EQ(103, makeFuture<int>(100).then(foo).value());
936   EXPECT_EQ(203, makeFuture<int>(200).then(cfoo).value());
937   EXPECT_EQ(303, makeFuture<int>(300).then(Foo()).value());
938 }