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.
21 #include <gtest/gtest.h>
22 #include <glog/logging.h>
24 #include <folly/futures/Future.h>
25 #include <folly/futures/Promise.h>
27 using namespace folly;
29 inline void popAndFulfillPromise(
30 std::queue<std::shared_ptr<Promise<Unit>>>& ps,
31 std::mutex& ps_mutex) {
39 inline std::function<Future<Unit>(void)> makeThunk(
40 std::queue<std::shared_ptr<Promise<Unit>>>& ps,
42 std::mutex& ps_mutex) {
43 return [&]() mutable {
44 auto p = std::make_shared<Promise<Unit>>();
45 p->setInterruptHandler([&](exception_wrapper const& e) {
52 return p->getFuture();
56 inline std::function<bool(void)> makePred(int& i) {
64 TEST(Times, success) {
65 std::queue<std::shared_ptr<Promise<Unit>>> ps;
68 bool complete = false;
71 auto thunk = makeThunk(ps, interrupt, ps_mutex);
72 auto f = folly::times(3, thunk)
73 .then([&]() mutable { complete = true; })
74 .onError([&] (FutureException& e) { failure = true; });
76 popAndFulfillPromise(ps, ps_mutex);
77 EXPECT_FALSE(complete);
78 EXPECT_FALSE(failure);
80 popAndFulfillPromise(ps, ps_mutex);
81 EXPECT_FALSE(complete);
82 EXPECT_FALSE(failure);
84 popAndFulfillPromise(ps, ps_mutex);
85 EXPECT_TRUE(f.isReady());
86 EXPECT_TRUE(complete);
87 EXPECT_FALSE(failure);
90 TEST(Times, failure) {
91 std::queue<std::shared_ptr<Promise<Unit>>> ps;
94 bool complete = false;
97 auto thunk = makeThunk(ps, interrupt, ps_mutex);
98 auto f = folly::times(3, thunk)
99 .then([&]() mutable { complete = true; })
100 .onError([&] (FutureException& e) { failure = true; });
102 popAndFulfillPromise(ps, ps_mutex);
103 EXPECT_FALSE(complete);
104 EXPECT_FALSE(failure);
107 auto p2 = ps.front();
110 FutureException eggs("eggs");
111 p2->setException(eggs);
113 EXPECT_TRUE(f.isReady());
114 EXPECT_FALSE(complete);
115 EXPECT_TRUE(failure);
118 TEST(Times, interrupt) {
119 std::queue<std::shared_ptr<Promise<Unit>>> ps;
122 bool complete = false;
123 bool failure = false;
125 auto thunk = makeThunk(ps, interrupt, ps_mutex);
126 auto f = folly::times(3, thunk)
127 .then([&]() mutable { complete = true; })
128 .onError([&] (FutureException& e) { failure = true; });
130 EXPECT_EQ(0, interrupt);
132 FutureException eggs("eggs");
135 for (int i = 1; i <= 3; ++i) {
136 EXPECT_EQ(1, interrupt);
137 popAndFulfillPromise(ps, ps_mutex);