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/Baton.h>
18 #include <folly/Executor.h>
19 #include <folly/Memory.h>
20 #include <folly/Unit.h>
21 #include <folly/dynamic.h>
22 #include <folly/futures/Future.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, makeEmpty) {
44 auto f = Future<int>::makeEmpty();
45 EXPECT_THROW(f.isReady(), NoState);
48 TEST(Future, futureDefaultCtor) {
52 TEST(Future, futureToUnit) {
53 Future<Unit> fu = makeFuture(42).unit();
55 EXPECT_TRUE(makeFuture<int>(eggs).unit().hasException());
58 TEST(Future, voidFutureToUnit) {
59 Future<Unit> fu = makeFuture().unit();
61 EXPECT_TRUE(makeFuture<Unit>(eggs).unit().hasException());
64 TEST(Future, unitFutureToUnitIdentity) {
65 Future<Unit> fu = makeFuture(Unit{}).unit();
67 EXPECT_TRUE(makeFuture<Unit>(eggs).unit().hasException());
70 TEST(Future, toUnitWhileInProgress) {
72 Future<Unit> fu = p.getFuture().unit();
73 EXPECT_FALSE(fu.isReady());
75 EXPECT_TRUE(fu.isReady());
78 TEST(Future, makeFutureWithUnit) {
80 Future<Unit> fu = makeFutureWith([&] { count++; });
85 Future<int> onErrorHelperEggs(const eggs_t&) {
86 return makeFuture(10);
88 Future<int> onErrorHelperGeneric(const std::exception&) {
89 return makeFuture(20);
93 TEST(Future, onError) {
95 auto flag = [&]{ theFlag = true; };
96 #define EXPECT_FLAG() \
98 EXPECT_TRUE(theFlag); \
102 #define EXPECT_NO_FLAG() \
104 EXPECT_FALSE(theFlag); \
110 auto f = makeFuture().then([] {
112 }).onError([&](eggs_t& /* e */) { flag(); });
114 EXPECT_NO_THROW(f.value());
118 auto f = makeFuture()
119 .then([] { throw eggs; })
120 .onError([&](eggs_t& /* e */) {
125 EXPECT_NO_THROW(f.value());
130 auto f = makeFuture().then([] {
132 }).onError([&](eggs_t /* e */) { flag(); });
134 EXPECT_NO_THROW(f.value());
138 auto f = makeFuture()
139 .then([] { throw eggs; })
140 .onError([&](eggs_t /* e */) {
145 EXPECT_NO_THROW(f.value());
150 auto f = makeFuture().then([] {
152 }).onError([&](std::exception& /* e */) { flag(); });
154 EXPECT_NO_THROW(f.value());
158 auto f = makeFuture()
159 .then([] { throw eggs; })
160 .onError([&](std::exception& /* e */) {
165 EXPECT_NO_THROW(f.value());
170 auto f = makeFuture().then([] {
172 }).onError([&](int /* e */) { flag(); });
174 EXPECT_NO_THROW(f.value());
178 auto f = makeFuture()
179 .then([] { throw - 1; })
180 .onError([&](int /* e */) {
185 EXPECT_NO_THROW(f.value());
190 auto f = makeFuture().then([] {
192 }).onError([&](eggs_t& /* e */) mutable { flag(); });
194 EXPECT_NO_THROW(f.value());
198 auto f = makeFuture()
199 .then([] { throw eggs; })
200 .onError([&](eggs_t& /* e */) mutable {
205 EXPECT_NO_THROW(f.value());
210 auto f = makeFuture()
211 .then([]() -> int { throw eggs; })
212 .onError(onErrorHelperEggs)
213 .onError(onErrorHelperGeneric);
214 EXPECT_EQ(10, f.value());
217 auto f = makeFuture()
218 .then([]() -> int { throw std::runtime_error("test"); })
219 .onError(onErrorHelperEggs)
220 .onError(onErrorHelperGeneric);
221 EXPECT_EQ(20, f.value());
224 auto f = makeFuture()
225 .then([]() -> int { throw std::runtime_error("test"); })
226 .onError(onErrorHelperEggs);
227 EXPECT_THROW(f.value(), std::runtime_error);
232 auto f = makeFuture()
233 .then([] { return 42; })
234 .onError([&](eggs_t& /* e */) {
239 EXPECT_EQ(42, f.value());
243 auto f = makeFuture()
244 .then([] { return 42; })
245 .onError([&](eggs_t& /* e */) {
247 return makeFuture<int>(-1);
250 EXPECT_EQ(42, f.value());
253 // Catch different exception
255 auto f = makeFuture().then([] {
257 }).onError([&](std::runtime_error& /* e */) { flag(); });
259 EXPECT_THROW(f.value(), eggs_t);
263 auto f = makeFuture()
264 .then([] { throw eggs; })
265 .onError([&](std::runtime_error& /* e */) {
270 EXPECT_THROW(f.value(), eggs_t);
273 // Returned value propagates
275 auto f = makeFuture().then([]() -> int {
277 }).onError([&](eggs_t& /* e */) { return 42; });
278 EXPECT_EQ(42, f.value());
281 // Returned future propagates
283 auto f = makeFuture().then([]() -> int {
285 }).onError([&](eggs_t& /* e */) { return makeFuture<int>(42); });
286 EXPECT_EQ(42, f.value());
291 auto f = makeFuture()
292 .then([]() -> int { throw eggs; })
293 .onError([&] (eggs_t& e) -> int { throw e; });
294 EXPECT_THROW(f.value(), eggs_t);
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);
304 // exception_wrapper, return Future<T>
306 auto f = makeFuture()
307 .then([] { throw eggs; })
308 .onError([&](exception_wrapper /* e */) {
313 EXPECT_NO_THROW(f.value());
316 // exception_wrapper, return Future<T> but throw
318 auto f = makeFuture()
322 .onError([&](exception_wrapper /* e */) -> Future<int> {
327 EXPECT_THROW(f.value(), eggs_t);
330 // exception_wrapper, return T
332 auto f = makeFuture()
336 .onError([&](exception_wrapper /* e */) {
341 EXPECT_EQ(-1, f.value());
344 // exception_wrapper, return T but throw
346 auto f = makeFuture()
350 .onError([&](exception_wrapper /* e */) -> int {
355 EXPECT_THROW(f.value(), eggs_t);
358 // const exception_wrapper&
360 auto f = makeFuture()
361 .then([] { throw eggs; })
362 .onError([&](const exception_wrapper& /* e */) {
367 EXPECT_NO_THROW(f.value());
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);
380 auto f = makeFuture<std::string>("0")
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"); })
408 EXPECT_EQ(f.value(), "1;2;3;4;5;6;7;8;9;10;11;12;13");
411 TEST(Future, thenTry) {
414 makeFuture<int>(42).then([&](Try<int>&& t) {
416 EXPECT_EQ(42, t.value());
418 EXPECT_TRUE(flag); flag = false;
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;
425 makeFuture().then([&](Try<Unit>&& t) { flag = true; t.value(); });
426 EXPECT_TRUE(flag); flag = false;
429 auto f = p.getFuture().then([&](Try<Unit>&& /* t */) { flag = true; });
431 EXPECT_FALSE(f.isReady());
434 EXPECT_TRUE(f.isReady());
437 TEST(Future, thenValue) {
439 makeFuture<int>(42).then([&](int i){
443 EXPECT_TRUE(flag); flag = false;
446 .then([](int i){ return i; })
447 .then([&](int i) { flag = true; EXPECT_EQ(42, i); });
448 EXPECT_TRUE(flag); flag = false;
450 makeFuture().then([&]{
453 EXPECT_TRUE(flag); flag = false;
455 auto f = makeFuture<int>(eggs).then([&](int /* i */) {});
456 EXPECT_THROW(f.value(), eggs_t);
458 f = makeFuture<Unit>(eggs).then([&]{});
459 EXPECT_THROW(f.value(), eggs_t);
462 TEST(Future, thenValueFuture) {
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;
469 makeFuture().then([] {
471 }).then([&](Try<Unit>&& /* t */) { flag = true; });
472 EXPECT_TRUE(flag); flag = false;
475 static std::string doWorkStatic(Try<std::string>&& t) {
476 return t.value() + ";static";
479 TEST(Future, thenFunction) {
481 std::string doWork(Try<std::string>&& t) {
482 return t.value() + ";class";
484 static std::string doWorkStatic(Try<std::string>&& t) {
485 return t.value() + ";class-static";
489 auto f = makeFuture<std::string>("start")
491 .then(Worker::doWorkStatic)
492 .then(&Worker::doWork, &w);
494 EXPECT_EQ(f.value(), "start;static;class-static;class");
497 static Future<std::string> doWorkStaticFuture(Try<std::string>&& t) {
498 return makeFuture(t.value() + ";static");
501 TEST(Future, thenFunctionFuture) {
503 Future<std::string> doWorkFuture(Try<std::string>&& t) {
504 return makeFuture(t.value() + ";class");
506 static Future<std::string> doWorkStaticFuture(Try<std::string>&& t) {
507 return makeFuture(t.value() + ";class-static");
511 auto f = makeFuture<std::string>("start")
512 .then(doWorkStaticFuture)
513 .then(Worker::doWorkStaticFuture)
514 .then(&Worker::doWorkFuture, &w);
516 EXPECT_EQ(f.value(), "start;static;class-static;class");
519 TEST(Future, thenStdFunction) {
521 std::function<int()> fn = [](){ return 42; };
522 auto f = makeFuture().then(std::move(fn));
523 EXPECT_EQ(f.value(), 42);
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);
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);
537 std::function<void()> fn = [&flag](){ flag = true; };
538 auto f = makeFuture().then(std::move(fn));
539 EXPECT_TRUE(f.isReady());
544 TEST(Future, thenBind) {
546 return makeFuture("bind");
548 auto b = std::bind(l);
549 auto f = makeFuture().then(std::move(b));
550 EXPECT_EQ(f.value(), "bind");
553 TEST(Future, thenBindTry) {
554 auto l = [](Try<std::string>&& t) {
555 return makeFuture(t.value() + ";bind");
557 auto b = std::bind(l, std::placeholders::_1);
558 auto f = makeFuture<std::string>("start").then(std::move(b));
560 EXPECT_EQ(f.value(), "start;bind");
563 TEST(Future, value) {
564 auto f = makeFuture(std::unique_ptr<int>(new int(42)));
565 auto up = std::move(f.value());
568 EXPECT_THROW(makeFuture<int>(eggs).value(), eggs_t);
571 TEST(Future, isReady) {
573 auto f = p.getFuture();
574 EXPECT_FALSE(f.isReady());
576 EXPECT_TRUE(f.isReady());
579 TEST(Future, futureNotReady) {
581 Future<int> f = p.getFuture();
582 EXPECT_THROW(f.value(), eggs_t);
585 TEST(Future, hasException) {
586 EXPECT_TRUE(makeFuture<int>(eggs).getTry().hasException());
587 EXPECT_FALSE(makeFuture(42).getTry().hasException());
590 TEST(Future, hasValue) {
591 EXPECT_TRUE(makeFuture(42).getTry().hasValue());
592 EXPECT_FALSE(makeFuture<int>(eggs).getTry().hasValue());
595 TEST(Future, makeFuture) {
596 EXPECT_TYPE(makeFuture(42), Future<int>);
597 EXPECT_EQ(42, makeFuture(42).value());
599 EXPECT_TYPE(makeFuture<float>(42), Future<float>);
600 EXPECT_EQ(42, makeFuture<float>(42).value());
602 auto fun = [] { return 42; };
603 EXPECT_TYPE(makeFutureWith(fun), Future<int>);
604 EXPECT_EQ(42, makeFutureWith(fun).value());
606 auto funf = [] { return makeFuture<int>(43); };
607 EXPECT_TYPE(makeFutureWith(funf), Future<int>);
608 EXPECT_EQ(43, makeFutureWith(funf).value());
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);
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);
620 EXPECT_TYPE(makeFuture(), Future<Unit>);
623 TEST(Future, finish) {
624 auto x = std::make_shared<int>(0);
627 auto f = p.getFuture().then([x](Try<int>&& t) { *x = t.value(); });
629 // The callback hasn't executed
632 // The callback has a reference to x
633 EXPECT_EQ(2, x.use_count());
637 // the callback has executed
640 // the callback has been destructed
641 // and has released its reference to x
642 EXPECT_EQ(1, x.use_count());
645 TEST(Future, finishBigLambda) {
646 auto x = std::make_shared<int>(0);
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}};
653 // suppress gcc warning about bulk_data not being used
654 EXPECT_EQ(bulk_data[0], 0);
657 auto f = p.getFuture().then([x, bulk_data](Try<int>&& t) {
662 // The callback hasn't executed
665 // The callback has a reference to x
666 EXPECT_EQ(2, x.use_count());
670 // the callback has executed
673 // the callback has been destructed
674 // and has released its reference to x
675 EXPECT_EQ(1, x.use_count());
678 TEST(Future, unwrap) {
682 auto fa = a.getFuture();
683 auto fb = b.getFuture();
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();
692 return fb.then([va, &flag2](Try<int>&& tb) {
694 return va + tb.value();
700 EXPECT_FALSE(f.isReady());
705 EXPECT_FALSE(f.isReady());
710 EXPECT_EQ(7, f.value());
713 TEST(Future, throwCaughtInImmediateThen) {
714 // Neither of these should throw "Promise already satisfied"
716 [=](Try<Unit>&&) -> int { throw std::exception(); });
718 [=](Try<Unit>&&) -> Future<int> { throw std::exception(); });
721 TEST(Future, throwIfFailed) {
722 makeFuture<Unit>(eggs)
723 .then([=](Try<Unit>&& t) {
724 EXPECT_THROW(t.throwIfFailed(), eggs_t);
727 .then([=](Try<Unit>&& t) {
728 EXPECT_NO_THROW(t.throwIfFailed());
731 makeFuture<int>(eggs)
732 .then([=](Try<int>&& t) {
733 EXPECT_THROW(t.throwIfFailed(), eggs_t);
736 .then([=](Try<int>&& t) {
737 EXPECT_NO_THROW(t.throwIfFailed());
741 TEST(Future, getFutureAfterSetValue) {
744 EXPECT_EQ(42, p.getFuture().value());
747 TEST(Future, getFutureAfterSetException) {
749 p.setWith([]() -> void { throw std::logic_error("foo"); });
750 EXPECT_THROW(p.getFuture().value(), std::logic_error);
753 TEST(Future, detachRace) {
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;
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());
783 ptr->then([ptr](folly::Try<int64_t>&& /* uid */) mutable {
784 EXPECT_EQ(1, ptr.use_count());
786 // Leaving no references to ourselves.
788 EXPECT_EQ(0, ptr.use_count());
791 EXPECT_EQ(2, ptr.use_count());
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());
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> { }();
813 TEST(Future, InPlaceConstructor) {
814 auto f = Future<std::pair<int, double>>(in_place, 5, 3.2);
815 EXPECT_EQ(5, f.value().first);
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);
829 EXPECT_EQ(f.get(), 5);
832 TEST(Future, RequestContext) {
833 class NewThreadExecutor : public Executor {
835 ~NewThreadExecutor() override {
836 std::for_each(v_.begin(), v_.end(), [](std::thread& t){ t.join(); });
838 void add(Func f) override {
839 if (throwsOnAdd_) { throw std::exception(); }
840 v_.emplace_back(std::move(f));
842 void addWithPriority(Func f, int8_t /* prio */) override {
845 uint8_t getNumPriorities() const override { return numPriorities_; }
847 void setHandlesPriorities() { numPriorities_ = 2; }
848 void setThrowsOnAdd() { throwsOnAdd_ = true; }
850 std::vector<std::thread> v_;
851 uint8_t numPriorities_ = 1;
852 bool throwsOnAdd_ = false;
855 struct MyRequestData : RequestData {
856 MyRequestData(bool value = false) : value(value) {}
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;
874 makeFuture(1).via(&e).then(checker(__LINE__));
876 e.setHandlesPriorities();
877 makeFuture(2).via(&e).then(checker(__LINE__));
879 p1.getFuture().then(checker(__LINE__));
882 p2.getFuture().via(&e).then(checker(__LINE__));
884 // Assert that no RequestContext is set
885 EXPECT_FALSE(RequestContext::saveContext());
890 TEST(Future, makeFutureNoThrow) {
891 makeFuture().value();
894 TEST(Future, invokeCallbackReturningValueAsRvalue) {
896 int operator()(int x) & {
899 int operator()(int x) const& {
902 int operator()(int x) && {
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());
917 TEST(Future, invokeCallbackReturningFutureAsRvalue) {
919 Future<int> operator()(int x) & {
922 Future<int> operator()(int x) const& {
925 Future<int> operator()(int x) && {
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());