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 <folly/ScopeGuard.h>
18 #include <folly/Portability.h>
20 #include <glog/logging.h>
25 #include <folly/portability/GTest.h>
27 using folly::ScopeGuard;
28 using folly::makeGuard;
31 double returnsDouble() {
37 explicit MyFunctor(int* ptr) : ptr_(ptr) {}
47 TEST(ScopeGuard, DifferentWaysToBind) {
49 // There is implicit conversion from func pointer
50 // double (*)() to function<void()>.
51 ScopeGuard g = makeGuard(returnsDouble);
55 void (vector<int>::*push_back)(int const&) = &vector<int>::push_back;
59 // binding to member function.
60 ScopeGuard 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 ScopeGuard g = makeGuard(std::bind(push_back, v, 2));
68 EXPECT_EQ(0, v.size()); // push_back happened on a copy of v... fail!
70 // pass in an argument by pointer so to avoid copy.
72 ScopeGuard g = makeGuard(std::bind(push_back, &v, 4));
74 EXPECT_EQ(1, v.size());
77 // pass in an argument by reference so to avoid copy.
78 ScopeGuard g = makeGuard(std::bind(push_back, std::ref(v), 4));
80 EXPECT_EQ(2, v.size());
82 // lambda with a reference to v
84 ScopeGuard g = makeGuard([&] { v.push_back(5); });
86 EXPECT_EQ(3, v.size());
88 // lambda with a copy of v
90 ScopeGuard g = makeGuard([v] () mutable { v.push_back(6); });
92 EXPECT_EQ(3, v.size());
98 ScopeGuard g = makeGuard(f);
102 // temporary functor object
105 ScopeGuard g = makeGuard(MyFunctor(&n));
109 // Use auto instead of ScopeGuard
112 auto g = makeGuard(MyFunctor(&n));
116 // Use const auto& instead of ScopeGuard
119 const auto& g = makeGuard(MyFunctor(&n));
124 TEST(ScopeGuard, GuardException) {
126 ScopeGuard g = makeGuard([&] {
127 throw std::runtime_error("destructors should never throw!");
130 "destructors should never throw!"
135 * Add an integer to a vector iff it was inserted into the
136 * db successfuly. Here is a schematic of how you would accomplish
137 * this with scope guard.
139 void testUndoAction(bool failure) {
141 { // defines a "mini" scope
143 // be optimistic and insert this into memory
146 // The guard is triggered to undo the insertion unless dismiss() is called.
147 ScopeGuard guard = makeGuard([&] { v.pop_back(); });
149 // Do some action; Use the failure argument to pretend
150 // if it failed or succeeded.
152 // if there was no failure, dismiss the undo guard action.
156 } // all stack allocated in the mini-scope will be destroyed here.
159 EXPECT_EQ(0, v.size()); // the action failed => undo insertion
161 EXPECT_EQ(1, v.size()); // the action succeeded => keep insertion
165 TEST(ScopeGuard, UndoAction) {
166 testUndoAction(true);
167 testUndoAction(false);
171 * Sometimes in a try catch block we want to execute a piece of code
172 * regardless if an exception happened or not. For example, you want
173 * to close a db connection regardless if an exception was thrown during
174 * insertion. In Java and other languages there is a finally clause that
175 * helps accomplish this:
178 * dbConn.doInsert(sql);
179 * } catch (const DbException& dbe) {
180 * dbConn.recordFailure(dbe);
181 * } catch (const CriticalException& e) {
182 * throw e; // re-throw the exception
184 * dbConn.closeConnection(); // executes no matter what!
187 * We can approximate this behavior in C++ with ScopeGuard.
189 enum class ErrorBehavior {
195 void testFinally(ErrorBehavior error) {
196 bool cleanupOccurred = false;
199 ScopeGuard guard = makeGuard([&] { cleanupOccurred = true; });
202 if (error == ErrorBehavior::HANDLED_ERROR) {
203 throw std::runtime_error("throwing an expected error");
204 } else if (error == ErrorBehavior::UNHANDLED_ERROR) {
205 throw "never throw raw strings";
207 } catch (const std::runtime_error&) {
210 // Outer catch to swallow the error for the UNHANDLED_ERROR behavior
213 EXPECT_TRUE(cleanupOccurred);
216 TEST(ScopeGuard, TryCatchFinally) {
217 testFinally(ErrorBehavior::SUCCESS);
218 testFinally(ErrorBehavior::HANDLED_ERROR);
219 testFinally(ErrorBehavior::UNHANDLED_ERROR);
222 TEST(ScopeGuard, TEST_SCOPE_EXIT) {
236 auto e = std::current_exception();
239 SCOPE_EXIT { ++test; };
243 } catch (const std::exception& ex) {
244 LOG(FATAL) << "Unexpected exception: " << ex.what();
249 TEST(ScopeGuard, TEST_SCOPE_FAILURE2) {
252 throw std::runtime_error("test");
257 void testScopeFailAndScopeSuccess(ErrorBehavior error, bool expectFail) {
258 bool scopeFailExecuted = false;
259 bool scopeSuccessExecuted = false;
262 SCOPE_FAIL { scopeFailExecuted = true; };
263 SCOPE_SUCCESS { scopeSuccessExecuted = true; };
266 if (error == ErrorBehavior::HANDLED_ERROR) {
267 throw std::runtime_error("throwing an expected error");
268 } else if (error == ErrorBehavior::UNHANDLED_ERROR) {
269 throw "never throw raw strings";
271 } catch (const std::runtime_error&) {
274 // Outer catch to swallow the error for the UNHANDLED_ERROR behavior
277 EXPECT_EQ(expectFail, scopeFailExecuted);
278 EXPECT_EQ(!expectFail, scopeSuccessExecuted);
281 TEST(ScopeGuard, TEST_SCOPE_FAIL_AND_SCOPE_SUCCESS) {
282 testScopeFailAndScopeSuccess(ErrorBehavior::SUCCESS, false);
283 testScopeFailAndScopeSuccess(ErrorBehavior::HANDLED_ERROR, false);
284 testScopeFailAndScopeSuccess(ErrorBehavior::UNHANDLED_ERROR, true);
287 TEST(ScopeGuard, TEST_SCOPE_SUCCESS_THROW) {
289 SCOPE_SUCCESS { throw std::runtime_error("ehm"); };
291 EXPECT_THROW(lambda(), std::runtime_error);
294 TEST(ScopeGuard, TEST_THROWING_CLEANUP_ACTION) {
295 struct ThrowingCleanupAction {
296 explicit ThrowingCleanupAction(int& scopeExitExecuted)
297 : scopeExitExecuted_(scopeExitExecuted) {}
298 ThrowingCleanupAction(const ThrowingCleanupAction& other)
299 : scopeExitExecuted_(other.scopeExitExecuted_) {
300 throw std::runtime_error("whoa");
302 void operator()() { ++scopeExitExecuted_; }
305 int& scopeExitExecuted_;
307 int scopeExitExecuted = 0;
308 ThrowingCleanupAction onExit(scopeExitExecuted);
309 EXPECT_THROW(makeGuard(onExit), std::runtime_error);
310 EXPECT_EQ(scopeExitExecuted, 1);