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