2 * Copyright 2013 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 <gflags/gflags.h>
21 #include <gtest/gtest.h>
22 #include <glog/logging.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!");
131 "terminate called throwing an exception"
133 "destructors should never throw"
139 * Add an integer to a vector iff it was inserted into the
140 * db successfuly. Here is a schematic of how you would accomplish
141 * this with scope guard.
143 void testUndoAction(bool failure) {
145 { // defines a "mini" scope
147 // be optimistic and insert this into memory
150 // The guard is triggered to undo the insertion unless dismiss() is called.
151 ScopeGuard guard = makeGuard([&] { v.pop_back(); });
153 // Do some action; Use the failure argument to pretend
154 // if it failed or succeeded.
156 // if there was no failure, dismiss the undo guard action.
160 } // all stack allocated in the mini-scope will be destroyed here.
163 EXPECT_EQ(0, v.size()); // the action failed => undo insertion
165 EXPECT_EQ(1, v.size()); // the action succeeded => keep insertion
169 TEST(ScopeGuard, UndoAction) {
170 testUndoAction(true);
171 testUndoAction(false);
175 * Sometimes in a try catch block we want to execute a piece of code
176 * regardless if an exception happened or not. For example, you want
177 * to close a db connection regardless if an exception was thrown during
178 * insertion. In Java and other languages there is a finally clause that
179 * helps accomplish this:
182 * dbConn.doInsert(sql);
183 * } catch (const DbException& dbe) {
184 * dbConn.recordFailure(dbe);
185 * } catch (const CriticalException& e) {
186 * throw e; // re-throw the exception
188 * dbConn.closeConnection(); // executes no matter what!
191 * We can approximate this behavior in C++ with ScopeGuard.
193 enum class ErrorBehavior {
199 void testFinally(ErrorBehavior error) {
200 bool cleanupOccurred = false;
203 ScopeGuard guard = makeGuard([&] { cleanupOccurred = true; });
206 if (error == ErrorBehavior::HANDLED_ERROR) {
207 throw std::runtime_error("throwing an expected error");
208 } else if (error == ErrorBehavior::UNHANDLED_ERROR) {
209 throw "never throw raw strings";
211 } catch (const std::runtime_error&) {
214 // Outer catch to swallow the error for the UNHANDLED_ERROR behavior
217 EXPECT_TRUE(cleanupOccurred);
220 TEST(ScopeGuard, TryCatchFinally) {
221 testFinally(ErrorBehavior::SUCCESS);
222 testFinally(ErrorBehavior::HANDLED_ERROR);
223 testFinally(ErrorBehavior::UNHANDLED_ERROR);
226 TEST(ScopeGuard, TEST_SCOPE_EXIT) {
240 auto e = std::current_exception();
243 SCOPE_EXIT { ++test; };
247 } catch (const std::exception& ex) {
248 LOG(FATAL) << "Unexpected exception: " << ex.what();
253 TEST(ScopeGuard, TEST_SCOPE_FAILURE2) {
256 throw std::runtime_error("test");
261 int main(int argc, char** argv) {
262 testing::InitGoogleTest(&argc, argv);
263 google::ParseCommandLineFlags(&argc, &argv, true);
264 return RUN_ALL_TESTS();