2 * Copyright 2017 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::ScopeGuard;
27 using folly::makeGuard;
30 double returnsDouble() {
36 explicit MyFunctor(int* ptr) : ptr_(ptr) {}
46 TEST(ScopeGuard, DifferentWaysToBind) {
48 // There is implicit conversion from func pointer
49 // double (*)() to function<void()>.
50 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));
63 EXPECT_EQ(0, v.size());
66 // bind member function with args. v is passed-by-value!
67 ScopeGuard g = makeGuard(std::bind(push_back, v, 2));
70 EXPECT_EQ(0, v.size()); // push_back happened on a copy of v... fail!
72 // pass in an argument by pointer so to avoid copy.
74 ScopeGuard g = makeGuard(std::bind(push_back, &v, 4));
77 EXPECT_EQ(1, v.size());
80 // pass in an argument by reference so to avoid copy.
81 ScopeGuard g = makeGuard(std::bind(push_back, std::ref(v), 4));
84 EXPECT_EQ(2, v.size());
86 // lambda with a reference to v
88 ScopeGuard g = makeGuard([&] { v.push_back(5); });
91 EXPECT_EQ(3, v.size());
93 // lambda with a copy of v
95 ScopeGuard g = makeGuard([v] () mutable { v.push_back(6); });
98 EXPECT_EQ(3, v.size());
104 ScopeGuard g = makeGuard(f);
109 // temporary functor object
112 ScopeGuard g = makeGuard(MyFunctor(&n));
117 // Use auto instead of ScopeGuard
120 auto g = makeGuard(MyFunctor(&n));
125 // Use const auto& instead of ScopeGuard
128 const auto& g = makeGuard(MyFunctor(&n));
134 TEST(ScopeGuard, GuardException) {
136 ScopeGuard g = makeGuard([&] {
137 throw std::runtime_error("destructors should never throw!");
141 "destructors should never throw!"
146 * Add an integer to a vector iff it was inserted into the
147 * db successfuly. Here is a schematic of how you would accomplish
148 * this with scope guard.
150 void testUndoAction(bool failure) {
152 { // defines a "mini" scope
154 // be optimistic and insert this into memory
157 // The guard is triggered to undo the insertion unless dismiss() is called.
158 ScopeGuard guard = makeGuard([&] { v.pop_back(); });
160 // Do some action; Use the failure argument to pretend
161 // if it failed or succeeded.
163 // if there was no failure, dismiss the undo guard action.
167 } // all stack allocated in the mini-scope will be destroyed here.
170 EXPECT_EQ(0, v.size()); // the action failed => undo insertion
172 EXPECT_EQ(1, v.size()); // the action succeeded => keep insertion
176 TEST(ScopeGuard, UndoAction) {
177 testUndoAction(true);
178 testUndoAction(false);
182 * Sometimes in a try catch block we want to execute a piece of code
183 * regardless if an exception happened or not. For example, you want
184 * to close a db connection regardless if an exception was thrown during
185 * insertion. In Java and other languages there is a finally clause that
186 * helps accomplish this:
189 * dbConn.doInsert(sql);
190 * } catch (const DbException& dbe) {
191 * dbConn.recordFailure(dbe);
192 * } catch (const CriticalException& e) {
193 * throw e; // re-throw the exception
195 * dbConn.closeConnection(); // executes no matter what!
198 * We can approximate this behavior in C++ with ScopeGuard.
200 enum class ErrorBehavior {
206 void testFinally(ErrorBehavior error) {
207 bool cleanupOccurred = false;
210 ScopeGuard guard = makeGuard([&] { cleanupOccurred = true; });
214 if (error == ErrorBehavior::HANDLED_ERROR) {
215 throw std::runtime_error("throwing an expected error");
216 } else if (error == ErrorBehavior::UNHANDLED_ERROR) {
217 throw "never throw raw strings";
219 } catch (const std::runtime_error&) {
222 // Outer catch to swallow the error for the UNHANDLED_ERROR behavior
225 EXPECT_TRUE(cleanupOccurred);
228 TEST(ScopeGuard, TryCatchFinally) {
229 testFinally(ErrorBehavior::SUCCESS);
230 testFinally(ErrorBehavior::HANDLED_ERROR);
231 testFinally(ErrorBehavior::UNHANDLED_ERROR);
234 TEST(ScopeGuard, TEST_SCOPE_EXIT) {
248 auto e = std::current_exception();
251 SCOPE_EXIT { ++test; };
255 } catch (const std::exception& ex) {
256 LOG(FATAL) << "Unexpected exception: " << ex.what();
261 TEST(ScopeGuard, TEST_SCOPE_FAILURE2) {
264 throw std::runtime_error("test");
269 void testScopeFailAndScopeSuccess(ErrorBehavior error, bool expectFail) {
270 bool scopeFailExecuted = false;
271 bool scopeSuccessExecuted = false;
274 SCOPE_FAIL { scopeFailExecuted = true; };
275 SCOPE_SUCCESS { scopeSuccessExecuted = true; };
278 if (error == ErrorBehavior::HANDLED_ERROR) {
279 throw std::runtime_error("throwing an expected error");
280 } else if (error == ErrorBehavior::UNHANDLED_ERROR) {
281 throw "never throw raw strings";
283 } catch (const std::runtime_error&) {
286 // Outer catch to swallow the error for the UNHANDLED_ERROR behavior
289 EXPECT_EQ(expectFail, scopeFailExecuted);
290 EXPECT_EQ(!expectFail, scopeSuccessExecuted);
293 TEST(ScopeGuard, TEST_SCOPE_FAIL_AND_SCOPE_SUCCESS) {
294 testScopeFailAndScopeSuccess(ErrorBehavior::SUCCESS, false);
295 testScopeFailAndScopeSuccess(ErrorBehavior::HANDLED_ERROR, false);
296 testScopeFailAndScopeSuccess(ErrorBehavior::UNHANDLED_ERROR, true);
299 TEST(ScopeGuard, TEST_SCOPE_SUCCESS_THROW) {
301 SCOPE_SUCCESS { throw std::runtime_error("ehm"); };
303 EXPECT_THROW(lambda(), std::runtime_error);
306 TEST(ScopeGuard, TEST_THROWING_CLEANUP_ACTION) {
307 struct ThrowingCleanupAction {
308 explicit ThrowingCleanupAction(int& scopeExitExecuted)
309 : scopeExitExecuted_(scopeExitExecuted) {}
311 ThrowingCleanupAction(const ThrowingCleanupAction& other)
312 : scopeExitExecuted_(other.scopeExitExecuted_) {
313 throw std::runtime_error("whoa");
315 void operator()() { ++scopeExitExecuted_; }
318 int& scopeExitExecuted_;
320 int scopeExitExecuted = 0;
321 ThrowingCleanupAction onExit(scopeExitExecuted);
322 EXPECT_THROW(makeGuard(onExit), std::runtime_error);
323 EXPECT_EQ(scopeExitExecuted, 1);