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.
19 #include <folly/small_vector.h>
20 #include <gtest/gtest.h>
24 #include <type_traits>
26 #include <folly/Memory.h>
27 #include <folly/Executor.h>
28 #include <folly/futures/Future.h>
29 #include <folly/futures/ManualExecutor.h>
30 #include <folly/futures/DrivableExecutor.h>
31 #include <folly/dynamic.h>
32 #include <folly/Baton.h>
33 #include <folly/MPMCQueue.h>
35 #include <folly/io/async/EventBase.h>
36 #include <folly/io/async/Request.h>
38 using namespace folly;
41 using std::unique_ptr;
43 using std::chrono::milliseconds;
45 #define EXPECT_TYPE(x, T) \
46 EXPECT_TRUE((std::is_same<decltype(x), T>::value))
48 /// Simple executor that does work in another thread
49 class ThreadExecutor : public Executor {
50 folly::MPMCQueue<Func> funcs;
51 std::atomic<bool> done {false};
59 while (!funcs.isEmpty()) {
60 funcs.blockingRead(fn);
67 explicit ThreadExecutor(size_t n = 1024)
69 worker = std::thread(std::bind(&ThreadExecutor::work, this));
78 void add(Func fn) override {
79 funcs.blockingWrite(std::move(fn));
82 void waitForStartup() {
87 typedef FutureException eggs_t;
88 static eggs_t eggs("eggs");
92 TEST(Future, coreSize) {
93 // If this number goes down, it's fine!
94 // If it goes up, please seek professional advice ;-)
95 EXPECT_EQ(192, sizeof(detail::Core<void>));
100 TEST(Future, onError) {
101 bool theFlag = false;
102 auto flag = [&]{ theFlag = true; };
103 #define EXPECT_FLAG() \
105 EXPECT_TRUE(theFlag); \
109 #define EXPECT_NO_FLAG() \
111 EXPECT_FALSE(theFlag); \
117 auto f = makeFuture()
118 .then([] { throw eggs; })
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) { flag(); return makeFuture(); });
129 EXPECT_NO_THROW(f.value());
134 auto f = makeFuture()
135 .then([] { throw eggs; })
136 .onError([&] (eggs_t e) { flag(); });
138 EXPECT_NO_THROW(f.value());
142 auto f = makeFuture()
143 .then([] { throw eggs; })
144 .onError([&] (eggs_t e) { flag(); return makeFuture(); });
146 EXPECT_NO_THROW(f.value());
151 auto f = makeFuture()
152 .then([] { throw eggs; })
153 .onError([&] (std::exception& e) { flag(); });
155 EXPECT_NO_THROW(f.value());
159 auto f = makeFuture()
160 .then([] { throw eggs; })
161 .onError([&] (std::exception& e) { flag(); return makeFuture(); });
163 EXPECT_NO_THROW(f.value());
168 auto f = makeFuture()
169 .then([] { throw -1; })
170 .onError([&] (int e) { flag(); });
172 EXPECT_NO_THROW(f.value());
176 auto f = makeFuture()
177 .then([] { throw -1; })
178 .onError([&] (int e) { flag(); return makeFuture(); });
180 EXPECT_NO_THROW(f.value());
185 auto f = makeFuture()
186 .then([] { throw eggs; })
187 .onError([&] (eggs_t& e) mutable { flag(); });
189 EXPECT_NO_THROW(f.value());
193 auto f = makeFuture()
194 .then([] { throw eggs; })
195 .onError([&] (eggs_t& e) mutable { flag(); return makeFuture(); });
197 EXPECT_NO_THROW(f.value());
202 auto f = makeFuture()
203 .then([] { return 42; })
204 .onError([&] (eggs_t& e) { flag(); return -1; });
206 EXPECT_EQ(42, f.value());
210 auto f = makeFuture()
211 .then([] { return 42; })
212 .onError([&] (eggs_t& e) { flag(); return makeFuture<int>(-1); });
214 EXPECT_EQ(42, f.value());
217 // Catch different exception
219 auto f = makeFuture()
220 .then([] { throw eggs; })
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) { flag(); return makeFuture(); });
231 EXPECT_THROW(f.value(), eggs_t);
234 // Returned value propagates
236 auto f = makeFuture()
237 .then([] { throw eggs; return 0; })
238 .onError([&] (eggs_t& e) { return 42; });
239 EXPECT_EQ(42, f.value());
242 // Returned future propagates
244 auto f = makeFuture()
245 .then([] { throw eggs; return 0; })
246 .onError([&] (eggs_t& e) { return makeFuture<int>(42); });
247 EXPECT_EQ(42, f.value());
252 auto f = makeFuture()
253 .then([] { throw eggs; return 0; })
254 .onError([&] (eggs_t& e) { throw e; return -1; });
255 EXPECT_THROW(f.value(), eggs_t);
259 auto f = makeFuture()
260 .then([] { throw eggs; return 0; })
261 .onError([&] (eggs_t& e) { throw e; return makeFuture<int>(-1); });
262 EXPECT_THROW(f.value(), eggs_t);
265 // exception_wrapper, return Future<T>
267 auto f = makeFuture()
268 .then([] { throw eggs; })
269 .onError([&] (exception_wrapper e) { flag(); return makeFuture(); });
271 EXPECT_NO_THROW(f.value());
274 // exception_wrapper, return Future<T> but throw
276 auto f = makeFuture()
277 .then([]{ throw eggs; return 0; })
278 .onError([&] (exception_wrapper e) {
281 return makeFuture<int>(-1);
284 EXPECT_THROW(f.value(), eggs_t);
287 // exception_wrapper, return T
289 auto f = makeFuture()
290 .then([]{ throw eggs; return 0; })
291 .onError([&] (exception_wrapper e) {
296 EXPECT_EQ(-1, f.value());
299 // exception_wrapper, return T but throw
301 auto f = makeFuture()
302 .then([]{ throw eggs; return 0; })
303 .onError([&] (exception_wrapper e) {
309 EXPECT_THROW(f.value(), eggs_t);
312 // const exception_wrapper&
314 auto f = makeFuture()
315 .then([] { throw eggs; })
316 .onError([&] (const exception_wrapper& e) {
321 EXPECT_NO_THROW(f.value());
339 Try<A> t_a(std::move(a));
343 EXPECT_EQ(5, t_a.value().x());
346 TEST(Future, special) {
347 EXPECT_FALSE(std::is_copy_constructible<Future<int>>::value);
348 EXPECT_FALSE(std::is_copy_assignable<Future<int>>::value);
349 EXPECT_TRUE(std::is_move_constructible<Future<int>>::value);
350 EXPECT_TRUE(std::is_move_assignable<Future<int>>::value);
354 auto f = makeFuture<string>("0")
355 .then([](){ return makeFuture<string>("1"); })
356 .then([](Try<string>&& t) { return makeFuture(t.value() + ";2"); })
357 .then([](const Try<string>&& t) { return makeFuture(t.value() + ";3"); })
358 .then([](Try<string>& t) { return makeFuture(t.value() + ";4"); })
359 .then([](const Try<string>& t) { return makeFuture(t.value() + ";5"); })
360 .then([](Try<string> t) { return makeFuture(t.value() + ";6"); })
361 .then([](const Try<string> t) { return makeFuture(t.value() + ";7"); })
362 .then([](string&& s) { return makeFuture(s + ";8"); })
363 .then([](const string&& s) { return makeFuture(s + ";9"); })
364 .then([](string& s) { return makeFuture(s + ";10"); })
365 .then([](const string& s) { return makeFuture(s + ";11"); })
366 .then([](string s) { return makeFuture(s + ";12"); })
367 .then([](const string s) { return makeFuture(s + ";13"); })
369 EXPECT_EQ(f.value(), "1;2;3;4;5;6;7;8;9;10;11;12;13");
372 TEST(Future, thenTry) {
375 makeFuture<int>(42).then([&](Try<int>&& t) {
377 EXPECT_EQ(42, t.value());
379 EXPECT_TRUE(flag); flag = false;
382 .then([](Try<int>&& t) { return t.value(); })
383 .then([&](Try<int>&& t) { flag = true; EXPECT_EQ(42, t.value()); });
384 EXPECT_TRUE(flag); flag = false;
386 makeFuture().then([&](Try<void>&& t) { flag = true; t.value(); });
387 EXPECT_TRUE(flag); flag = false;
390 auto f = p.getFuture().then([&](Try<void>&& t) { flag = true; });
392 EXPECT_FALSE(f.isReady());
395 EXPECT_TRUE(f.isReady());
398 TEST(Future, thenValue) {
400 makeFuture<int>(42).then([&](int i){
404 EXPECT_TRUE(flag); flag = false;
407 .then([](int i){ return i; })
408 .then([&](int i) { flag = true; EXPECT_EQ(42, i); });
409 EXPECT_TRUE(flag); flag = false;
411 makeFuture().then([&]{
414 EXPECT_TRUE(flag); flag = false;
416 auto f = makeFuture<int>(eggs).then([&](int i){});
417 EXPECT_THROW(f.value(), eggs_t);
419 f = makeFuture<void>(eggs).then([&]{});
420 EXPECT_THROW(f.value(), eggs_t);
423 TEST(Future, thenValueFuture) {
426 .then([](int i){ return makeFuture<int>(std::move(i)); })
427 .then([&](Try<int>&& t) { flag = true; EXPECT_EQ(42, t.value()); });
428 EXPECT_TRUE(flag); flag = false;
431 .then([]{ return makeFuture(); })
432 .then([&](Try<void>&& t) { flag = true; });
433 EXPECT_TRUE(flag); flag = false;
436 static string doWorkStatic(Try<string>&& t) {
437 return t.value() + ";static";
440 TEST(Future, thenFunction) {
442 string doWork(Try<string>&& t) {
443 return t.value() + ";class";
445 static string doWorkStatic(Try<string>&& t) {
446 return t.value() + ";class-static";
450 auto f = makeFuture<string>("start")
452 .then(Worker::doWorkStatic)
453 .then(&Worker::doWork, &w);
455 EXPECT_EQ(f.value(), "start;static;class-static;class");
458 static Future<string> doWorkStaticFuture(Try<string>&& t) {
459 return makeFuture(t.value() + ";static");
462 TEST(Future, thenFunctionFuture) {
464 Future<string> doWorkFuture(Try<string>&& t) {
465 return makeFuture(t.value() + ";class");
467 static Future<string> doWorkStaticFuture(Try<string>&& t) {
468 return makeFuture(t.value() + ";class-static");
472 auto f = makeFuture<string>("start")
473 .then(doWorkStaticFuture)
474 .then(Worker::doWorkStaticFuture)
475 .then(&Worker::doWorkFuture, &w);
477 EXPECT_EQ(f.value(), "start;static;class-static;class");
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<string>&& t) {
491 return makeFuture(t.value() + ";bind");
493 auto b = std::bind(l, std::placeholders::_1);
494 auto f = makeFuture<string>("start").then(std::move(b));
496 EXPECT_EQ(f.value(), "start;bind");
499 TEST(Future, value) {
500 auto f = makeFuture(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 failfun = []() -> int { throw eggs; };
543 EXPECT_TYPE(makeFutureWith(failfun), Future<int>);
544 EXPECT_THROW(makeFutureWith(failfun).value(), eggs_t);
546 EXPECT_TYPE(makeFuture(), Future<void>);
551 TEST(Promise, special) {
552 EXPECT_FALSE(std::is_copy_constructible<Promise<int>>::value);
553 EXPECT_FALSE(std::is_copy_assignable<Promise<int>>::value);
554 EXPECT_TRUE(std::is_move_constructible<Promise<int>>::value);
555 EXPECT_TRUE(std::is_move_assignable<Promise<int>>::value);
558 TEST(Promise, getFuture) {
560 Future<int> f = p.getFuture();
561 EXPECT_FALSE(f.isReady());
564 TEST(Promise, setValue) {
566 auto ffund = fund.getFuture();
568 EXPECT_EQ(42, ffund.value());
576 auto fpod = pod.getFuture();
577 Foo f = {"the answer", 42};
579 Foo f2 = fpod.value();
580 EXPECT_EQ(f.name, f2.name);
581 EXPECT_EQ(f.value, f2.value);
583 pod = Promise<Foo>();
584 fpod = pod.getFuture();
585 pod.setValue(std::move(f2));
586 Foo f3 = fpod.value();
587 EXPECT_EQ(f.name, f3.name);
588 EXPECT_EQ(f.value, f3.value);
590 Promise<unique_ptr<int>> mov;
591 auto fmov = mov.getFuture();
592 mov.setValue(unique_ptr<int>(new int(42)));
593 unique_ptr<int> ptr = std::move(fmov.value());
597 auto fv = v.getFuture();
599 EXPECT_TRUE(fv.isReady());
602 TEST(Promise, setException) {
605 auto f = p.getFuture();
606 p.setException(eggs);
607 EXPECT_THROW(f.value(), eggs_t);
611 auto f = p.getFuture();
615 p.setException(exception_wrapper(std::current_exception()));
617 EXPECT_THROW(f.value(), eggs_t);
621 TEST(Promise, setWith) {
624 auto f = p.getFuture();
625 p.setWith([] { return 42; });
626 EXPECT_EQ(42, f.value());
630 auto f = p.getFuture();
631 p.setWith([]() -> int { throw eggs; });
632 EXPECT_THROW(f.value(), eggs_t);
636 TEST(Future, finish) {
637 auto x = std::make_shared<int>(0);
640 auto f = p.getFuture().then([x](Try<int>&& t) { *x = t.value(); });
642 // The callback hasn't executed
645 // The callback has a reference to x
646 EXPECT_EQ(2, x.use_count());
650 // the callback has executed
653 // the callback has been destructed
654 // and has released its reference to x
655 EXPECT_EQ(1, x.use_count());
658 TEST(Future, unwrap) {
662 auto fa = a.getFuture();
663 auto fb = b.getFuture();
668 // do a, then do b, and get the result of a + b.
669 Future<int> f = fa.then([&](Try<int>&& ta) {
670 auto va = ta.value();
672 return fb.then([va, &flag2](Try<int>&& tb) {
674 return va + tb.value();
680 EXPECT_FALSE(f.isReady());
685 EXPECT_FALSE(f.isReady());
690 EXPECT_EQ(7, f.value());
693 TEST(Future, stream) {
694 auto fn = [](vector<int> input, size_t window_size, size_t expect) {
698 [](int i) { return makeFuture(i); },
701 [](int sum, const Try<int>& b) {
704 EXPECT_EQ(expect, res);
707 // streaming 2 at a time
708 vector<int> input = {1, 2, 3};
712 // streaming 4 at a time
713 vector<int> input = {1, 2, 3};
723 TEST(Future, collectAll) {
724 // returns a vector variant
726 vector<Promise<int>> promises(10);
727 vector<Future<int>> futures;
729 for (auto& p : promises)
730 futures.push_back(p.getFuture());
732 auto allf = collectAll(futures);
734 random_shuffle(promises.begin(), promises.end());
735 for (auto& p : promises) {
736 EXPECT_FALSE(allf.isReady());
740 EXPECT_TRUE(allf.isReady());
741 auto& results = allf.value();
742 for (auto& t : results) {
743 EXPECT_EQ(42, t.value());
747 // check error semantics
749 vector<Promise<int>> promises(4);
750 vector<Future<int>> futures;
752 for (auto& p : promises)
753 futures.push_back(p.getFuture());
755 auto allf = collectAll(futures);
758 promises[0].setValue(42);
759 promises[1].setException(eggs);
761 EXPECT_FALSE(allf.isReady());
763 promises[2].setValue(42);
765 EXPECT_FALSE(allf.isReady());
767 promises[3].setException(eggs);
769 EXPECT_TRUE(allf.isReady());
770 EXPECT_FALSE(allf.getTry().hasException());
772 auto& results = allf.value();
773 EXPECT_EQ(42, results[0].value());
774 EXPECT_TRUE(results[1].hasException());
775 EXPECT_EQ(42, results[2].value());
776 EXPECT_TRUE(results[3].hasException());
779 // check that futures are ready in then()
781 vector<Promise<void>> promises(10);
782 vector<Future<void>> futures;
784 for (auto& p : promises)
785 futures.push_back(p.getFuture());
787 auto allf = collectAll(futures)
788 .then([](Try<vector<Try<void>>>&& ts) {
789 for (auto& f : ts.value())
793 random_shuffle(promises.begin(), promises.end());
794 for (auto& p : promises)
796 EXPECT_TRUE(allf.isReady());
800 TEST(Future, collect) {
803 vector<Promise<int>> promises(10);
804 vector<Future<int>> futures;
806 for (auto& p : promises)
807 futures.push_back(p.getFuture());
809 auto allf = collect(futures);
811 random_shuffle(promises.begin(), promises.end());
812 for (auto& p : promises) {
813 EXPECT_FALSE(allf.isReady());
817 EXPECT_TRUE(allf.isReady());
818 for (auto i : allf.value()) {
825 vector<Promise<int>> promises(10);
826 vector<Future<int>> futures;
828 for (auto& p : promises)
829 futures.push_back(p.getFuture());
831 auto allf = collect(futures);
833 random_shuffle(promises.begin(), promises.end());
834 for (int i = 0; i < 10; i++) {
836 // everthing goes well so far...
837 EXPECT_FALSE(allf.isReady());
838 promises[i].setValue(42);
840 // short circuit with an exception
841 EXPECT_FALSE(allf.isReady());
842 promises[i].setException(eggs);
843 EXPECT_TRUE(allf.isReady());
845 // don't blow up on further values
846 EXPECT_TRUE(allf.isReady());
847 promises[i].setValue(42);
849 // don't blow up on further exceptions
850 EXPECT_TRUE(allf.isReady());
851 promises[i].setException(eggs);
855 EXPECT_THROW(allf.value(), eggs_t);
858 // void futures success case
860 vector<Promise<void>> promises(10);
861 vector<Future<void>> futures;
863 for (auto& p : promises)
864 futures.push_back(p.getFuture());
866 auto allf = collect(futures);
868 random_shuffle(promises.begin(), promises.end());
869 for (auto& p : promises) {
870 EXPECT_FALSE(allf.isReady());
874 EXPECT_TRUE(allf.isReady());
877 // void futures failure case
879 vector<Promise<void>> promises(10);
880 vector<Future<void>> futures;
882 for (auto& p : promises)
883 futures.push_back(p.getFuture());
885 auto allf = collect(futures);
887 random_shuffle(promises.begin(), promises.end());
888 for (int i = 0; i < 10; i++) {
890 // everthing goes well so far...
891 EXPECT_FALSE(allf.isReady());
892 promises[i].setValue();
894 // short circuit with an exception
895 EXPECT_FALSE(allf.isReady());
896 promises[i].setException(eggs);
897 EXPECT_TRUE(allf.isReady());
899 // don't blow up on further values
900 EXPECT_TRUE(allf.isReady());
901 promises[i].setValue();
903 // don't blow up on further exceptions
904 EXPECT_TRUE(allf.isReady());
905 promises[i].setException(eggs);
909 EXPECT_THROW(allf.value(), eggs_t);
912 // move only compiles
914 vector<Promise<unique_ptr<int>>> promises(10);
915 vector<Future<unique_ptr<int>>> futures;
917 for (auto& p : promises)
918 futures.push_back(p.getFuture());
925 struct NotDefaultConstructible {
926 NotDefaultConstructible() = delete;
927 NotDefaultConstructible(int arg) : i(arg) {}
931 // We have a specialized implementation for non-default-constructible objects
932 // Ensure that it works and preserves order
933 TEST(Future, collectNotDefaultConstructible) {
934 vector<Promise<NotDefaultConstructible>> promises(10);
935 vector<Future<NotDefaultConstructible>> futures;
936 vector<int> indices(10);
937 std::iota(indices.begin(), indices.end(), 0);
938 random_shuffle(indices.begin(), indices.end());
940 for (auto& p : promises)
941 futures.push_back(p.getFuture());
943 auto allf = collect(futures);
945 for (auto i : indices) {
946 EXPECT_FALSE(allf.isReady());
947 promises[i].setValue(NotDefaultConstructible(i));
950 EXPECT_TRUE(allf.isReady());
952 for (auto val : allf.value()) {
958 TEST(Future, collectAny) {
960 vector<Promise<int>> promises(10);
961 vector<Future<int>> futures;
963 for (auto& p : promises)
964 futures.push_back(p.getFuture());
966 for (auto& f : futures) {
967 EXPECT_FALSE(f.isReady());
970 auto anyf = collectAny(futures);
972 /* futures were moved in, so these are invalid now */
973 EXPECT_FALSE(anyf.isReady());
975 promises[7].setValue(42);
976 EXPECT_TRUE(anyf.isReady());
977 auto& idx_fut = anyf.value();
979 auto i = idx_fut.first;
982 auto& f = idx_fut.second;
983 EXPECT_EQ(42, f.value());
988 vector<Promise<void>> promises(10);
989 vector<Future<void>> futures;
991 for (auto& p : promises)
992 futures.push_back(p.getFuture());
994 for (auto& f : futures) {
995 EXPECT_FALSE(f.isReady());
998 auto anyf = collectAny(futures);
1000 EXPECT_FALSE(anyf.isReady());
1002 promises[3].setException(eggs);
1003 EXPECT_TRUE(anyf.isReady());
1004 EXPECT_TRUE(anyf.value().second.hasException());
1009 vector<Promise<int>> promises(10);
1010 vector<Future<int>> futures;
1012 for (auto& p : promises)
1013 futures.push_back(p.getFuture());
1015 auto anyf = collectAny(futures)
1016 .then([](pair<size_t, Try<int>> p) {
1017 EXPECT_EQ(42, p.second.value());
1020 promises[3].setValue(42);
1021 EXPECT_TRUE(anyf.isReady());
1026 TEST(when, already_completed) {
1028 vector<Future<void>> fs;
1029 for (int i = 0; i < 10; i++)
1030 fs.push_back(makeFuture());
1033 .then([&](vector<Try<void>> ts) {
1034 EXPECT_EQ(fs.size(), ts.size());
1038 vector<Future<int>> fs;
1039 for (int i = 0; i < 10; i++)
1040 fs.push_back(makeFuture(i));
1043 .then([&](pair<size_t, Try<int>> p) {
1044 EXPECT_EQ(p.first, p.second.value());
1049 TEST(when, collectN) {
1050 vector<Promise<void>> promises(10);
1051 vector<Future<void>> futures;
1053 for (auto& p : promises)
1054 futures.push_back(p.getFuture());
1058 collectN(futures, n)
1059 .then([&](vector<pair<size_t, Try<void>>> v) {
1061 EXPECT_EQ(n, v.size());
1063 EXPECT_TRUE(tt.second.hasValue());
1066 promises[0].setValue();
1068 promises[1].setValue();
1070 promises[2].setValue();
1074 /* Ensure that we can compile when_{all,any} with folly::small_vector */
1075 TEST(when, small_vector) {
1077 static_assert(!FOLLY_IS_TRIVIALLY_COPYABLE(Future<void>),
1078 "Futures should not be trivially copyable");
1079 static_assert(!FOLLY_IS_TRIVIALLY_COPYABLE(Future<int>),
1080 "Futures should not be trivially copyable");
1082 using folly::small_vector;
1084 small_vector<Future<void>> futures;
1086 for (int i = 0; i < 10; i++)
1087 futures.push_back(makeFuture());
1089 auto anyf = collectAny(futures);
1093 small_vector<Future<void>> futures;
1095 for (int i = 0; i < 10; i++)
1096 futures.push_back(makeFuture());
1098 auto allf = collectAll(futures);
1102 TEST(Future, collectAllVariadic) {
1105 Future<bool> fb = pb.getFuture();
1106 Future<int> fi = pi.getFuture();
1108 collectAll(std::move(fb), std::move(fi))
1109 .then([&](std::tuple<Try<bool>, Try<int>> tup) {
1111 EXPECT_TRUE(std::get<0>(tup).hasValue());
1112 EXPECT_EQ(std::get<0>(tup).value(), true);
1113 EXPECT_TRUE(std::get<1>(tup).hasValue());
1114 EXPECT_EQ(std::get<1>(tup).value(), 42);
1122 TEST(Future, collectAllVariadicReferences) {
1125 Future<bool> fb = pb.getFuture();
1126 Future<int> fi = pi.getFuture();
1129 .then([&](std::tuple<Try<bool>, Try<int>> tup) {
1131 EXPECT_TRUE(std::get<0>(tup).hasValue());
1132 EXPECT_EQ(std::get<0>(tup).value(), true);
1133 EXPECT_TRUE(std::get<1>(tup).hasValue());
1134 EXPECT_EQ(std::get<1>(tup).value(), 42);
1142 TEST(Future, collectAll_none) {
1143 vector<Future<int>> fs;
1144 auto f = collectAll(fs);
1145 EXPECT_TRUE(f.isReady());
1148 TEST(Future, throwCaughtInImmediateThen) {
1149 // Neither of these should throw "Promise already satisfied"
1151 [=](Try<void>&&) -> int { throw std::exception(); });
1153 [=](Try<void>&&) -> Future<int> { throw std::exception(); });
1156 TEST(Future, throwIfFailed) {
1157 makeFuture<void>(eggs)
1158 .then([=](Try<void>&& t) {
1159 EXPECT_THROW(t.throwIfFailed(), eggs_t);
1162 .then([=](Try<void>&& t) {
1163 EXPECT_NO_THROW(t.throwIfFailed());
1166 makeFuture<int>(eggs)
1167 .then([=](Try<int>&& t) {
1168 EXPECT_THROW(t.throwIfFailed(), eggs_t);
1171 .then([=](Try<int>&& t) {
1172 EXPECT_NO_THROW(t.throwIfFailed());
1176 TEST(Future, waitImmediate) {
1177 makeFuture().wait();
1178 auto done = makeFuture(42).wait().value();
1179 EXPECT_EQ(42, done);
1181 vector<int> v{1,2,3};
1182 auto done_v = makeFuture(v).wait().value();
1183 EXPECT_EQ(v.size(), done_v.size());
1184 EXPECT_EQ(v, done_v);
1186 vector<Future<void>> v_f;
1187 v_f.push_back(makeFuture());
1188 v_f.push_back(makeFuture());
1189 auto done_v_f = collectAll(v_f).wait().value();
1190 EXPECT_EQ(2, done_v_f.size());
1192 vector<Future<bool>> v_fb;
1193 v_fb.push_back(makeFuture(true));
1194 v_fb.push_back(makeFuture(false));
1195 auto fut = collectAll(v_fb);
1196 auto done_v_fb = std::move(fut.wait().value());
1197 EXPECT_EQ(2, done_v_fb.size());
1200 TEST(Future, wait) {
1202 Future<int> f = p.getFuture();
1203 std::atomic<bool> flag{false};
1204 std::atomic<int> result{1};
1205 std::atomic<std::thread::id> id;
1207 std::thread t([&](Future<int>&& tf){
1208 auto n = tf.then([&](Try<int> && t) {
1209 id = std::this_thread::get_id();
1213 result.store(n.wait().value());
1218 EXPECT_EQ(result.load(), 1);
1221 // validate that the callback ended up executing in this thread, which
1222 // is more to ensure that this test actually tests what it should
1223 EXPECT_EQ(id, std::this_thread::get_id());
1224 EXPECT_EQ(result.load(), 42);
1228 MoveFlag() = default;
1229 MoveFlag(const MoveFlag&) = delete;
1230 MoveFlag(MoveFlag&& other) noexcept {
1236 TEST(Future, waitReplacesSelf) {
1240 auto f1 = makeFuture(MoveFlag());
1242 EXPECT_FALSE(f1.value().moved);
1245 auto f2 = makeFuture(MoveFlag()).wait();
1246 EXPECT_FALSE(f2.value().moved);
1252 auto f1 = makeFuture(MoveFlag());
1253 f1.wait(milliseconds(1));
1254 EXPECT_FALSE(f1.value().moved);
1257 auto f2 = makeFuture(MoveFlag()).wait(milliseconds(1));
1258 EXPECT_FALSE(f2.value().moved);
1263 folly::EventBase eb;
1265 auto f1 = makeFuture(MoveFlag());
1267 EXPECT_FALSE(f1.value().moved);
1270 auto f2 = makeFuture(MoveFlag()).waitVia(&eb);
1271 EXPECT_FALSE(f2.value().moved);
1275 TEST(Future, waitWithDuration) {
1278 Future<int> f = p.getFuture();
1279 f.wait(milliseconds(1));
1280 EXPECT_FALSE(f.isReady());
1282 EXPECT_TRUE(f.isReady());
1286 Future<int> f = p.getFuture();
1288 f.wait(milliseconds(1));
1289 EXPECT_TRUE(f.isReady());
1292 vector<Future<bool>> v_fb;
1293 v_fb.push_back(makeFuture(true));
1294 v_fb.push_back(makeFuture(false));
1295 auto f = collectAll(v_fb);
1296 f.wait(milliseconds(1));
1297 EXPECT_TRUE(f.isReady());
1298 EXPECT_EQ(2, f.value().size());
1301 vector<Future<bool>> v_fb;
1304 v_fb.push_back(p1.getFuture());
1305 v_fb.push_back(p2.getFuture());
1306 auto f = collectAll(v_fb);
1307 f.wait(milliseconds(1));
1308 EXPECT_FALSE(f.isReady());
1310 EXPECT_FALSE(f.isReady());
1312 EXPECT_TRUE(f.isReady());
1315 auto f = makeFuture().wait(milliseconds(1));
1316 EXPECT_TRUE(f.isReady());
1321 auto start = std::chrono::steady_clock::now();
1322 auto f = p.getFuture().wait(milliseconds(100));
1323 auto elapsed = std::chrono::steady_clock::now() - start;
1324 EXPECT_GE(elapsed, milliseconds(100));
1325 EXPECT_FALSE(f.isReady());
1327 EXPECT_TRUE(f.isReady());
1331 // Try to trigger the race where the resultant Future is not yet complete
1332 // even if we didn't hit the timeout, and make sure we deal with it properly
1335 auto t = std::thread([&]{
1337 /* sleep override */ std::this_thread::sleep_for(milliseconds(100));
1341 auto f = p.getFuture().wait(std::chrono::seconds(3600));
1342 EXPECT_TRUE(f.isReady());
1347 class DummyDrivableExecutor : public DrivableExecutor {
1349 void add(Func f) override {}
1350 void drive() override { ran = true; }
1354 TEST(Future, getVia) {
1358 auto f = via(&x).then([]{ return true; });
1359 EXPECT_TRUE(f.getVia(&x));
1365 auto f = via(&x).then();
1370 DummyDrivableExecutor x;
1371 auto f = makeFuture(true);
1372 EXPECT_TRUE(f.getVia(&x));
1373 EXPECT_FALSE(x.ran);
1377 TEST(Future, waitVia) {
1380 auto f = via(&x).then();
1381 EXPECT_FALSE(f.isReady());
1383 EXPECT_TRUE(f.isReady());
1387 // try rvalue as well
1389 auto f = via(&x).then().waitVia(&x);
1390 EXPECT_TRUE(f.isReady());
1394 DummyDrivableExecutor x;
1395 makeFuture(true).waitVia(&x);
1396 EXPECT_FALSE(x.ran);
1400 TEST(Future, viaRaces) {
1403 auto tid = std::this_thread::get_id();
1406 std::thread t1([&] {
1409 .then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
1410 .then([&](Try<void>&&) { EXPECT_EQ(tid, std::this_thread::get_id()); })
1411 .then([&](Try<void>&&) { done = true; });
1414 std::thread t2([&] {
1418 while (!done) x.run();
1423 TEST(Future, getFuture_after_setValue) {
1426 EXPECT_EQ(42, p.getFuture().value());
1429 TEST(Future, getFuture_after_setException) {
1431 p.setWith([]() -> void { throw std::logic_error("foo"); });
1432 EXPECT_THROW(p.getFuture().value(), std::logic_error);
1435 TEST(Future, detachRace) {
1437 // This test is designed to detect a race that was in Core::detachOne()
1438 // where detached_ was incremented and then tested, and that
1439 // allowed a race where both Promise and Future would think they were the
1440 // second and both try to delete. This showed up at scale but was very
1441 // difficult to reliably repro in a test. As it is, this only fails about
1442 // once in every 1,000 executions. Doing this 1,000 times is going to make a
1443 // slow test so I won't do that but if it ever fails, take it seriously, and
1444 // run the test binary with "--gtest_repeat=10000 --gtest_filter=*detachRace"
1445 // (Don't forget to enable ASAN)
1446 auto p = folly::make_unique<Promise<bool>>();
1447 auto f = folly::make_unique<Future<bool>>(p->getFuture());
1448 folly::Baton<> baton;
1458 class TestData : public RequestData {
1460 explicit TestData(int data) : data_(data) {}
1461 virtual ~TestData() {}
1465 TEST(Future, context) {
1467 // Start a new context
1468 RequestContext::create();
1470 EXPECT_EQ(nullptr, RequestContext::get()->getContextData("test"));
1472 // Set some test data
1473 RequestContext::get()->setContextData(
1475 std::unique_ptr<TestData>(new TestData(10)));
1479 auto future = p.getFuture().then([&]{
1480 // Check that the context followed the future
1481 EXPECT_TRUE(RequestContext::get() != nullptr);
1482 auto a = dynamic_cast<TestData*>(
1483 RequestContext::get()->getContextData("test"));
1484 auto data = a->data_;
1485 EXPECT_EQ(10, data);
1488 // Clear the context
1489 RequestContext::setContext(nullptr);
1491 EXPECT_EQ(nullptr, RequestContext::get()->getContextData("test"));
1493 // Fulfill the promise
1498 // This only fails about 1 in 1k times when the bug is present :(
1499 TEST(Future, t5506504) {
1503 auto promises = std::make_shared<vector<Promise<void>>>(4);
1504 vector<Future<void>> futures;
1506 for (auto& p : *promises) {
1507 futures.emplace_back(
1510 .then([](Try<void>&&){}));
1515 for (auto& p : *promises) p.setValue();
1518 return collectAll(futures);
1524 // Test of handling of a circular dependency. It's never recommended
1525 // to have one because of possible memory leaks. Here we test that
1526 // we can handle freeing of the Future while it is running.
1527 TEST(Future, CircularDependencySharedPtrSelfReset) {
1528 Promise<int64_t> promise;
1529 auto ptr = std::make_shared<Future<int64_t>>(promise.getFuture());
1532 [ptr] (folly::Try<int64_t>&& uid) mutable {
1533 EXPECT_EQ(1, ptr.use_count());
1535 // Leaving no references to ourselves.
1537 EXPECT_EQ(0, ptr.use_count());
1541 EXPECT_EQ(2, ptr.use_count());
1545 promise.setWith([]{return 1l;});
1548 TEST(Future, Constructor) {
1549 auto f1 = []() -> Future<int> { return Future<int>(3); }();
1550 EXPECT_EQ(f1.value(), 3);
1551 auto f2 = []() -> Future<void> { return Future<void>(); }();
1552 EXPECT_NO_THROW(f2.value());
1555 TEST(Future, ImplicitConstructor) {
1556 auto f1 = []() -> Future<int> { return 3; }();
1557 EXPECT_EQ(f1.value(), 3);
1558 // Unfortunately, the C++ standard does not allow the
1559 // following implicit conversion to work:
1560 //auto f2 = []() -> Future<void> { }();
1563 TEST(Future, thenDynamic) {
1564 // folly::dynamic has a constructor that takes any T, this test makes
1565 // sure that we call the then lambda with folly::dynamic and not
1566 // Try<folly::dynamic> because that then fails to compile
1567 Promise<folly::dynamic> p;
1568 Future<folly::dynamic> f = p.getFuture().then(
1569 [](const folly::dynamic& d) {
1570 return folly::dynamic(d.asInt() + 3);
1574 EXPECT_EQ(f.get(), 5);
1577 TEST(Future, via_then_get_was_racy) {
1579 std::unique_ptr<int> val = folly::via(&x)
1580 .then([] { return folly::make_unique<int>(42); })
1583 EXPECT_EQ(42, *val);
1586 TEST(Future, ensure) {
1588 auto cob = [&]{ count++; };
1589 auto f = makeFuture(42)
1591 .then([](int) { throw std::runtime_error("ensure"); })
1594 EXPECT_THROW(f.get(), std::runtime_error);
1595 EXPECT_EQ(2, count);
1598 TEST(Future, willEqual) {
1599 //both p1 and p2 already fulfilled
1605 auto f1 = p1.getFuture();
1606 auto f2 = p2.getFuture();
1607 EXPECT_TRUE(f1.willEqual(f2).get());
1613 auto f1 = p1.getFuture();
1614 auto f2 = p2.getFuture();
1615 EXPECT_FALSE(f1.willEqual(f2).get());
1617 //both p1 and p2 not yet fulfilled
1621 auto f1 = p1.getFuture();
1622 auto f2 = p2.getFuture();
1623 auto f3 = f1.willEqual(f2);
1626 EXPECT_TRUE(f3.get());
1630 auto f1 = p1.getFuture();
1631 auto f2 = p2.getFuture();
1632 auto f3 = f1.willEqual(f2);
1635 EXPECT_FALSE(f3.get());
1637 //p1 already fulfilled, p2 not yet fulfilled
1642 auto f1 = p1.getFuture();
1643 auto f2 = p2.getFuture();
1644 auto f3 = f1.willEqual(f2);
1646 EXPECT_TRUE(f3.get());
1651 auto f1 = p1.getFuture();
1652 auto f2 = p2.getFuture();
1653 auto f3 = f1.willEqual(f2);
1655 EXPECT_FALSE(f3.get());
1657 //p2 already fulfilled, p1 not yet fulfilled
1662 auto f1 = p1.getFuture();
1663 auto f2 = p2.getFuture();
1664 auto f3 = f1.willEqual(f2);
1666 EXPECT_TRUE(f3.get());
1671 auto f1 = p1.getFuture();
1672 auto f2 = p2.getFuture();
1673 auto f3 = f1.willEqual(f2);
1675 EXPECT_FALSE(f3.get());
1681 // A simple scenario for the unwrap call, when the promise was fulfilled
1682 // before calling to unwrap.
1683 TEST(Future, Unwrap_SimpleScenario) {
1684 Future<int> encapsulated_future = makeFuture(5484);
1685 Future<Future<int>> future = makeFuture(std::move(encapsulated_future));
1686 EXPECT_EQ(5484, future.unwrap().value());
1689 // Makes sure that unwrap() works when chaning Future's commands.
1690 TEST(Future, Unwrap_ChainCommands) {
1691 Future<Future<int>> future = makeFuture(makeFuture(5484));
1692 auto unwrapped = future.unwrap().then([](int i){ return i; });
1693 EXPECT_EQ(5484, unwrapped.value());
1696 // Makes sure that the unwrap call also works when the promise was not yet
1697 // fulfilled, and that the returned Future<T> becomes ready once the promise
1699 TEST(Future, Unwrap_FutureNotReady) {
1700 Promise<Future<int>> p;
1701 Future<Future<int>> future = p.getFuture();
1702 Future<int> unwrapped = future.unwrap();
1703 // Sanity - should not be ready before the promise is fulfilled.
1704 ASSERT_FALSE(unwrapped.isReady());
1705 // Fulfill the promise and make sure the unwrapped future is now ready.
1706 p.setValue(makeFuture(5484));
1707 ASSERT_TRUE(unwrapped.isReady());
1708 EXPECT_EQ(5484, unwrapped.value());
1711 TEST(Reduce, Basic) {
1712 auto makeFutures = [](int count) {
1713 std::vector<Future<int>> fs;
1714 for (int i = 1; i <= count; ++i) {
1715 fs.emplace_back(makeFuture(i));
1722 auto fs = makeFutures(0);
1724 Future<double> f1 = reduce(fs, 1.2,
1725 [](double a, Try<int>&& b){
1726 return a + *b + 0.1;
1728 EXPECT_EQ(1.2, f1.get());
1733 auto fs = makeFutures(1);
1735 Future<double> f1 = reduce(fs, 0.0,
1736 [](double a, Try<int>&& b){
1737 return a + *b + 0.1;
1739 EXPECT_EQ(1.1, f1.get());
1742 // Returning values (Try)
1744 auto fs = makeFutures(3);
1746 Future<double> f1 = reduce(fs, 0.0,
1747 [](double a, Try<int>&& b){
1748 return a + *b + 0.1;
1750 EXPECT_EQ(6.3, f1.get());
1755 auto fs = makeFutures(3);
1757 Future<double> f1 = reduce(fs, 0.0,
1758 [](double a, int&& b){
1761 EXPECT_EQ(6.3, f1.get());
1764 // Returning futures (Try)
1766 auto fs = makeFutures(3);
1768 Future<double> f2 = reduce(fs, 0.0,
1769 [](double a, Try<int>&& b){
1770 return makeFuture<double>(a + *b + 0.1);
1772 EXPECT_EQ(6.3, f2.get());
1775 // Returning futures
1777 auto fs = makeFutures(3);
1779 Future<double> f2 = reduce(fs, 0.0,
1780 [](double a, int&& b){
1781 return makeFuture<double>(a + b + 0.1);
1783 EXPECT_EQ(6.3, f2.get());
1787 TEST(Reduce, Chain) {
1788 auto makeFutures = [](int count) {
1789 std::vector<Future<int>> fs;
1790 for (int i = 1; i <= count; ++i) {
1791 fs.emplace_back(makeFuture(i));
1797 auto f = collectAll(makeFutures(3)).reduce(0, [](int a, Try<int>&& b){
1800 EXPECT_EQ(6, f.get());
1803 auto f = collect(makeFutures(3)).reduce(0, [](int a, int&& b){
1806 EXPECT_EQ(6, f.get());
1815 std::vector<Future<int>> fs;
1816 fs.push_back(p1.getFuture());
1817 fs.push_back(p2.getFuture());
1818 fs.push_back(p3.getFuture());
1821 std::vector<Future<void>> fs2 = futures::map(fs, [&](int i){
1825 // Ensure we call the callbacks as the futures complete regardless of order
1833 EXPECT_TRUE(collect(fs2).isReady());