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 <gtest/gtest.h>
19 #include <folly/futures/Future.h>
21 using namespace folly;
24 auto makeFutures = [](int count) {
25 std::vector<Future<int>> fs;
26 for (int i = 1; i <= count; ++i) {
27 fs.emplace_back(makeFuture(i));
34 auto fs = makeFutures(0);
36 Future<double> f1 = reduce(fs, 1.2,
37 [](double a, Try<int>&& b){
40 EXPECT_EQ(1.2, f1.get());
45 auto fs = makeFutures(1);
47 Future<double> f1 = reduce(fs, 0.0,
48 [](double a, Try<int>&& b){
51 EXPECT_EQ(1.1, f1.get());
54 // Returning values (Try)
56 auto fs = makeFutures(3);
58 Future<double> f1 = reduce(fs, 0.0,
59 [](double a, Try<int>&& b){
62 EXPECT_EQ(6.3, f1.get());
67 auto fs = makeFutures(3);
69 Future<double> f1 = reduce(fs, 0.0,
70 [](double a, int&& b){
73 EXPECT_EQ(6.3, f1.get());
76 // Returning futures (Try)
78 auto fs = makeFutures(3);
80 Future<double> f2 = reduce(fs, 0.0,
81 [](double a, Try<int>&& b){
82 return makeFuture<double>(a + *b + 0.1);
84 EXPECT_EQ(6.3, f2.get());
89 auto fs = makeFutures(3);
91 Future<double> f2 = reduce(fs, 0.0,
92 [](double a, int&& b){
93 return makeFuture<double>(a + b + 0.1);
95 EXPECT_EQ(6.3, f2.get());
100 auto makeFutures = [](int count) {
101 std::vector<Future<int>> fs;
102 for (int i = 1; i <= count; ++i) {
103 fs.emplace_back(makeFuture(i));
109 auto f = collectAll(makeFutures(3)).reduce(0, [](int a, Try<int>&& b){
112 EXPECT_EQ(6, f.get());
115 auto f = collect(makeFutures(3)).reduce(0, [](int a, int&& b){
118 EXPECT_EQ(6, f.get());
122 TEST(Reduce, unorderedReduce) {
124 std::vector<Future<int>> fs;
125 fs.push_back(makeFuture(1));
126 fs.push_back(makeFuture(2));
127 fs.push_back(makeFuture(3));
130 unorderedReduce(fs.begin(),
133 [](double /* a */, int&& b) { return double(b); });
134 EXPECT_EQ(3.0, f.get());
141 std::vector<Future<int>> fs;
142 fs.push_back(p1.getFuture());
143 fs.push_back(p2.getFuture());
144 fs.push_back(p3.getFuture());
147 unorderedReduce(fs.begin(),
150 [](double /* a */, int&& b) { return double(b); });
154 EXPECT_EQ(1.0, f.get());
158 TEST(Reduce, unorderedReduceException) {
163 std::vector<Future<int>> fs;
164 fs.push_back(p1.getFuture());
165 fs.push_back(p2.getFuture());
166 fs.push_back(p3.getFuture());
169 unorderedReduce(fs.begin(),
172 [](double /* a */, int&& b) { return b + 0.0; });
174 p2.setException(exception_wrapper(std::runtime_error("blah")));
176 EXPECT_THROW(f.get(), std::runtime_error);