| Tom Cherry | eb92782 | 2017-04-05 14:15:31 -0700 | [diff] [blame] | 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> | 
| Luis Hector Chavez | b77035b | 2018-03-26 13:11:21 -0700 | [diff] [blame] | 20 | #include <vector> | 
| Tom Cherry | eb92782 | 2017-04-05 14:15:31 -0700 | [diff] [blame] | 21 |  | 
|  | 22 | #include <gtest/gtest.h> | 
|  | 23 |  | 
|  | 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 |  | 
|  | 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 |  | 
|  | 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 | } | 
| Luis Hector Chavez | b77035b | 2018-03-26 13:11:21 -0700 | [diff] [blame] | 48 |  | 
|  | 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 | } |