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(WhileDo, success) {
65 std::queue<std::shared_ptr<Promise<Unit>>> ps;
69 bool complete = false;
72 auto pred = makePred(i);
73 auto thunk = makeThunk(ps, interrupt, ps_mutex);
74 auto f = folly::whileDo(pred, thunk)
75 .then([&]() mutable { complete = true; })
76 .onError([&] (FutureException& e) { failure = true; });
78 popAndFulfillPromise(ps, ps_mutex);
79 EXPECT_FALSE(complete);
80 EXPECT_FALSE(failure);
82 popAndFulfillPromise(ps, ps_mutex);
83 EXPECT_FALSE(complete);
84 EXPECT_FALSE(failure);
86 popAndFulfillPromise(ps, ps_mutex);
87 EXPECT_TRUE(f.isReady());
88 EXPECT_TRUE(complete);
89 EXPECT_FALSE(failure);
92 TEST(WhileDo, failure) {
93 std::queue<std::shared_ptr<Promise<Unit>>> ps;
97 bool complete = false;
100 auto pred = makePred(i);
101 auto thunk = makeThunk(ps, interrupt, ps_mutex);
102 auto f = folly::whileDo(pred, thunk)
103 .then([&]() mutable { complete = true; })
104 .onError([&] (FutureException& e) { failure = true; });
106 popAndFulfillPromise(ps, ps_mutex);
107 EXPECT_FALSE(complete);
108 EXPECT_FALSE(failure);
111 auto p2 = ps.front();
114 FutureException eggs("eggs");
115 p2->setException(eggs);
117 EXPECT_TRUE(f.isReady());
118 EXPECT_FALSE(complete);
119 EXPECT_TRUE(failure);
122 TEST(WhileDo, interrupt) {
123 std::queue<std::shared_ptr<Promise<Unit>>> ps;
127 bool complete = false;
128 bool failure = false;
130 auto pred = makePred(i);
131 auto thunk = makeThunk(ps, interrupt, ps_mutex);
132 auto f = folly::whileDo(pred, thunk)
133 .then([&]() mutable { complete = true; })
134 .onError([&] (FutureException& e) { failure = true; });
136 EXPECT_EQ(0, interrupt);
138 FutureException eggs("eggs");
141 for (int i = 1; i <= 3; ++i) {
142 EXPECT_EQ(1, interrupt);
143 popAndFulfillPromise(ps, ps_mutex);