1 /*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17 #include "android-base/scopeguard.h"
18
19 #include <utility>
20 #include <vector>
21
22 #include <gtest/gtest.h>
23
TEST(scopeguard,normal)24 TEST(scopeguard, normal) {
25 bool guarded_var = true;
26 {
27 auto scopeguard = android::base::make_scope_guard([&guarded_var] { guarded_var = false; });
28 }
29 ASSERT_FALSE(guarded_var);
30 }
31
TEST(scopeguard,disabled)32 TEST(scopeguard, disabled) {
33 bool guarded_var = true;
34 {
35 auto scopeguard = android::base::make_scope_guard([&guarded_var] { guarded_var = false; });
36 scopeguard.Disable();
37 }
38 ASSERT_TRUE(guarded_var);
39 }
40
TEST(scopeguard,moved)41 TEST(scopeguard, moved) {
42 int guarded_var = true;
43 auto scopeguard = android::base::make_scope_guard([&guarded_var] { guarded_var = false; });
44 { decltype(scopeguard) new_guard(std::move(scopeguard)); }
45 EXPECT_FALSE(scopeguard.active());
46 ASSERT_FALSE(guarded_var);
47 }
48
TEST(scopeguard,vector)49 TEST(scopeguard, vector) {
50 int guarded_var = 0;
51 {
52 std::vector<android::base::ScopeGuard<std::function<void()>>> scopeguards;
53 scopeguards.emplace_back(android::base::make_scope_guard(
54 std::bind([](int& guarded_var) { guarded_var++; }, std::ref(guarded_var))));
55 scopeguards.emplace_back(android::base::make_scope_guard(
56 std::bind([](int& guarded_var) { guarded_var++; }, std::ref(guarded_var))));
57 }
58 ASSERT_EQ(guarded_var, 2);
59 }
60