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) { *x = t.value(); });
623 // The callback hasn't executed
626 // The callback has a reference to x
627 EXPECT_EQ(2, x.use_count());
631 // the callback has executed
634 // the callback has been destructed
635 // and has released its reference to x
636 EXPECT_EQ(1, x.use_count());
639 TEST(Future, unwrap) {
643 auto fa = a.getFuture();
644 auto fb = b.getFuture();
649 // do a, then do b, and get the result of a + b.
650 Future<int> f = fa.then([&](Try<int>&& ta) {
651 auto va = ta.value();
653 return fb.then([va, &flag2](Try<int>&& tb) {
655 return va + tb.value();
661 EXPECT_FALSE(f.isReady());
666 EXPECT_FALSE(f.isReady());
671 EXPECT_EQ(7, f.value());
674 TEST(Future, throwCaughtInImmediateThen) {
675 // Neither of these should throw "Promise already satisfied"
677 [=](Try<Unit>&&) -> int { throw std::exception(); });
679 [=](Try<Unit>&&) -> Future<int> { throw std::exception(); });
682 TEST(Future, throwIfFailed) {
683 makeFuture<Unit>(eggs)
684 .then([=](Try<Unit>&& t) {
685 EXPECT_THROW(t.throwIfFailed(), eggs_t);
688 .then([=](Try<Unit>&& t) {
689 EXPECT_NO_THROW(t.throwIfFailed());
692 makeFuture<int>(eggs)
693 .then([=](Try<int>&& t) {
694 EXPECT_THROW(t.throwIfFailed(), eggs_t);
697 .then([=](Try<int>&& t) {
698 EXPECT_NO_THROW(t.throwIfFailed());
702 TEST(Future, getFutureAfterSetValue) {
705 EXPECT_EQ(42, p.getFuture().value());
708 TEST(Future, getFutureAfterSetException) {
710 p.setWith([]() -> void { throw std::logic_error("foo"); });
711 EXPECT_THROW(p.getFuture().value(), std::logic_error);
714 TEST(Future, detachRace) {
716 // This test is designed to detect a race that was in Core::detachOne()
717 // where detached_ was incremented and then tested, and that
718 // allowed a race where both Promise and Future would think they were the
719 // second and both try to delete. This showed up at scale but was very
720 // difficult to reliably repro in a test. As it is, this only fails about
721 // once in every 1,000 executions. Doing this 1,000 times is going to make a
722 // slow test so I won't do that but if it ever fails, take it seriously, and
723 // run the test binary with "--gtest_repeat=10000 --gtest_filter=*detachRace"
724 // (Don't forget to enable ASAN)
725 auto p = folly::make_unique<Promise<bool>>();
726 auto f = folly::make_unique<Future<bool>>(p->getFuture());
727 folly::Baton<> baton;
737 // Test of handling of a circular dependency. It's never recommended
738 // to have one because of possible memory leaks. Here we test that
739 // we can handle freeing of the Future while it is running.
740 TEST(Future, CircularDependencySharedPtrSelfReset) {
741 Promise<int64_t> promise;
742 auto ptr = std::make_shared<Future<int64_t>>(promise.getFuture());
744 ptr->then([ptr](folly::Try<int64_t>&& /* uid */) mutable {
745 EXPECT_EQ(1, ptr.use_count());
747 // Leaving no references to ourselves.
749 EXPECT_EQ(0, ptr.use_count());
752 EXPECT_EQ(2, ptr.use_count());
759 TEST(Future, Constructor) {
760 auto f1 = []() -> Future<int> { return Future<int>(3); }();
761 EXPECT_EQ(f1.value(), 3);
762 auto f2 = []() -> Future<Unit> { return Future<Unit>(); }();
763 EXPECT_NO_THROW(f2.value());
766 TEST(Future, ImplicitConstructor) {
767 auto f1 = []() -> Future<int> { return 3; }();
768 EXPECT_EQ(f1.value(), 3);
769 // Unfortunately, the C++ standard does not allow the
770 // following implicit conversion to work:
771 //auto f2 = []() -> Future<Unit> { }();
774 TEST(Future, thenDynamic) {
775 // folly::dynamic has a constructor that takes any T, this test makes
776 // sure that we call the then lambda with folly::dynamic and not
777 // Try<folly::dynamic> because that then fails to compile
778 Promise<folly::dynamic> p;
779 Future<folly::dynamic> f = p.getFuture().then(
780 [](const folly::dynamic& d) {
781 return folly::dynamic(d.asInt() + 3);
785 EXPECT_EQ(f.get(), 5);
788 TEST(Future, RequestContext) {
789 class NewThreadExecutor : public Executor {
791 ~NewThreadExecutor() override {
792 std::for_each(v_.begin(), v_.end(), [](std::thread& t){ t.join(); });
794 void add(Func f) override {
795 if (throwsOnAdd_) { throw std::exception(); }
796 v_.emplace_back(std::move(f));
798 void addWithPriority(Func f, int8_t /* prio */) override {
801 uint8_t getNumPriorities() const override { return numPriorities_; }
803 void setHandlesPriorities() { numPriorities_ = 2; }
804 void setThrowsOnAdd() { throwsOnAdd_ = true; }
806 std::vector<std::thread> v_;
807 uint8_t numPriorities_ = 1;
808 bool throwsOnAdd_ = false;
811 struct MyRequestData : RequestData {
812 MyRequestData(bool value = false) : value(value) {}
819 folly::RequestContextScopeGuard rctx;
820 RequestContext::get()->setContextData(
821 "key", folly::make_unique<MyRequestData>(true));
822 auto checker = [](int lineno) {
823 return [lineno](Try<int>&& /* t */) {
824 auto d = static_cast<MyRequestData*>(
825 RequestContext::get()->getContextData("key"));
826 EXPECT_TRUE(d && d->value) << "on line " << lineno;
830 makeFuture(1).via(&e).then(checker(__LINE__));
832 e.setHandlesPriorities();
833 makeFuture(2).via(&e).then(checker(__LINE__));
835 p1.getFuture().then(checker(__LINE__));
838 p2.getFuture().via(&e).then(checker(__LINE__));
840 // Assert that no RequestContext is set
841 EXPECT_FALSE(RequestContext::saveContext());
846 TEST(Future, makeFutureNoThrow) {
847 makeFuture().value();