2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
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>
31 #include <type_traits>
33 using namespace folly;
35 #define EXPECT_TYPE(x, T) \
36 EXPECT_TRUE((std::is_same<decltype(x), T>::value))
38 typedef FutureException eggs_t;
39 static eggs_t eggs("eggs");
43 TEST(Future, futureDefaultCtor) {
47 TEST(Future, futureToUnit) {
48 Future<Unit> fu = makeFuture(42).unit();
50 EXPECT_TRUE(makeFuture<int>(eggs).unit().hasException());
53 TEST(Future, voidFutureToUnit) {
54 Future<Unit> fu = makeFuture().unit();
56 EXPECT_TRUE(makeFuture<Unit>(eggs).unit().hasException());
59 TEST(Future, unitFutureToUnitIdentity) {
60 Future<Unit> fu = makeFuture(Unit{}).unit();
62 EXPECT_TRUE(makeFuture<Unit>(eggs).unit().hasException());
65 TEST(Future, toUnitWhileInProgress) {
67 Future<Unit> fu = p.getFuture().unit();
68 EXPECT_FALSE(fu.isReady());
70 EXPECT_TRUE(fu.isReady());
73 TEST(Future, makeFutureWithUnit) {
75 Future<Unit> fu = makeFutureWith([&] { count++; });
79 TEST(Future, onError) {
81 auto flag = [&]{ theFlag = true; };
82 #define EXPECT_FLAG() \
84 EXPECT_TRUE(theFlag); \
88 #define EXPECT_NO_FLAG() \
90 EXPECT_FALSE(theFlag); \
96 auto f = makeFuture().then([] {
98 }).onError([&](eggs_t& /* e */) { flag(); });
100 EXPECT_NO_THROW(f.value());
104 auto f = makeFuture()
105 .then([] { throw eggs; })
106 .onError([&](eggs_t& /* e */) {
111 EXPECT_NO_THROW(f.value());
116 auto f = makeFuture().then([] {
118 }).onError([&](eggs_t /* e */) { flag(); });
120 EXPECT_NO_THROW(f.value());
124 auto f = makeFuture()
125 .then([] { throw eggs; })
126 .onError([&](eggs_t /* e */) {
131 EXPECT_NO_THROW(f.value());
136 auto f = makeFuture().then([] {
138 }).onError([&](std::exception& /* e */) { flag(); });
140 EXPECT_NO_THROW(f.value());
144 auto f = makeFuture()
145 .then([] { throw eggs; })
146 .onError([&](std::exception& /* e */) {
151 EXPECT_NO_THROW(f.value());
156 auto f = makeFuture().then([] {
158 }).onError([&](int /* e */) { flag(); });
160 EXPECT_NO_THROW(f.value());
164 auto f = makeFuture()
165 .then([] { throw - 1; })
166 .onError([&](int /* e */) {
171 EXPECT_NO_THROW(f.value());
176 auto f = makeFuture().then([] {
178 }).onError([&](eggs_t& /* e */) mutable { flag(); });
180 EXPECT_NO_THROW(f.value());
184 auto f = makeFuture()
185 .then([] { throw eggs; })
186 .onError([&](eggs_t& /* e */) mutable {
191 EXPECT_NO_THROW(f.value());
196 auto f = makeFuture()
197 .then([] { return 42; })
198 .onError([&](eggs_t& /* e */) {
203 EXPECT_EQ(42, f.value());
207 auto f = makeFuture()
208 .then([] { return 42; })
209 .onError([&](eggs_t& /* e */) {
211 return makeFuture<int>(-1);
214 EXPECT_EQ(42, f.value());
217 // Catch different exception
219 auto f = makeFuture().then([] {
221 }).onError([&](std::runtime_error& /* e */) { flag(); });
223 EXPECT_THROW(f.value(), eggs_t);
227 auto f = makeFuture()
228 .then([] { throw eggs; })
229 .onError([&](std::runtime_error& /* e */) {
234 EXPECT_THROW(f.value(), eggs_t);
237 // Returned value propagates
239 auto f = makeFuture().then([]() -> int {
241 }).onError([&](eggs_t& /* e */) { return 42; });
242 EXPECT_EQ(42, f.value());
245 // Returned future propagates
247 auto f = makeFuture().then([]() -> int {
249 }).onError([&](eggs_t& /* e */) { return makeFuture<int>(42); });
250 EXPECT_EQ(42, f.value());
255 auto f = makeFuture()
256 .then([]() -> int { throw eggs; })
257 .onError([&] (eggs_t& e) -> int { throw e; });
258 EXPECT_THROW(f.value(), eggs_t);
262 auto f = makeFuture()
263 .then([]() -> int { throw eggs; })
264 .onError([&] (eggs_t& e) -> Future<int> { throw e; });
265 EXPECT_THROW(f.value(), eggs_t);
268 // exception_wrapper, return Future<T>
270 auto f = makeFuture()
271 .then([] { throw eggs; })
272 .onError([&](exception_wrapper /* e */) {
277 EXPECT_NO_THROW(f.value());
280 // exception_wrapper, return Future<T> but throw
282 auto f = makeFuture()
286 .onError([&](exception_wrapper /* e */) -> Future<int> {
291 EXPECT_THROW(f.value(), eggs_t);
294 // exception_wrapper, return T
296 auto f = makeFuture()
300 .onError([&](exception_wrapper /* e */) {
305 EXPECT_EQ(-1, f.value());
308 // exception_wrapper, return T but throw
310 auto f = makeFuture()
314 .onError([&](exception_wrapper /* e */) -> int {
319 EXPECT_THROW(f.value(), eggs_t);
322 // const exception_wrapper&
324 auto f = makeFuture()
325 .then([] { throw eggs; })
326 .onError([&](const exception_wrapper& /* e */) {
331 EXPECT_NO_THROW(f.value());
336 TEST(Future, special) {
337 EXPECT_FALSE(std::is_copy_constructible<Future<int>>::value);
338 EXPECT_FALSE(std::is_copy_assignable<Future<int>>::value);
339 EXPECT_TRUE(std::is_move_constructible<Future<int>>::value);
340 EXPECT_TRUE(std::is_move_assignable<Future<int>>::value);
344 auto f = makeFuture<std::string>("0")
346 return makeFuture<std::string>("1"); })
347 .then([](Try<std::string>&& t) {
348 return makeFuture(t.value() + ";2"); })
349 .then([](const Try<std::string>&& t) {
350 return makeFuture(t.value() + ";3"); })
351 .then([](Try<std::string>& t) {
352 return makeFuture(t.value() + ";4"); })
353 .then([](const Try<std::string>& t) {
354 return makeFuture(t.value() + ";5"); })
355 .then([](Try<std::string> t) {
356 return makeFuture(t.value() + ";6"); })
357 .then([](const Try<std::string> t) {
358 return makeFuture(t.value() + ";7"); })
359 .then([](std::string&& s) {
360 return makeFuture(s + ";8"); })
361 .then([](const std::string&& s) {
362 return makeFuture(s + ";9"); })
363 .then([](std::string& s) {
364 return makeFuture(s + ";10"); })
365 .then([](const std::string& s) {
366 return makeFuture(s + ";11"); })
367 .then([](std::string s) {
368 return makeFuture(s + ";12"); })
369 .then([](const std::string s) {
370 return makeFuture(s + ";13"); })
372 EXPECT_EQ(f.value(), "1;2;3;4;5;6;7;8;9;10;11;12;13");
375 TEST(Future, thenTry) {
378 makeFuture<int>(42).then([&](Try<int>&& t) {
380 EXPECT_EQ(42, t.value());
382 EXPECT_TRUE(flag); flag = false;
385 .then([](Try<int>&& t) { return t.value(); })
386 .then([&](Try<int>&& t) { flag = true; EXPECT_EQ(42, t.value()); });
387 EXPECT_TRUE(flag); flag = false;
389 makeFuture().then([&](Try<Unit>&& t) { flag = true; t.value(); });
390 EXPECT_TRUE(flag); flag = false;
393 auto f = p.getFuture().then([&](Try<Unit>&& /* t */) { flag = true; });
395 EXPECT_FALSE(f.isReady());
398 EXPECT_TRUE(f.isReady());
401 TEST(Future, thenValue) {
403 makeFuture<int>(42).then([&](int i){
407 EXPECT_TRUE(flag); flag = false;
410 .then([](int i){ return i; })
411 .then([&](int i) { flag = true; EXPECT_EQ(42, i); });
412 EXPECT_TRUE(flag); flag = false;
414 makeFuture().then([&]{
417 EXPECT_TRUE(flag); flag = false;
419 auto f = makeFuture<int>(eggs).then([&](int /* i */) {});
420 EXPECT_THROW(f.value(), eggs_t);
422 f = makeFuture<Unit>(eggs).then([&]{});
423 EXPECT_THROW(f.value(), eggs_t);
426 TEST(Future, thenValueFuture) {
429 .then([](int i){ return makeFuture<int>(std::move(i)); })
430 .then([&](Try<int>&& t) { flag = true; EXPECT_EQ(42, t.value()); });
431 EXPECT_TRUE(flag); flag = false;
433 makeFuture().then([] {
435 }).then([&](Try<Unit>&& /* t */) { flag = true; });
436 EXPECT_TRUE(flag); flag = false;
439 static std::string doWorkStatic(Try<std::string>&& t) {
440 return t.value() + ";static";
443 TEST(Future, thenFunction) {
445 std::string doWork(Try<std::string>&& t) {
446 return t.value() + ";class";
448 static std::string doWorkStatic(Try<std::string>&& t) {
449 return t.value() + ";class-static";
453 auto f = makeFuture<std::string>("start")
455 .then(Worker::doWorkStatic)
456 .then(&Worker::doWork, &w);
458 EXPECT_EQ(f.value(), "start;static;class-static;class");
461 static Future<std::string> doWorkStaticFuture(Try<std::string>&& t) {
462 return makeFuture(t.value() + ";static");
465 TEST(Future, thenFunctionFuture) {
467 Future<std::string> doWorkFuture(Try<std::string>&& t) {
468 return makeFuture(t.value() + ";class");
470 static Future<std::string> doWorkStaticFuture(Try<std::string>&& t) {
471 return makeFuture(t.value() + ";class-static");
475 auto f = makeFuture<std::string>("start")
476 .then(doWorkStaticFuture)
477 .then(Worker::doWorkStaticFuture)
478 .then(&Worker::doWorkFuture, &w);
480 EXPECT_EQ(f.value(), "start;static;class-static;class");
483 TEST(Future, thenStdFunction) {
485 std::function<int()> fn = [](){ return 42; };
486 auto f = makeFuture().then(std::move(fn));
487 EXPECT_EQ(f.value(), 42);
490 std::function<int(int)> fn = [](int i){ return i + 23; };
491 auto f = makeFuture(19).then(std::move(fn));
492 EXPECT_EQ(f.value(), 42);
495 std::function<int(Try<int>&)> fn = [](Try<int>& t){ return t.value() + 2; };
496 auto f = makeFuture(1).then(std::move(fn));
497 EXPECT_EQ(f.value(), 3);
501 std::function<void()> fn = [&flag](){ flag = true; };
502 auto f = makeFuture().then(std::move(fn));
503 EXPECT_TRUE(f.isReady());
508 TEST(Future, thenBind) {
510 return makeFuture("bind");
512 auto b = std::bind(l);
513 auto f = makeFuture().then(std::move(b));
514 EXPECT_EQ(f.value(), "bind");
517 TEST(Future, thenBindTry) {
518 auto l = [](Try<std::string>&& t) {
519 return makeFuture(t.value() + ";bind");
521 auto b = std::bind(l, std::placeholders::_1);
522 auto f = makeFuture<std::string>("start").then(std::move(b));
524 EXPECT_EQ(f.value(), "start;bind");
527 TEST(Future, value) {
528 auto f = makeFuture(std::unique_ptr<int>(new int(42)));
529 auto up = std::move(f.value());
532 EXPECT_THROW(makeFuture<int>(eggs).value(), eggs_t);
535 TEST(Future, isReady) {
537 auto f = p.getFuture();
538 EXPECT_FALSE(f.isReady());
540 EXPECT_TRUE(f.isReady());
543 TEST(Future, futureNotReady) {
545 Future<int> f = p.getFuture();
546 EXPECT_THROW(f.value(), eggs_t);
549 TEST(Future, hasException) {
550 EXPECT_TRUE(makeFuture<int>(eggs).getTry().hasException());
551 EXPECT_FALSE(makeFuture(42).getTry().hasException());
554 TEST(Future, hasValue) {
555 EXPECT_TRUE(makeFuture(42).getTry().hasValue());
556 EXPECT_FALSE(makeFuture<int>(eggs).getTry().hasValue());
559 TEST(Future, makeFuture) {
560 EXPECT_TYPE(makeFuture(42), Future<int>);
561 EXPECT_EQ(42, makeFuture(42).value());
563 EXPECT_TYPE(makeFuture<float>(42), Future<float>);
564 EXPECT_EQ(42, makeFuture<float>(42).value());
566 auto fun = [] { return 42; };
567 EXPECT_TYPE(makeFutureWith(fun), Future<int>);
568 EXPECT_EQ(42, makeFutureWith(fun).value());
570 auto funf = [] { return makeFuture<int>(43); };
571 EXPECT_TYPE(makeFutureWith(funf), Future<int>);
572 EXPECT_EQ(43, makeFutureWith(funf).value());
574 auto failfun = []() -> int { throw eggs; };
575 EXPECT_TYPE(makeFutureWith(failfun), Future<int>);
576 EXPECT_NO_THROW(makeFutureWith(failfun));
577 EXPECT_THROW(makeFutureWith(failfun).value(), eggs_t);
579 auto failfunf = []() -> Future<int> { throw eggs; };
580 EXPECT_TYPE(makeFutureWith(failfunf), Future<int>);
581 EXPECT_NO_THROW(makeFutureWith(failfunf));
582 EXPECT_THROW(makeFutureWith(failfunf).value(), eggs_t);
584 EXPECT_TYPE(makeFuture(), Future<Unit>);
587 TEST(Future, finish) {
588 auto x = std::make_shared<int>(0);
591 auto f = p.getFuture().then([x](Try<int>&& t) { *x = t.value(); });
593 // The callback hasn't executed
596 // The callback has a reference to x
597 EXPECT_EQ(2, x.use_count());
601 // the callback has executed
604 // the callback has been destructed
605 // and has released its reference to x
606 EXPECT_EQ(1, x.use_count());
609 TEST(Future, finishBigLambda) {
610 auto x = std::make_shared<int>(0);
612 // bulk_data, to be captured in the lambda passed to Future::then.
613 // This is meant to force that the lambda can't be stored inside
614 // the Future object.
615 std::array<char, sizeof(detail::Core<int>)> bulk_data = {{0}};
617 // suppress gcc warning about bulk_data not being used
618 EXPECT_EQ(bulk_data[0], 0);
621 auto f = p.getFuture().then([x, bulk_data](Try<int>&& t) {
626 // The callback hasn't executed
629 // The callback has a reference to x
630 EXPECT_EQ(2, x.use_count());
634 // the callback has executed
637 // the callback has been destructed
638 // and has released its reference to x
639 EXPECT_EQ(1, x.use_count());
642 TEST(Future, unwrap) {
646 auto fa = a.getFuture();
647 auto fb = b.getFuture();
652 // do a, then do b, and get the result of a + b.
653 Future<int> f = fa.then([&](Try<int>&& ta) {
654 auto va = ta.value();
656 return fb.then([va, &flag2](Try<int>&& tb) {
658 return va + tb.value();
664 EXPECT_FALSE(f.isReady());
669 EXPECT_FALSE(f.isReady());
674 EXPECT_EQ(7, f.value());
677 TEST(Future, throwCaughtInImmediateThen) {
678 // Neither of these should throw "Promise already satisfied"
680 [=](Try<Unit>&&) -> int { throw std::exception(); });
682 [=](Try<Unit>&&) -> Future<int> { throw std::exception(); });
685 TEST(Future, throwIfFailed) {
686 makeFuture<Unit>(eggs)
687 .then([=](Try<Unit>&& t) {
688 EXPECT_THROW(t.throwIfFailed(), eggs_t);
691 .then([=](Try<Unit>&& t) {
692 EXPECT_NO_THROW(t.throwIfFailed());
695 makeFuture<int>(eggs)
696 .then([=](Try<int>&& t) {
697 EXPECT_THROW(t.throwIfFailed(), eggs_t);
700 .then([=](Try<int>&& t) {
701 EXPECT_NO_THROW(t.throwIfFailed());
705 TEST(Future, getFutureAfterSetValue) {
708 EXPECT_EQ(42, p.getFuture().value());
711 TEST(Future, getFutureAfterSetException) {
713 p.setWith([]() -> void { throw std::logic_error("foo"); });
714 EXPECT_THROW(p.getFuture().value(), std::logic_error);
717 TEST(Future, detachRace) {
719 // This test is designed to detect a race that was in Core::detachOne()
720 // where detached_ was incremented and then tested, and that
721 // allowed a race where both Promise and Future would think they were the
722 // second and both try to delete. This showed up at scale but was very
723 // difficult to reliably repro in a test. As it is, this only fails about
724 // once in every 1,000 executions. Doing this 1,000 times is going to make a
725 // slow test so I won't do that but if it ever fails, take it seriously, and
726 // run the test binary with "--gtest_repeat=10000 --gtest_filter=*detachRace"
727 // (Don't forget to enable ASAN)
728 auto p = std::make_unique<Promise<bool>>();
729 auto f = std::make_unique<Future<bool>>(p->getFuture());
730 folly::Baton<> baton;
740 // Test of handling of a circular dependency. It's never recommended
741 // to have one because of possible memory leaks. Here we test that
742 // we can handle freeing of the Future while it is running.
743 TEST(Future, CircularDependencySharedPtrSelfReset) {
744 Promise<int64_t> promise;
745 auto ptr = std::make_shared<Future<int64_t>>(promise.getFuture());
747 ptr->then([ptr](folly::Try<int64_t>&& /* uid */) mutable {
748 EXPECT_EQ(1, ptr.use_count());
750 // Leaving no references to ourselves.
752 EXPECT_EQ(0, ptr.use_count());
755 EXPECT_EQ(2, ptr.use_count());
762 TEST(Future, Constructor) {
763 auto f1 = []() -> Future<int> { return Future<int>(3); }();
764 EXPECT_EQ(f1.value(), 3);
765 auto f2 = []() -> Future<Unit> { return Future<Unit>(); }();
766 EXPECT_NO_THROW(f2.value());
769 TEST(Future, ImplicitConstructor) {
770 auto f1 = []() -> Future<int> { return 3; }();
771 EXPECT_EQ(f1.value(), 3);
772 // Unfortunately, the C++ standard does not allow the
773 // following implicit conversion to work:
774 //auto f2 = []() -> Future<Unit> { }();
777 TEST(Future, thenDynamic) {
778 // folly::dynamic has a constructor that takes any T, this test makes
779 // sure that we call the then lambda with folly::dynamic and not
780 // Try<folly::dynamic> because that then fails to compile
781 Promise<folly::dynamic> p;
782 Future<folly::dynamic> f = p.getFuture().then(
783 [](const folly::dynamic& d) {
784 return folly::dynamic(d.asInt() + 3);
788 EXPECT_EQ(f.get(), 5);
791 TEST(Future, RequestContext) {
792 class NewThreadExecutor : public Executor {
794 ~NewThreadExecutor() override {
795 std::for_each(v_.begin(), v_.end(), [](std::thread& t){ t.join(); });
797 void add(Func f) override {
798 if (throwsOnAdd_) { throw std::exception(); }
799 v_.emplace_back(std::move(f));
801 void addWithPriority(Func f, int8_t /* prio */) override {
804 uint8_t getNumPriorities() const override { return numPriorities_; }
806 void setHandlesPriorities() { numPriorities_ = 2; }
807 void setThrowsOnAdd() { throwsOnAdd_ = true; }
809 std::vector<std::thread> v_;
810 uint8_t numPriorities_ = 1;
811 bool throwsOnAdd_ = false;
814 struct MyRequestData : RequestData {
815 MyRequestData(bool value = false) : value(value) {}
822 folly::RequestContextScopeGuard rctx;
823 RequestContext::get()->setContextData(
824 "key", std::make_unique<MyRequestData>(true));
825 auto checker = [](int lineno) {
826 return [lineno](Try<int>&& /* t */) {
827 auto d = static_cast<MyRequestData*>(
828 RequestContext::get()->getContextData("key"));
829 EXPECT_TRUE(d && d->value) << "on line " << lineno;
833 makeFuture(1).via(&e).then(checker(__LINE__));
835 e.setHandlesPriorities();
836 makeFuture(2).via(&e).then(checker(__LINE__));
838 p1.getFuture().then(checker(__LINE__));
841 p2.getFuture().via(&e).then(checker(__LINE__));
843 // Assert that no RequestContext is set
844 EXPECT_FALSE(RequestContext::saveContext());
849 TEST(Future, makeFutureNoThrow) {
850 makeFuture().value();
853 TEST(Future, invokeCallbackReturningValueAsRvalue) {
855 int operator()(int x) & {
858 int operator()(int x) const& {
861 int operator()(int x) && {
869 // The callback will be copied when given as lvalue or const ref, and moved
870 // if provided as rvalue. Either way, it should be executed as rvalue.
871 EXPECT_EQ(103, makeFuture<int>(100).then(foo).value());
872 EXPECT_EQ(203, makeFuture<int>(200).then(cfoo).value());
873 EXPECT_EQ(303, makeFuture<int>(300).then(Foo()).value());
876 TEST(Future, invokeCallbackReturningFutureAsRvalue) {
878 Future<int> operator()(int x) & {
881 Future<int> operator()(int x) const& {
884 Future<int> operator()(int x) && {
892 // The callback will be copied when given as lvalue or const ref, and moved
893 // if provided as rvalue. Either way, it should be executed as rvalue.
894 EXPECT_EQ(103, makeFuture<int>(100).then(foo).value());
895 EXPECT_EQ(203, makeFuture<int>(200).then(cfoo).value());
896 EXPECT_EQ(303, makeFuture<int>(300).then(Foo()).value());