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.
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(
46 [&](exception_wrapper const& /* e */) { ++interrupt; });
51 return p->getFuture();
55 inline std::function<bool(void)> makePred(int& i) {
63 TEST(Times, success) {
64 std::queue<std::shared_ptr<Promise<Unit>>> ps;
67 bool complete = false;
70 auto thunk = makeThunk(ps, interrupt, ps_mutex);
71 auto f = folly::times(3, thunk).then([&]() mutable {
73 }).onError([&](FutureException& /* e */) { failure = true; });
75 popAndFulfillPromise(ps, ps_mutex);
76 EXPECT_FALSE(complete);
77 EXPECT_FALSE(failure);
79 popAndFulfillPromise(ps, ps_mutex);
80 EXPECT_FALSE(complete);
81 EXPECT_FALSE(failure);
83 popAndFulfillPromise(ps, ps_mutex);
84 EXPECT_TRUE(f.isReady());
85 EXPECT_TRUE(complete);
86 EXPECT_FALSE(failure);
89 TEST(Times, failure) {
90 std::queue<std::shared_ptr<Promise<Unit>>> ps;
93 bool complete = false;
96 auto thunk = makeThunk(ps, interrupt, ps_mutex);
97 auto f = folly::times(3, thunk).then([&]() mutable {
99 }).onError([&](FutureException& /* e */) { failure = true; });
101 popAndFulfillPromise(ps, ps_mutex);
102 EXPECT_FALSE(complete);
103 EXPECT_FALSE(failure);
106 auto p2 = ps.front();
109 FutureException eggs("eggs");
110 p2->setException(eggs);
112 EXPECT_TRUE(f.isReady());
113 EXPECT_FALSE(complete);
114 EXPECT_TRUE(failure);
117 TEST(Times, interrupt) {
118 std::queue<std::shared_ptr<Promise<Unit>>> ps;
121 bool complete = false;
122 bool failure = false;
124 auto thunk = makeThunk(ps, interrupt, ps_mutex);
125 auto f = folly::times(3, thunk).then([&]() mutable {
127 }).onError([&](FutureException& /* e */) { failure = true; });
129 EXPECT_EQ(0, interrupt);
131 FutureException eggs("eggs");
134 for (int i = 1; i <= 3; ++i) {
135 EXPECT_EQ(1, interrupt);
136 popAndFulfillPromise(ps, ps_mutex);