2 * Copyright 2015 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 <gtest/gtest.h>
19 #include <folly/futures/Future.h>
20 #include <folly/Memory.h>
21 #include <folly/Executor.h>
22 #include <folly/dynamic.h>
23 #include <folly/Baton.h>
31 #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, onError) {
46 auto flag = [&]{ theFlag = true; };
47 #define EXPECT_FLAG() \
49 EXPECT_TRUE(theFlag); \
53 #define EXPECT_NO_FLAG() \
55 EXPECT_FALSE(theFlag); \
61 auto f = makeFuture().then([] {
63 }).onError([&](eggs_t& /* e */) { flag(); });
65 EXPECT_NO_THROW(f.value());
70 .then([] { throw eggs; })
71 .onError([&](eggs_t& /* e */) {
76 EXPECT_NO_THROW(f.value());
81 auto f = makeFuture().then([] {
83 }).onError([&](eggs_t /* e */) { flag(); });
85 EXPECT_NO_THROW(f.value());
90 .then([] { throw eggs; })
91 .onError([&](eggs_t /* e */) {
96 EXPECT_NO_THROW(f.value());
101 auto f = makeFuture().then([] {
103 }).onError([&](std::exception& /* e */) { flag(); });
105 EXPECT_NO_THROW(f.value());
109 auto f = makeFuture()
110 .then([] { throw eggs; })
111 .onError([&](std::exception& /* e */) {
116 EXPECT_NO_THROW(f.value());
121 auto f = makeFuture().then([] {
123 }).onError([&](int /* e */) { flag(); });
125 EXPECT_NO_THROW(f.value());
129 auto f = makeFuture()
130 .then([] { throw - 1; })
131 .onError([&](int /* e */) {
136 EXPECT_NO_THROW(f.value());
141 auto f = makeFuture().then([] {
143 }).onError([&](eggs_t& /* e */) mutable { flag(); });
145 EXPECT_NO_THROW(f.value());
149 auto f = makeFuture()
150 .then([] { throw eggs; })
151 .onError([&](eggs_t& /* e */) mutable {
156 EXPECT_NO_THROW(f.value());
161 auto f = makeFuture()
162 .then([] { return 42; })
163 .onError([&](eggs_t& /* e */) {
168 EXPECT_EQ(42, f.value());
172 auto f = makeFuture()
173 .then([] { return 42; })
174 .onError([&](eggs_t& /* e */) {
176 return makeFuture<int>(-1);
179 EXPECT_EQ(42, f.value());
182 // Catch different exception
184 auto f = makeFuture().then([] {
186 }).onError([&](std::runtime_error& /* e */) { flag(); });
188 EXPECT_THROW(f.value(), eggs_t);
192 auto f = makeFuture()
193 .then([] { throw eggs; })
194 .onError([&](std::runtime_error& /* e */) {
199 EXPECT_THROW(f.value(), eggs_t);
202 // Returned value propagates
204 auto f = makeFuture().then([] {
207 }).onError([&](eggs_t& /* e */) { return 42; });
208 EXPECT_EQ(42, f.value());
211 // Returned future propagates
213 auto f = makeFuture().then([] {
216 }).onError([&](eggs_t& /* e */) { return makeFuture<int>(42); });
217 EXPECT_EQ(42, f.value());
222 auto f = makeFuture()
223 .then([] { throw eggs; return 0; })
224 .onError([&] (eggs_t& e) { throw e; return -1; });
225 EXPECT_THROW(f.value(), eggs_t);
229 auto f = makeFuture()
230 .then([] { throw eggs; return 0; })
231 .onError([&] (eggs_t& e) { throw e; return makeFuture<int>(-1); });
232 EXPECT_THROW(f.value(), eggs_t);
235 // exception_wrapper, return Future<T>
237 auto f = makeFuture()
238 .then([] { throw eggs; })
239 .onError([&](exception_wrapper /* e */) {
244 EXPECT_NO_THROW(f.value());
247 // exception_wrapper, return Future<T> but throw
249 auto f = makeFuture()
254 .onError([&](exception_wrapper /* e */) {
257 return makeFuture<int>(-1);
260 EXPECT_THROW(f.value(), eggs_t);
263 // exception_wrapper, return T
265 auto f = makeFuture()
270 .onError([&](exception_wrapper /* e */) {
275 EXPECT_EQ(-1, f.value());
278 // exception_wrapper, return T but throw
280 auto f = makeFuture()
285 .onError([&](exception_wrapper /* e */) {
291 EXPECT_THROW(f.value(), eggs_t);
294 // const exception_wrapper&
296 auto f = makeFuture()
297 .then([] { throw eggs; })
298 .onError([&](const exception_wrapper& /* e */) {
303 EXPECT_NO_THROW(f.value());
308 TEST(Future, special) {
309 EXPECT_FALSE(std::is_copy_constructible<Future<int>>::value);
310 EXPECT_FALSE(std::is_copy_assignable<Future<int>>::value);
311 EXPECT_TRUE(std::is_move_constructible<Future<int>>::value);
312 EXPECT_TRUE(std::is_move_assignable<Future<int>>::value);
316 auto f = makeFuture<std::string>("0")
318 return makeFuture<std::string>("1"); })
319 .then([](Try<std::string>&& t) {
320 return makeFuture(t.value() + ";2"); })
321 .then([](const Try<std::string>&& t) {
322 return makeFuture(t.value() + ";3"); })
323 .then([](Try<std::string>& t) {
324 return makeFuture(t.value() + ";4"); })
325 .then([](const Try<std::string>& t) {
326 return makeFuture(t.value() + ";5"); })
327 .then([](Try<std::string> t) {
328 return makeFuture(t.value() + ";6"); })
329 .then([](const Try<std::string> t) {
330 return makeFuture(t.value() + ";7"); })
331 .then([](std::string&& s) {
332 return makeFuture(s + ";8"); })
333 .then([](const std::string&& s) {
334 return makeFuture(s + ";9"); })
335 .then([](std::string& s) {
336 return makeFuture(s + ";10"); })
337 .then([](const std::string& s) {
338 return makeFuture(s + ";11"); })
339 .then([](std::string s) {
340 return makeFuture(s + ";12"); })
341 .then([](const std::string s) {
342 return makeFuture(s + ";13"); })
344 EXPECT_EQ(f.value(), "1;2;3;4;5;6;7;8;9;10;11;12;13");
347 TEST(Future, thenTry) {
350 makeFuture<int>(42).then([&](Try<int>&& t) {
352 EXPECT_EQ(42, t.value());
354 EXPECT_TRUE(flag); flag = false;
357 .then([](Try<int>&& t) { return t.value(); })
358 .then([&](Try<int>&& t) { flag = true; EXPECT_EQ(42, t.value()); });
359 EXPECT_TRUE(flag); flag = false;
361 makeFuture().then([&](Try<Unit>&& t) { flag = true; t.value(); });
362 EXPECT_TRUE(flag); flag = false;
365 auto f = p.getFuture().then([&](Try<Unit>&& /* t */) { flag = true; });
367 EXPECT_FALSE(f.isReady());
370 EXPECT_TRUE(f.isReady());
373 TEST(Future, thenValue) {
375 makeFuture<int>(42).then([&](int i){
379 EXPECT_TRUE(flag); flag = false;
382 .then([](int i){ return i; })
383 .then([&](int i) { flag = true; EXPECT_EQ(42, i); });
384 EXPECT_TRUE(flag); flag = false;
386 makeFuture().then([&]{
389 EXPECT_TRUE(flag); flag = false;
391 auto f = makeFuture<int>(eggs).then([&](int /* i */) {});
392 EXPECT_THROW(f.value(), eggs_t);
394 f = makeFuture<Unit>(eggs).then([&]{});
395 EXPECT_THROW(f.value(), eggs_t);
398 TEST(Future, thenValueFuture) {
401 .then([](int i){ return makeFuture<int>(std::move(i)); })
402 .then([&](Try<int>&& t) { flag = true; EXPECT_EQ(42, t.value()); });
403 EXPECT_TRUE(flag); flag = false;
405 makeFuture().then([] {
407 }).then([&](Try<Unit>&& /* t */) { flag = true; });
408 EXPECT_TRUE(flag); flag = false;
411 static std::string doWorkStatic(Try<std::string>&& t) {
412 return t.value() + ";static";
415 TEST(Future, thenFunction) {
417 std::string doWork(Try<std::string>&& t) {
418 return t.value() + ";class";
420 static std::string doWorkStatic(Try<std::string>&& t) {
421 return t.value() + ";class-static";
425 auto f = makeFuture<std::string>("start")
427 .then(Worker::doWorkStatic)
428 .then(&Worker::doWork, &w);
430 EXPECT_EQ(f.value(), "start;static;class-static;class");
433 static Future<std::string> doWorkStaticFuture(Try<std::string>&& t) {
434 return makeFuture(t.value() + ";static");
437 TEST(Future, thenFunctionFuture) {
439 Future<std::string> doWorkFuture(Try<std::string>&& t) {
440 return makeFuture(t.value() + ";class");
442 static Future<std::string> doWorkStaticFuture(Try<std::string>&& t) {
443 return makeFuture(t.value() + ";class-static");
447 auto f = makeFuture<std::string>("start")
448 .then(doWorkStaticFuture)
449 .then(Worker::doWorkStaticFuture)
450 .then(&Worker::doWorkFuture, &w);
452 EXPECT_EQ(f.value(), "start;static;class-static;class");
455 TEST(Future, thenStdFunction) {
457 std::function<int()> fn = [](){ return 42; };
458 auto f = makeFuture().then(std::move(fn));
459 EXPECT_EQ(f.value(), 42);
462 std::function<int(int)> fn = [](int i){ return i + 23; };
463 auto f = makeFuture(19).then(std::move(fn));
464 EXPECT_EQ(f.value(), 42);
467 std::function<int(Try<int>&)> fn = [](Try<int>& t){ return t.value() + 2; };
468 auto f = makeFuture(1).then(std::move(fn));
469 EXPECT_EQ(f.value(), 3);
473 std::function<void()> fn = [&flag](){ flag = true; };
474 auto f = makeFuture().then(std::move(fn));
475 EXPECT_TRUE(f.isReady());
480 TEST(Future, thenBind) {
482 return makeFuture("bind");
484 auto b = std::bind(l);
485 auto f = makeFuture().then(std::move(b));
486 EXPECT_EQ(f.value(), "bind");
489 TEST(Future, thenBindTry) {
490 auto l = [](Try<std::string>&& t) {
491 return makeFuture(t.value() + ";bind");
493 auto b = std::bind(l, std::placeholders::_1);
494 auto f = makeFuture<std::string>("start").then(std::move(b));
496 EXPECT_EQ(f.value(), "start;bind");
499 TEST(Future, value) {
500 auto f = makeFuture(std::unique_ptr<int>(new int(42)));
501 auto up = std::move(f.value());
504 EXPECT_THROW(makeFuture<int>(eggs).value(), eggs_t);
507 TEST(Future, isReady) {
509 auto f = p.getFuture();
510 EXPECT_FALSE(f.isReady());
512 EXPECT_TRUE(f.isReady());
515 TEST(Future, futureNotReady) {
517 Future<int> f = p.getFuture();
518 EXPECT_THROW(f.value(), eggs_t);
521 TEST(Future, hasException) {
522 EXPECT_TRUE(makeFuture<int>(eggs).getTry().hasException());
523 EXPECT_FALSE(makeFuture(42).getTry().hasException());
526 TEST(Future, hasValue) {
527 EXPECT_TRUE(makeFuture(42).getTry().hasValue());
528 EXPECT_FALSE(makeFuture<int>(eggs).getTry().hasValue());
531 TEST(Future, makeFuture) {
532 EXPECT_TYPE(makeFuture(42), Future<int>);
533 EXPECT_EQ(42, makeFuture(42).value());
535 EXPECT_TYPE(makeFuture<float>(42), Future<float>);
536 EXPECT_EQ(42, makeFuture<float>(42).value());
538 auto fun = [] { return 42; };
539 EXPECT_TYPE(makeFutureWith(fun), Future<int>);
540 EXPECT_EQ(42, makeFutureWith(fun).value());
542 auto funf = [] { return makeFuture<int>(43); };
543 EXPECT_TYPE(makeFutureWith(funf), Future<int>);
544 EXPECT_EQ(43, makeFutureWith(funf).value());
546 auto failfun = []() -> int { throw eggs; };
547 EXPECT_TYPE(makeFutureWith(failfun), Future<int>);
548 EXPECT_NO_THROW(makeFutureWith(failfun));
549 EXPECT_THROW(makeFutureWith(failfun).value(), eggs_t);
551 auto failfunf = []() -> Future<int> { throw eggs; };
552 EXPECT_TYPE(makeFutureWith(failfunf), Future<int>);
553 EXPECT_NO_THROW(makeFutureWith(failfunf));
554 EXPECT_THROW(makeFutureWith(failfunf).value(), eggs_t);
556 EXPECT_TYPE(makeFuture(), Future<Unit>);
559 TEST(Future, finish) {
560 auto x = std::make_shared<int>(0);
563 auto f = p.getFuture().then([x](Try<int>&& t) { *x = t.value(); });
565 // The callback hasn't executed
568 // The callback has a reference to x
569 EXPECT_EQ(2, x.use_count());
573 // the callback has executed
576 // the callback has been destructed
577 // and has released its reference to x
578 EXPECT_EQ(1, x.use_count());
581 TEST(Future, unwrap) {
585 auto fa = a.getFuture();
586 auto fb = b.getFuture();
591 // do a, then do b, and get the result of a + b.
592 Future<int> f = fa.then([&](Try<int>&& ta) {
593 auto va = ta.value();
595 return fb.then([va, &flag2](Try<int>&& tb) {
597 return va + tb.value();
603 EXPECT_FALSE(f.isReady());
608 EXPECT_FALSE(f.isReady());
613 EXPECT_EQ(7, f.value());
616 TEST(Future, throwCaughtInImmediateThen) {
617 // Neither of these should throw "Promise already satisfied"
619 [=](Try<Unit>&&) -> int { throw std::exception(); });
621 [=](Try<Unit>&&) -> Future<int> { throw std::exception(); });
624 TEST(Future, throwIfFailed) {
625 makeFuture<Unit>(eggs)
626 .then([=](Try<Unit>&& t) {
627 EXPECT_THROW(t.throwIfFailed(), eggs_t);
630 .then([=](Try<Unit>&& t) {
631 EXPECT_NO_THROW(t.throwIfFailed());
634 makeFuture<int>(eggs)
635 .then([=](Try<int>&& t) {
636 EXPECT_THROW(t.throwIfFailed(), eggs_t);
639 .then([=](Try<int>&& t) {
640 EXPECT_NO_THROW(t.throwIfFailed());
644 TEST(Future, getFutureAfterSetValue) {
647 EXPECT_EQ(42, p.getFuture().value());
650 TEST(Future, getFutureAfterSetException) {
652 p.setWith([]() -> void { throw std::logic_error("foo"); });
653 EXPECT_THROW(p.getFuture().value(), std::logic_error);
656 TEST(Future, detachRace) {
658 // This test is designed to detect a race that was in Core::detachOne()
659 // where detached_ was incremented and then tested, and that
660 // allowed a race where both Promise and Future would think they were the
661 // second and both try to delete. This showed up at scale but was very
662 // difficult to reliably repro in a test. As it is, this only fails about
663 // once in every 1,000 executions. Doing this 1,000 times is going to make a
664 // slow test so I won't do that but if it ever fails, take it seriously, and
665 // run the test binary with "--gtest_repeat=10000 --gtest_filter=*detachRace"
666 // (Don't forget to enable ASAN)
667 auto p = folly::make_unique<Promise<bool>>();
668 auto f = folly::make_unique<Future<bool>>(p->getFuture());
669 folly::Baton<> baton;
679 // Test of handling of a circular dependency. It's never recommended
680 // to have one because of possible memory leaks. Here we test that
681 // we can handle freeing of the Future while it is running.
682 TEST(Future, CircularDependencySharedPtrSelfReset) {
683 Promise<int64_t> promise;
684 auto ptr = std::make_shared<Future<int64_t>>(promise.getFuture());
686 ptr->then([ptr](folly::Try<int64_t>&& /* uid */) mutable {
687 EXPECT_EQ(1, ptr.use_count());
689 // Leaving no references to ourselves.
691 EXPECT_EQ(0, ptr.use_count());
694 EXPECT_EQ(2, ptr.use_count());
701 TEST(Future, Constructor) {
702 auto f1 = []() -> Future<int> { return Future<int>(3); }();
703 EXPECT_EQ(f1.value(), 3);
704 auto f2 = []() -> Future<Unit> { return Future<Unit>(); }();
705 EXPECT_NO_THROW(f2.value());
708 TEST(Future, ImplicitConstructor) {
709 auto f1 = []() -> Future<int> { return 3; }();
710 EXPECT_EQ(f1.value(), 3);
711 // Unfortunately, the C++ standard does not allow the
712 // following implicit conversion to work:
713 //auto f2 = []() -> Future<Unit> { }();
716 TEST(Future, thenDynamic) {
717 // folly::dynamic has a constructor that takes any T, this test makes
718 // sure that we call the then lambda with folly::dynamic and not
719 // Try<folly::dynamic> because that then fails to compile
720 Promise<folly::dynamic> p;
721 Future<folly::dynamic> f = p.getFuture().then(
722 [](const folly::dynamic& d) {
723 return folly::dynamic(d.asInt() + 3);
727 EXPECT_EQ(f.get(), 5);
730 TEST(Future, RequestContext) {
731 class NewThreadExecutor : public Executor {
733 ~NewThreadExecutor() override {
734 std::for_each(v_.begin(), v_.end(), [](std::thread& t){ t.join(); });
736 void add(Func f) override {
737 if (throwsOnAdd_) { throw std::exception(); }
738 v_.emplace_back(std::move(f));
740 void addWithPriority(Func f, int8_t /* prio */) override {
743 uint8_t getNumPriorities() const override { return numPriorities_; }
745 void setHandlesPriorities() { numPriorities_ = 2; }
746 void setThrowsOnAdd() { throwsOnAdd_ = true; }
748 std::vector<std::thread> v_;
749 uint8_t numPriorities_ = 1;
750 bool throwsOnAdd_ = false;
753 struct MyRequestData : RequestData {
754 MyRequestData(bool value = false) : value(value) {}
759 RequestContext::create();
760 RequestContext::get()->setContextData("key",
761 folly::make_unique<MyRequestData>(true));
762 auto checker = [](int lineno) {
763 return [lineno](Try<int>&& /* t */) {
764 auto d = static_cast<MyRequestData*>(
765 RequestContext::get()->getContextData("key"));
766 EXPECT_TRUE(d && d->value) << "on line " << lineno;
770 makeFuture(1).via(&e).then(checker(__LINE__));
772 e.setHandlesPriorities();
773 makeFuture(2).via(&e).then(checker(__LINE__));
776 p1.getFuture().then(checker(__LINE__));
779 p2.getFuture().via(&e).then(checker(__LINE__));
781 RequestContext::create();
786 TEST(Future, makeFutureNoThrow) {
787 makeFuture().value();