2 * Copyright 2011-present 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 <folly/ScopeGuard.h>
19 #include <glog/logging.h>
24 #include <folly/portability/GTest.h>
26 using folly::makeGuard;
29 double returnsDouble() {
35 explicit MyFunctor(int* ptr) : ptr_(ptr) {}
45 TEST(ScopeGuard, DifferentWaysToBind) {
47 // There is implicit conversion from func pointer
48 // double (*)() to function<void()>.
49 auto g = makeGuard(returnsDouble);
54 void (vector<int>::*push_back)(int const&) = &vector<int>::push_back;
58 // binding to member function.
59 auto g = makeGuard(std::bind(&vector<int>::pop_back, &v));
62 EXPECT_EQ(0, v.size());
65 // bind member function with args. v is passed-by-value!
66 auto g = makeGuard(std::bind(push_back, v, 2));
69 EXPECT_EQ(0, v.size()); // push_back happened on a copy of v... fail!
71 // pass in an argument by pointer so to avoid copy.
73 auto g = makeGuard(std::bind(push_back, &v, 4));
76 EXPECT_EQ(1, v.size());
79 // pass in an argument by reference so to avoid copy.
80 auto g = makeGuard(std::bind(push_back, std::ref(v), 4));
83 EXPECT_EQ(2, v.size());
85 // lambda with a reference to v
87 auto g = makeGuard([&] { v.push_back(5); });
90 EXPECT_EQ(3, v.size());
92 // lambda with a copy of v
94 auto g = makeGuard([v]() mutable { v.push_back(6); });
97 EXPECT_EQ(3, v.size());
103 auto g = makeGuard(f);
108 // temporary functor object
111 auto g = makeGuard(MyFunctor(&n));
116 // Use auto instead of ScopeGuard
119 auto g = makeGuard(MyFunctor(&n));
124 // Use const auto& instead of ScopeGuard
127 const auto& g = makeGuard(MyFunctor(&n));
133 TEST(ScopeGuard, GuardException) {
135 makeGuard([] { throw std::runtime_error("dtors should never throw!"); }),
136 "dtors should never throw!");
140 * Add an integer to a vector iff it was inserted into the
141 * db successfuly. Here is a schematic of how you would accomplish
142 * this with scope guard.
144 void testUndoAction(bool failure) {
146 { // defines a "mini" scope
148 // be optimistic and insert this into memory
151 // The guard is triggered to undo the insertion unless dismiss() is called.
152 auto guard = makeGuard([&] { v.pop_back(); });
154 // Do some action; Use the failure argument to pretend
155 // if it failed or succeeded.
157 // if there was no failure, dismiss the undo guard action.
161 } // all stack allocated in the mini-scope will be destroyed here.
164 EXPECT_EQ(0, v.size()); // the action failed => undo insertion
166 EXPECT_EQ(1, v.size()); // the action succeeded => keep insertion
170 TEST(ScopeGuard, UndoAction) {
171 testUndoAction(true);
172 testUndoAction(false);
176 * Sometimes in a try catch block we want to execute a piece of code
177 * regardless if an exception happened or not. For example, you want
178 * to close a db connection regardless if an exception was thrown during
179 * insertion. In Java and other languages there is a finally clause that
180 * helps accomplish this:
183 * dbConn.doInsert(sql);
184 * } catch (const DbException& dbe) {
185 * dbConn.recordFailure(dbe);
186 * } catch (const CriticalException& e) {
187 * throw e; // re-throw the exception
189 * dbConn.closeConnection(); // executes no matter what!
192 * We can approximate this behavior in C++ with ScopeGuard.
194 enum class ErrorBehavior {
200 void testFinally(ErrorBehavior error) {
201 bool cleanupOccurred = false;
204 auto guard = makeGuard([&] { cleanupOccurred = true; });
208 if (error == ErrorBehavior::HANDLED_ERROR) {
209 throw std::runtime_error("throwing an expected error");
210 } else if (error == ErrorBehavior::UNHANDLED_ERROR) {
211 throw "never throw raw strings";
213 } catch (const std::runtime_error&) {
216 // Outer catch to swallow the error for the UNHANDLED_ERROR behavior
219 EXPECT_TRUE(cleanupOccurred);
222 TEST(ScopeGuard, TryCatchFinally) {
223 testFinally(ErrorBehavior::SUCCESS);
224 testFinally(ErrorBehavior::HANDLED_ERROR);
225 testFinally(ErrorBehavior::UNHANDLED_ERROR);
228 TEST(ScopeGuard, TEST_SCOPE_EXIT) {
242 auto e = std::current_exception();
245 SCOPE_EXIT { ++test; };
249 } catch (const std::exception& ex) {
250 LOG(FATAL) << "Unexpected exception: " << ex.what();
255 TEST(ScopeGuard, TEST_SCOPE_FAILURE2) {
258 throw std::runtime_error("test");
263 void testScopeFailAndScopeSuccess(ErrorBehavior error, bool expectFail) {
264 bool scopeFailExecuted = false;
265 bool scopeSuccessExecuted = false;
268 SCOPE_FAIL { scopeFailExecuted = true; };
269 SCOPE_SUCCESS { scopeSuccessExecuted = true; };
272 if (error == ErrorBehavior::HANDLED_ERROR) {
273 throw std::runtime_error("throwing an expected error");
274 } else if (error == ErrorBehavior::UNHANDLED_ERROR) {
275 throw "never throw raw strings";
277 } catch (const std::runtime_error&) {
280 // Outer catch to swallow the error for the UNHANDLED_ERROR behavior
283 EXPECT_EQ(expectFail, scopeFailExecuted);
284 EXPECT_EQ(!expectFail, scopeSuccessExecuted);
287 TEST(ScopeGuard, TEST_SCOPE_FAIL_AND_SCOPE_SUCCESS) {
288 testScopeFailAndScopeSuccess(ErrorBehavior::SUCCESS, false);
289 testScopeFailAndScopeSuccess(ErrorBehavior::HANDLED_ERROR, false);
290 testScopeFailAndScopeSuccess(ErrorBehavior::UNHANDLED_ERROR, true);
293 TEST(ScopeGuard, TEST_SCOPE_SUCCESS_THROW) {
295 SCOPE_SUCCESS { throw std::runtime_error("ehm"); };
297 EXPECT_THROW(lambda(), std::runtime_error);
300 TEST(ScopeGuard, TEST_THROWING_CLEANUP_ACTION) {
301 struct ThrowingCleanupAction {
302 explicit ThrowingCleanupAction(int& scopeExitExecuted)
303 : scopeExitExecuted_(scopeExitExecuted) {}
305 ThrowingCleanupAction(const ThrowingCleanupAction& other)
306 : scopeExitExecuted_(other.scopeExitExecuted_) {
307 throw std::runtime_error("whoa");
309 void operator()() { ++scopeExitExecuted_; }
312 int& scopeExitExecuted_;
314 int scopeExitExecuted = 0;
315 ThrowingCleanupAction onExit(scopeExitExecuted);
316 EXPECT_THROW(makeGuard(onExit), std::runtime_error);
317 EXPECT_EQ(scopeExitExecuted, 1);