2 * Copyright 2016 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>
24 #include <folly/portability/Unistd.h>
32 #include <type_traits>
34 using namespace folly;
36 #define EXPECT_TYPE(x, T) \
37 EXPECT_TRUE((std::is_same<decltype(x), T>::value))
39 typedef FutureException eggs_t;
40 static eggs_t eggs("eggs");
44 TEST(Future, futureDefaultCtor) {
48 TEST(Future, futureToUnit) {
49 Future<Unit> fu = makeFuture(42).unit();
51 EXPECT_TRUE(makeFuture<int>(eggs).unit().hasException());
54 TEST(Future, voidFutureToUnit) {
55 Future<Unit> fu = makeFuture().unit();
57 EXPECT_TRUE(makeFuture<Unit>(eggs).unit().hasException());
60 TEST(Future, unitFutureToUnitIdentity) {
61 Future<Unit> fu = makeFuture(Unit{}).unit();
63 EXPECT_TRUE(makeFuture<Unit>(eggs).unit().hasException());
66 TEST(Future, toUnitWhileInProgress) {
68 Future<Unit> fu = p.getFuture().unit();
69 EXPECT_FALSE(fu.isReady());
71 EXPECT_TRUE(fu.isReady());
74 TEST(Future, makeFutureWithUnit) {
76 Future<Unit> fu = makeFutureWith([&] { count++; });
80 TEST(Future, onError) {
82 auto flag = [&]{ theFlag = true; };
83 #define EXPECT_FLAG() \
85 EXPECT_TRUE(theFlag); \
89 #define EXPECT_NO_FLAG() \
91 EXPECT_FALSE(theFlag); \
97 auto f = makeFuture().then([] {
99 }).onError([&](eggs_t& /* e */) { flag(); });
101 EXPECT_NO_THROW(f.value());
105 auto f = makeFuture()
106 .then([] { throw eggs; })
107 .onError([&](eggs_t& /* e */) {
112 EXPECT_NO_THROW(f.value());
117 auto f = makeFuture().then([] {
119 }).onError([&](eggs_t /* e */) { flag(); });
121 EXPECT_NO_THROW(f.value());
125 auto f = makeFuture()
126 .then([] { throw eggs; })
127 .onError([&](eggs_t /* e */) {
132 EXPECT_NO_THROW(f.value());
137 auto f = makeFuture().then([] {
139 }).onError([&](std::exception& /* e */) { flag(); });
141 EXPECT_NO_THROW(f.value());
145 auto f = makeFuture()
146 .then([] { throw eggs; })
147 .onError([&](std::exception& /* e */) {
152 EXPECT_NO_THROW(f.value());
157 auto f = makeFuture().then([] {
159 }).onError([&](int /* e */) { flag(); });
161 EXPECT_NO_THROW(f.value());
165 auto f = makeFuture()
166 .then([] { throw - 1; })
167 .onError([&](int /* e */) {
172 EXPECT_NO_THROW(f.value());
177 auto f = makeFuture().then([] {
179 }).onError([&](eggs_t& /* e */) mutable { flag(); });
181 EXPECT_NO_THROW(f.value());
185 auto f = makeFuture()
186 .then([] { throw eggs; })
187 .onError([&](eggs_t& /* e */) mutable {
192 EXPECT_NO_THROW(f.value());
197 auto f = makeFuture()
198 .then([] { return 42; })
199 .onError([&](eggs_t& /* e */) {
204 EXPECT_EQ(42, f.value());
208 auto f = makeFuture()
209 .then([] { return 42; })
210 .onError([&](eggs_t& /* e */) {
212 return makeFuture<int>(-1);
215 EXPECT_EQ(42, f.value());
218 // Catch different exception
220 auto f = makeFuture().then([] {
222 }).onError([&](std::runtime_error& /* e */) { flag(); });
224 EXPECT_THROW(f.value(), eggs_t);
228 auto f = makeFuture()
229 .then([] { throw eggs; })
230 .onError([&](std::runtime_error& /* e */) {
235 EXPECT_THROW(f.value(), eggs_t);
238 // Returned value propagates
240 auto f = makeFuture().then([]() -> int {
242 }).onError([&](eggs_t& /* e */) { return 42; });
243 EXPECT_EQ(42, f.value());
246 // Returned future propagates
248 auto f = makeFuture().then([]() -> int {
250 }).onError([&](eggs_t& /* e */) { return makeFuture<int>(42); });
251 EXPECT_EQ(42, f.value());
256 auto f = makeFuture()
257 .then([]() -> int { throw eggs; })
258 .onError([&] (eggs_t& e) -> int { throw e; });
259 EXPECT_THROW(f.value(), eggs_t);
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);
269 // exception_wrapper, return Future<T>
271 auto f = makeFuture()
272 .then([] { throw eggs; })
273 .onError([&](exception_wrapper /* e */) {
278 EXPECT_NO_THROW(f.value());
281 // exception_wrapper, return Future<T> but throw
283 auto f = makeFuture()
287 .onError([&](exception_wrapper /* e */) -> Future<int> {
292 EXPECT_THROW(f.value(), eggs_t);
295 // exception_wrapper, return T
297 auto f = makeFuture()
301 .onError([&](exception_wrapper /* e */) {
306 EXPECT_EQ(-1, f.value());
309 // exception_wrapper, return T but throw
311 auto f = makeFuture()
315 .onError([&](exception_wrapper /* e */) -> int {
320 EXPECT_THROW(f.value(), eggs_t);
323 // const exception_wrapper&
325 auto f = makeFuture()
326 .then([] { throw eggs; })
327 .onError([&](const exception_wrapper& /* e */) {
332 EXPECT_NO_THROW(f.value());
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);
345 auto f = makeFuture<std::string>("0")
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"); })
373 EXPECT_EQ(f.value(), "1;2;3;4;5;6;7;8;9;10;11;12;13");
376 TEST(Future, thenTry) {
379 makeFuture<int>(42).then([&](Try<int>&& t) {
381 EXPECT_EQ(42, t.value());
383 EXPECT_TRUE(flag); flag = false;
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;
390 makeFuture().then([&](Try<Unit>&& t) { flag = true; t.value(); });
391 EXPECT_TRUE(flag); flag = false;
394 auto f = p.getFuture().then([&](Try<Unit>&& /* t */) { flag = true; });
396 EXPECT_FALSE(f.isReady());
399 EXPECT_TRUE(f.isReady());
402 TEST(Future, thenValue) {
404 makeFuture<int>(42).then([&](int i){
408 EXPECT_TRUE(flag); flag = false;
411 .then([](int i){ return i; })
412 .then([&](int i) { flag = true; EXPECT_EQ(42, i); });
413 EXPECT_TRUE(flag); flag = false;
415 makeFuture().then([&]{
418 EXPECT_TRUE(flag); flag = false;
420 auto f = makeFuture<int>(eggs).then([&](int /* i */) {});
421 EXPECT_THROW(f.value(), eggs_t);
423 f = makeFuture<Unit>(eggs).then([&]{});
424 EXPECT_THROW(f.value(), eggs_t);
427 TEST(Future, thenValueFuture) {
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;
434 makeFuture().then([] {
436 }).then([&](Try<Unit>&& /* t */) { flag = true; });
437 EXPECT_TRUE(flag); flag = false;
440 static std::string doWorkStatic(Try<std::string>&& t) {
441 return t.value() + ";static";
444 TEST(Future, thenFunction) {
446 std::string doWork(Try<std::string>&& t) {
447 return t.value() + ";class";
449 static std::string doWorkStatic(Try<std::string>&& t) {
450 return t.value() + ";class-static";
454 auto f = makeFuture<std::string>("start")
456 .then(Worker::doWorkStatic)
457 .then(&Worker::doWork, &w);
459 EXPECT_EQ(f.value(), "start;static;class-static;class");
462 static Future<std::string> doWorkStaticFuture(Try<std::string>&& t) {
463 return makeFuture(t.value() + ";static");
466 TEST(Future, thenFunctionFuture) {
468 Future<std::string> doWorkFuture(Try<std::string>&& t) {
469 return makeFuture(t.value() + ";class");
471 static Future<std::string> doWorkStaticFuture(Try<std::string>&& t) {
472 return makeFuture(t.value() + ";class-static");
476 auto f = makeFuture<std::string>("start")
477 .then(doWorkStaticFuture)
478 .then(Worker::doWorkStaticFuture)
479 .then(&Worker::doWorkFuture, &w);
481 EXPECT_EQ(f.value(), "start;static;class-static;class");
484 TEST(Future, thenStdFunction) {
486 std::function<int()> fn = [](){ return 42; };
487 auto f = makeFuture().then(std::move(fn));
488 EXPECT_EQ(f.value(), 42);
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);
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);
502 std::function<void()> fn = [&flag](){ flag = true; };
503 auto f = makeFuture().then(std::move(fn));
504 EXPECT_TRUE(f.isReady());
509 TEST(Future, thenBind) {
511 return makeFuture("bind");
513 auto b = std::bind(l);
514 auto f = makeFuture().then(std::move(b));
515 EXPECT_EQ(f.value(), "bind");
518 TEST(Future, thenBindTry) {
519 auto l = [](Try<std::string>&& t) {
520 return makeFuture(t.value() + ";bind");
522 auto b = std::bind(l, std::placeholders::_1);
523 auto f = makeFuture<std::string>("start").then(std::move(b));
525 EXPECT_EQ(f.value(), "start;bind");
528 TEST(Future, value) {
529 auto f = makeFuture(std::unique_ptr<int>(new int(42)));
530 auto up = std::move(f.value());
533 EXPECT_THROW(makeFuture<int>(eggs).value(), eggs_t);
536 TEST(Future, isReady) {
538 auto f = p.getFuture();
539 EXPECT_FALSE(f.isReady());
541 EXPECT_TRUE(f.isReady());
544 TEST(Future, futureNotReady) {
546 Future<int> f = p.getFuture();
547 EXPECT_THROW(f.value(), eggs_t);
550 TEST(Future, hasException) {
551 EXPECT_TRUE(makeFuture<int>(eggs).getTry().hasException());
552 EXPECT_FALSE(makeFuture(42).getTry().hasException());
555 TEST(Future, hasValue) {
556 EXPECT_TRUE(makeFuture(42).getTry().hasValue());
557 EXPECT_FALSE(makeFuture<int>(eggs).getTry().hasValue());
560 TEST(Future, makeFuture) {
561 EXPECT_TYPE(makeFuture(42), Future<int>);
562 EXPECT_EQ(42, makeFuture(42).value());
564 EXPECT_TYPE(makeFuture<float>(42), Future<float>);
565 EXPECT_EQ(42, makeFuture<float>(42).value());
567 auto fun = [] { return 42; };
568 EXPECT_TYPE(makeFutureWith(fun), Future<int>);
569 EXPECT_EQ(42, makeFutureWith(fun).value());
571 auto funf = [] { return makeFuture<int>(43); };
572 EXPECT_TYPE(makeFutureWith(funf), Future<int>);
573 EXPECT_EQ(43, makeFutureWith(funf).value());
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);
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);
585 EXPECT_TYPE(makeFuture(), Future<Unit>);
588 TEST(Future, finish) {
589 auto x = std::make_shared<int>(0);
592 auto f = p.getFuture().then([x](Try<int>&& t) { *x = t.value(); });
594 // The callback hasn't executed
597 // The callback has a reference to x
598 EXPECT_EQ(2, x.use_count());
602 // the callback has executed
605 // the callback has been destructed
606 // and has released its reference to x
607 EXPECT_EQ(1, x.use_count());
610 TEST(Future, finishBigLambda) {
611 auto x = std::make_shared<int>(0);
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}};
618 // suppress gcc warning about bulk_data not being used
619 EXPECT_EQ(bulk_data[0], 0);
622 auto f = p.getFuture().then([x, bulk_data](Try<int>&& t) { *x = t.value(); });
624 // The callback hasn't executed
627 // The callback has a reference to x
628 EXPECT_EQ(2, x.use_count());
632 // the callback has executed
635 // the callback has been destructed
636 // and has released its reference to x
637 EXPECT_EQ(1, x.use_count());
640 TEST(Future, unwrap) {
644 auto fa = a.getFuture();
645 auto fb = b.getFuture();
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();
654 return fb.then([va, &flag2](Try<int>&& tb) {
656 return va + tb.value();
662 EXPECT_FALSE(f.isReady());
667 EXPECT_FALSE(f.isReady());
672 EXPECT_EQ(7, f.value());
675 TEST(Future, throwCaughtInImmediateThen) {
676 // Neither of these should throw "Promise already satisfied"
678 [=](Try<Unit>&&) -> int { throw std::exception(); });
680 [=](Try<Unit>&&) -> Future<int> { throw std::exception(); });
683 TEST(Future, throwIfFailed) {
684 makeFuture<Unit>(eggs)
685 .then([=](Try<Unit>&& t) {
686 EXPECT_THROW(t.throwIfFailed(), eggs_t);
689 .then([=](Try<Unit>&& t) {
690 EXPECT_NO_THROW(t.throwIfFailed());
693 makeFuture<int>(eggs)
694 .then([=](Try<int>&& t) {
695 EXPECT_THROW(t.throwIfFailed(), eggs_t);
698 .then([=](Try<int>&& t) {
699 EXPECT_NO_THROW(t.throwIfFailed());
703 TEST(Future, getFutureAfterSetValue) {
706 EXPECT_EQ(42, p.getFuture().value());
709 TEST(Future, getFutureAfterSetException) {
711 p.setWith([]() -> void { throw std::logic_error("foo"); });
712 EXPECT_THROW(p.getFuture().value(), std::logic_error);
715 TEST(Future, detachRace) {
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;
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());
745 ptr->then([ptr](folly::Try<int64_t>&& /* uid */) mutable {
746 EXPECT_EQ(1, ptr.use_count());
748 // Leaving no references to ourselves.
750 EXPECT_EQ(0, ptr.use_count());
753 EXPECT_EQ(2, ptr.use_count());
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());
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> { }();
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);
786 EXPECT_EQ(f.get(), 5);
789 TEST(Future, RequestContext) {
790 class NewThreadExecutor : public Executor {
792 ~NewThreadExecutor() override {
793 std::for_each(v_.begin(), v_.end(), [](std::thread& t){ t.join(); });
795 void add(Func f) override {
796 if (throwsOnAdd_) { throw std::exception(); }
797 v_.emplace_back(std::move(f));
799 void addWithPriority(Func f, int8_t /* prio */) override {
802 uint8_t getNumPriorities() const override { return numPriorities_; }
804 void setHandlesPriorities() { numPriorities_ = 2; }
805 void setThrowsOnAdd() { throwsOnAdd_ = true; }
807 std::vector<std::thread> v_;
808 uint8_t numPriorities_ = 1;
809 bool throwsOnAdd_ = false;
812 struct MyRequestData : RequestData {
813 MyRequestData(bool value = false) : value(value) {}
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;
831 makeFuture(1).via(&e).then(checker(__LINE__));
833 e.setHandlesPriorities();
834 makeFuture(2).via(&e).then(checker(__LINE__));
836 p1.getFuture().then(checker(__LINE__));
839 p2.getFuture().via(&e).then(checker(__LINE__));
841 // Assert that no RequestContext is set
842 EXPECT_FALSE(RequestContext::saveContext());
847 TEST(Future, makeFutureNoThrow) {
848 makeFuture().value();