2 * Copyright 2014 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.
19 #include <folly/small_vector.h>
20 #include <gtest/gtest.h>
24 #include <type_traits>
26 #include <folly/Memory.h>
27 #include <folly/wangle/Executor.h>
28 #include <folly/wangle/Future.h>
29 #include <folly/wangle/ManualExecutor.h>
31 #include <folly/io/async/Request.h>
33 using namespace folly;
34 using namespace folly::wangle;
37 using std::unique_ptr;
40 #define EXPECT_TYPE(x, T) \
41 EXPECT_TRUE((std::is_same<decltype(x), T>::value))
43 typedef WangleException eggs_t;
44 static eggs_t eggs("eggs");
61 Try<A> t_a(std::move(a));
65 EXPECT_EQ(5, t_a.value().x());
68 TEST(Future, special) {
69 EXPECT_FALSE(std::is_copy_constructible<Future<int>>::value);
70 EXPECT_FALSE(std::is_copy_assignable<Future<int>>::value);
71 EXPECT_TRUE(std::is_move_constructible<Future<int>>::value);
72 EXPECT_TRUE(std::is_move_assignable<Future<int>>::value);
75 TEST(Future, thenTry) {
78 makeFuture<int>(42).then([&](Try<int>&& t) {
80 EXPECT_EQ(42, t.value());
82 EXPECT_TRUE(flag); flag = false;
85 .then([](Try<int>&& t) { return t.value(); })
86 .then([&](Try<int>&& t) { flag = true; EXPECT_EQ(42, t.value()); });
87 EXPECT_TRUE(flag); flag = false;
89 makeFuture().then([&](Try<void>&& t) { flag = true; t.value(); });
90 EXPECT_TRUE(flag); flag = false;
93 auto f = p.getFuture().then([&](Try<void>&& t) { flag = true; });
95 EXPECT_FALSE(f.isReady());
98 EXPECT_TRUE(f.isReady());
101 TEST(Future, thenValue) {
103 makeFuture<int>(42).then([&](int i){
107 EXPECT_TRUE(flag); flag = false;
110 .then([](int i){ return i; })
111 .then([&](int i) { flag = true; EXPECT_EQ(42, i); });
112 EXPECT_TRUE(flag); flag = false;
114 makeFuture().then([&]{
117 EXPECT_TRUE(flag); flag = false;
119 auto f = makeFuture<int>(eggs).then([&](int i){});
120 EXPECT_THROW(f.value(), eggs_t);
122 f = makeFuture<void>(eggs).then([&]{});
123 EXPECT_THROW(f.value(), eggs_t);
126 TEST(Future, thenValueFuture) {
129 .then([](int i){ return makeFuture<int>(std::move(i)); })
130 .then([&](Try<int>&& t) { flag = true; EXPECT_EQ(42, t.value()); });
131 EXPECT_TRUE(flag); flag = false;
134 .then([]{ return makeFuture(); })
135 .then([&](Try<void>&& t) { flag = true; });
136 EXPECT_TRUE(flag); flag = false;
139 static string doWorkStatic(Try<string>&& t) {
140 return t.value() + ";static";
143 TEST(Future, thenFunction) {
145 string doWork(Try<string>&& t) {
146 return t.value() + ";class";
148 static string doWorkStatic(Try<string>&& t) {
149 return t.value() + ";class-static";
153 auto f = makeFuture<string>("start")
155 .then(Worker::doWorkStatic)
156 .then(&w, &Worker::doWork);
158 EXPECT_EQ(f.value(), "start;static;class-static;class");
161 static Future<string> doWorkStaticFuture(Try<string>&& t) {
162 return makeFuture(t.value() + ";static");
165 TEST(Future, thenFunctionFuture) {
167 Future<string> doWorkFuture(Try<string>&& t) {
168 return makeFuture(t.value() + ";class");
170 static Future<string> doWorkStaticFuture(Try<string>&& t) {
171 return makeFuture(t.value() + ";class-static");
175 auto f = makeFuture<string>("start")
176 .then(doWorkStaticFuture)
177 .then(Worker::doWorkStaticFuture)
178 .then(&w, &Worker::doWorkFuture);
180 EXPECT_EQ(f.value(), "start;static;class-static;class");
183 TEST(Future, value) {
184 auto f = makeFuture(unique_ptr<int>(new int(42)));
185 auto up = std::move(f.value());
188 EXPECT_THROW(makeFuture<int>(eggs).value(), eggs_t);
191 TEST(Future, isReady) {
193 auto f = p.getFuture();
194 EXPECT_FALSE(f.isReady());
196 EXPECT_TRUE(f.isReady());
199 TEST(Future, futureNotReady) {
201 Future<int> f = p.getFuture();
202 EXPECT_THROW(f.value(), eggs_t);
205 TEST(Future, hasException) {
206 EXPECT_TRUE(makeFuture<int>(eggs).getTry().hasException());
207 EXPECT_FALSE(makeFuture(42).getTry().hasException());
210 TEST(Future, hasValue) {
211 EXPECT_TRUE(makeFuture(42).getTry().hasValue());
212 EXPECT_FALSE(makeFuture<int>(eggs).getTry().hasValue());
215 TEST(Future, makeFuture) {
216 EXPECT_TYPE(makeFuture(42), Future<int>);
217 EXPECT_EQ(42, makeFuture(42).value());
219 EXPECT_TYPE(makeFuture<float>(42), Future<float>);
220 EXPECT_EQ(42, makeFuture<float>(42).value());
222 auto fun = [] { return 42; };
223 EXPECT_TYPE(makeFutureTry(fun), Future<int>);
224 EXPECT_EQ(42, makeFutureTry(fun).value());
226 auto failfun = []() -> int { throw eggs; };
227 EXPECT_TYPE(makeFutureTry(failfun), Future<int>);
228 EXPECT_THROW(makeFutureTry(failfun).value(), eggs_t);
230 EXPECT_TYPE(makeFuture(), Future<void>);
235 TEST(Promise, special) {
236 EXPECT_FALSE(std::is_copy_constructible<Promise<int>>::value);
237 EXPECT_FALSE(std::is_copy_assignable<Promise<int>>::value);
238 EXPECT_TRUE(std::is_move_constructible<Promise<int>>::value);
239 EXPECT_TRUE(std::is_move_assignable<Promise<int>>::value);
242 TEST(Promise, getFuture) {
244 Future<int> f = p.getFuture();
245 EXPECT_FALSE(f.isReady());
248 TEST(Promise, setValue) {
250 auto ffund = fund.getFuture();
252 EXPECT_EQ(42, ffund.value());
260 auto fpod = pod.getFuture();
261 Foo f = {"the answer", 42};
263 Foo f2 = fpod.value();
264 EXPECT_EQ(f.name, f2.name);
265 EXPECT_EQ(f.value, f2.value);
267 pod = Promise<Foo>();
268 fpod = pod.getFuture();
269 pod.setValue(std::move(f2));
270 Foo f3 = fpod.value();
271 EXPECT_EQ(f.name, f3.name);
272 EXPECT_EQ(f.value, f3.value);
274 Promise<unique_ptr<int>> mov;
275 auto fmov = mov.getFuture();
276 mov.setValue(unique_ptr<int>(new int(42)));
277 unique_ptr<int> ptr = std::move(fmov.value());
281 auto fv = v.getFuture();
283 EXPECT_TRUE(fv.isReady());
286 TEST(Promise, setException) {
289 auto f = p.getFuture();
290 p.setException(eggs);
291 EXPECT_THROW(f.value(), eggs_t);
295 auto f = p.getFuture();
299 p.setException(std::current_exception());
301 EXPECT_THROW(f.value(), eggs_t);
305 TEST(Promise, fulfil) {
308 auto f = p.getFuture();
309 p.fulfil([] { return 42; });
310 EXPECT_EQ(42, f.value());
314 auto f = p.getFuture();
315 p.fulfil([]() -> int { throw eggs; });
316 EXPECT_THROW(f.value(), eggs_t);
320 TEST(Future, finish) {
321 auto x = std::make_shared<int>(0);
324 auto f = p.getFuture().then([x](Try<int>&& t) { *x = t.value(); });
326 // The callback hasn't executed
329 // The callback has a reference to x
330 EXPECT_EQ(2, x.use_count());
334 // the callback has executed
337 // the callback has been destructed
338 // and has released its reference to x
339 EXPECT_EQ(1, x.use_count());
342 TEST(Future, unwrap) {
346 auto fa = a.getFuture();
347 auto fb = b.getFuture();
352 // do a, then do b, and get the result of a + b.
353 Future<int> f = fa.then([&](Try<int>&& ta) {
354 auto va = ta.value();
356 return fb.then([va, &flag2](Try<int>&& tb) {
358 return va + tb.value();
364 EXPECT_FALSE(f.isReady());
369 EXPECT_FALSE(f.isReady());
374 EXPECT_EQ(7, f.value());
377 TEST(Future, whenAll) {
378 // returns a vector variant
380 vector<Promise<int>> promises(10);
381 vector<Future<int>> futures;
383 for (auto& p : promises)
384 futures.push_back(p.getFuture());
386 auto allf = whenAll(futures.begin(), futures.end());
388 random_shuffle(promises.begin(), promises.end());
389 for (auto& p : promises) {
390 EXPECT_FALSE(allf.isReady());
394 EXPECT_TRUE(allf.isReady());
395 auto& results = allf.value();
396 for (auto& t : results) {
397 EXPECT_EQ(42, t.value());
401 // check error semantics
403 vector<Promise<int>> promises(4);
404 vector<Future<int>> futures;
406 for (auto& p : promises)
407 futures.push_back(p.getFuture());
409 auto allf = whenAll(futures.begin(), futures.end());
412 promises[0].setValue(42);
413 promises[1].setException(eggs);
415 EXPECT_FALSE(allf.isReady());
417 promises[2].setValue(42);
419 EXPECT_FALSE(allf.isReady());
421 promises[3].setException(eggs);
423 EXPECT_TRUE(allf.isReady());
424 EXPECT_FALSE(allf.getTry().hasException());
426 auto& results = allf.value();
427 EXPECT_EQ(42, results[0].value());
428 EXPECT_TRUE(results[1].hasException());
429 EXPECT_EQ(42, results[2].value());
430 EXPECT_TRUE(results[3].hasException());
433 // check that futures are ready in then()
435 vector<Promise<void>> promises(10);
436 vector<Future<void>> futures;
438 for (auto& p : promises)
439 futures.push_back(p.getFuture());
441 auto allf = whenAll(futures.begin(), futures.end())
442 .then([](Try<vector<Try<void>>>&& ts) {
443 for (auto& f : ts.value())
447 random_shuffle(promises.begin(), promises.end());
448 for (auto& p : promises)
450 EXPECT_TRUE(allf.isReady());
455 TEST(Future, whenAny) {
457 vector<Promise<int>> promises(10);
458 vector<Future<int>> futures;
460 for (auto& p : promises)
461 futures.push_back(p.getFuture());
463 for (auto& f : futures) {
464 EXPECT_FALSE(f.isReady());
467 auto anyf = whenAny(futures.begin(), futures.end());
469 /* futures were moved in, so these are invalid now */
470 EXPECT_FALSE(anyf.isReady());
472 promises[7].setValue(42);
473 EXPECT_TRUE(anyf.isReady());
474 auto& idx_fut = anyf.value();
476 auto i = idx_fut.first;
479 auto& f = idx_fut.second;
480 EXPECT_EQ(42, f.value());
485 vector<Promise<void>> promises(10);
486 vector<Future<void>> futures;
488 for (auto& p : promises)
489 futures.push_back(p.getFuture());
491 for (auto& f : futures) {
492 EXPECT_FALSE(f.isReady());
495 auto anyf = whenAny(futures.begin(), futures.end());
497 EXPECT_FALSE(anyf.isReady());
499 promises[3].setException(eggs);
500 EXPECT_TRUE(anyf.isReady());
501 EXPECT_TRUE(anyf.value().second.hasException());
506 vector<Promise<int>> promises(10);
507 vector<Future<int>> futures;
509 for (auto& p : promises)
510 futures.push_back(p.getFuture());
512 auto anyf = whenAny(futures.begin(), futures.end())
513 .then([](Try<pair<size_t, Try<int>>>&& f) {
514 EXPECT_EQ(42, f.value().second.value());
517 promises[3].setValue(42);
518 EXPECT_TRUE(anyf.isReady());
523 TEST(when, already_completed) {
525 vector<Future<void>> fs;
526 for (int i = 0; i < 10; i++)
527 fs.push_back(makeFuture());
529 whenAll(fs.begin(), fs.end())
530 .then([&](Try<vector<Try<void>>>&& t) {
531 EXPECT_EQ(fs.size(), t.value().size());
535 vector<Future<int>> fs;
536 for (int i = 0; i < 10; i++)
537 fs.push_back(makeFuture(i));
539 whenAny(fs.begin(), fs.end())
540 .then([&](Try<pair<size_t, Try<int>>>&& t) {
542 EXPECT_EQ(p.first, p.second.value());
548 vector<Promise<void>> promises(10);
549 vector<Future<void>> futures;
551 for (auto& p : promises)
552 futures.push_back(p.getFuture());
556 whenN(futures.begin(), futures.end(), n)
557 .then([&](Try<vector<pair<size_t, Try<void>>>>&& t) {
560 EXPECT_EQ(n, v.size());
562 EXPECT_TRUE(tt.second.hasValue());
565 promises[0].setValue();
567 promises[1].setValue();
569 promises[2].setValue();
573 /* Ensure that we can compile when_{all,any} with folly::small_vector */
574 TEST(when, small_vector) {
576 static_assert(!FOLLY_IS_TRIVIALLY_COPYABLE(Future<void>),
577 "Futures should not be trivially copyable");
578 static_assert(!FOLLY_IS_TRIVIALLY_COPYABLE(Future<int>),
579 "Futures should not be trivially copyable");
581 using folly::small_vector;
583 small_vector<Future<void>> futures;
585 for (int i = 0; i < 10; i++)
586 futures.push_back(makeFuture());
588 auto anyf = whenAny(futures.begin(), futures.end());
592 small_vector<Future<void>> futures;
594 for (int i = 0; i < 10; i++)
595 futures.push_back(makeFuture());
597 auto allf = whenAll(futures.begin(), futures.end());
601 TEST(Future, whenAllVariadic) {
604 Future<bool> fb = pb.getFuture();
605 Future<int> fi = pi.getFuture();
607 whenAll(std::move(fb), std::move(fi))
608 .then([&](Try<std::tuple<Try<bool>, Try<int>>>&& t) {
610 EXPECT_TRUE(t.hasValue());
611 EXPECT_TRUE(std::get<0>(t.value()).hasValue());
612 EXPECT_EQ(std::get<0>(t.value()).value(), true);
613 EXPECT_TRUE(std::get<1>(t.value()).hasValue());
614 EXPECT_EQ(std::get<1>(t.value()).value(), 42);
622 TEST(Future, whenAllVariadicReferences) {
625 Future<bool> fb = pb.getFuture();
626 Future<int> fi = pi.getFuture();
629 .then([&](Try<std::tuple<Try<bool>, Try<int>>>&& t) {
631 EXPECT_TRUE(t.hasValue());
632 EXPECT_TRUE(std::get<0>(t.value()).hasValue());
633 EXPECT_EQ(std::get<0>(t.value()).value(), true);
634 EXPECT_TRUE(std::get<1>(t.value()).hasValue());
635 EXPECT_EQ(std::get<1>(t.value()).value(), 42);
643 TEST(Future, whenAll_none) {
644 vector<Future<int>> fs;
645 auto f = whenAll(fs.begin(), fs.end());
646 EXPECT_TRUE(f.isReady());
649 TEST(Future, throwCaughtInImmediateThen) {
650 // Neither of these should throw "Promise already satisfied"
652 [=](Try<void>&&) -> int { throw std::exception(); });
654 [=](Try<void>&&) -> Future<int> { throw std::exception(); });
657 TEST(Future, throwIfFailed) {
658 makeFuture<void>(eggs)
659 .then([=](Try<void>&& t) {
660 EXPECT_THROW(t.throwIfFailed(), eggs_t);
663 .then([=](Try<void>&& t) {
664 EXPECT_NO_THROW(t.throwIfFailed());
667 makeFuture<int>(eggs)
668 .then([=](Try<int>&& t) {
669 EXPECT_THROW(t.throwIfFailed(), eggs_t);
672 .then([=](Try<int>&& t) {
673 EXPECT_NO_THROW(t.throwIfFailed());
677 TEST(Future, waitWithSemaphoreImmediate) {
678 waitWithSemaphore(makeFuture());
679 auto done = waitWithSemaphore(makeFuture(42)).value();
682 vector<int> v{1,2,3};
683 auto done_v = waitWithSemaphore(makeFuture(v)).value();
684 EXPECT_EQ(v.size(), done_v.size());
685 EXPECT_EQ(v, done_v);
687 vector<Future<void>> v_f;
688 v_f.push_back(makeFuture());
689 v_f.push_back(makeFuture());
690 auto done_v_f = waitWithSemaphore(whenAll(v_f.begin(), v_f.end())).value();
691 EXPECT_EQ(2, done_v_f.size());
693 vector<Future<bool>> v_fb;
694 v_fb.push_back(makeFuture(true));
695 v_fb.push_back(makeFuture(false));
696 auto fut = whenAll(v_fb.begin(), v_fb.end());
697 auto done_v_fb = std::move(waitWithSemaphore(std::move(fut)).value());
698 EXPECT_EQ(2, done_v_fb.size());
701 TEST(Future, waitWithSemaphore) {
703 Future<int> f = p.getFuture();
704 std::atomic<bool> flag{false};
705 std::atomic<int> result{1};
706 std::atomic<std::thread::id> id;
708 std::thread t([&](Future<int>&& tf){
709 auto n = tf.then([&](Try<int> && t) {
710 id = std::this_thread::get_id();
714 result.store(waitWithSemaphore(std::move(n)).value());
719 EXPECT_EQ(result.load(), 1);
722 // validate that the callback ended up executing in this thread, which
723 // is more to ensure that this test actually tests what it should
724 EXPECT_EQ(id, std::this_thread::get_id());
725 EXPECT_EQ(result.load(), 42);
728 TEST(Future, waitWithSemaphoreForTime) {
731 Future<int> f = p.getFuture();
732 auto t = waitWithSemaphore(std::move(f),
733 std::chrono::microseconds(1));
734 EXPECT_FALSE(t.isReady());
736 EXPECT_TRUE(t.isReady());
740 Future<int> f = p.getFuture();
742 auto t = waitWithSemaphore(std::move(f),
743 std::chrono::milliseconds(1));
744 EXPECT_TRUE(t.isReady());
747 vector<Future<bool>> v_fb;
748 v_fb.push_back(makeFuture(true));
749 v_fb.push_back(makeFuture(false));
750 auto f = whenAll(v_fb.begin(), v_fb.end());
751 auto t = waitWithSemaphore(std::move(f),
752 std::chrono::milliseconds(1));
753 EXPECT_TRUE(t.isReady());
754 EXPECT_EQ(2, t.value().size());
757 vector<Future<bool>> v_fb;
760 v_fb.push_back(p1.getFuture());
761 v_fb.push_back(p2.getFuture());
762 auto f = whenAll(v_fb.begin(), v_fb.end());
763 auto t = waitWithSemaphore(std::move(f),
764 std::chrono::milliseconds(1));
765 EXPECT_FALSE(t.isReady());
767 EXPECT_FALSE(t.isReady());
769 EXPECT_TRUE(t.isReady());
772 auto t = waitWithSemaphore(makeFuture(),
773 std::chrono::milliseconds(1));
774 EXPECT_TRUE(t.isReady());
778 TEST(Future, callbackAfterActivate) {
780 auto f = p.getFuture();
784 f.then([&](Try<void>&&) { count++; });
793 TEST(Future, activateOnDestruct) {
795 auto f = p.getFuture();
799 f.then([&](Try<void>&&) { count++; });
804 f = makeFuture(); // force destruction of old f
808 TEST(Future, viaActsCold) {
812 auto fv = makeFuture().via(&x);
813 fv.then([&](Try<void>&&) { count++; });
819 EXPECT_EQ(1, x.run());
823 TEST(Future, viaIsCold) {
825 EXPECT_FALSE(makeFuture().via(&x).isActive());
828 TEST(Future, viaRaces) {
831 auto tid = std::this_thread::get_id();
837 .then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
838 .then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
839 .then([&](Try<void>&&) { done = true; });
846 while (!done) x.run();
852 TEST(Future, viaRaces_2stage) {
855 auto tid = std::this_thread::get_id();
859 auto f2 = p.getFuture().via(&x);
860 f2.then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
861 .then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
862 .then([&](Try<void>&&) { done = true; });
864 // the bug was in the promise being fulfilled before f2 is reactivated. we
865 // could sleep, but yielding should cause this to fail with reasonable
867 std::this_thread::yield();
875 while (!done) x.run();
880 TEST(Future, getFuture_after_setValue) {
883 EXPECT_EQ(42, p.getFuture().value());
886 TEST(Future, getFuture_after_setException) {
888 p.fulfil([]() -> void { throw std::logic_error("foo"); });
889 EXPECT_THROW(p.getFuture().value(), std::logic_error);
892 TEST(Future, detachRace) {
894 // This test is designed to detect a race that was in Core::detachOne()
895 // where detached_ was incremented and then tested, and that
896 // allowed a race where both Promise and Future would think they were the
897 // second and both try to delete. This showed up at scale but was very
898 // difficult to reliably repro in a test. As it is, this only fails about
899 // once in every 1,000 executions. Doing this 1,000 times is going to make a
900 // slow test so I won't do that but if it ever fails, take it seriously, and
901 // run the test binary with "--gtest_repeat=10000 --gtest_filter=*detachRace"
902 // (Don't forget to enable ASAN)
903 auto p = folly::make_unique<Promise<bool>>();
904 auto f = folly::make_unique<Future<bool>>(p->getFuture());
905 folly::Baton<> baton;
915 class TestData : public RequestData {
917 explicit TestData(int data) : data_(data) {}
918 virtual ~TestData() {}
922 TEST(Future, context) {
924 // Start a new context
925 RequestContext::create();
927 EXPECT_EQ(nullptr, RequestContext::get()->getContextData("test"));
929 // Set some test data
930 RequestContext::get()->setContextData(
932 std::unique_ptr<TestData>(new TestData(10)));
936 auto future = p.getFuture().then([&]{
937 // Check that the context followed the future
938 EXPECT_TRUE(RequestContext::get() != nullptr);
939 auto a = dynamic_cast<TestData*>(
940 RequestContext::get()->getContextData("test"));
941 auto data = a->data_;
946 RequestContext::setContext(nullptr);
948 EXPECT_EQ(nullptr, RequestContext::get()->getContextData("test"));
950 // Fulfil the promise