1 // Copyright 2023 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 #include "pw_function/scope_guard.h"
16
17 #include <utility>
18
19 #include "pw_function/function.h"
20 #include "pw_unit_test/framework.h"
21
22 namespace pw {
23 namespace {
24
TEST(ScopeGuard,ExecutesLambda)25 TEST(ScopeGuard, ExecutesLambda) {
26 bool executed = false;
27 {
28 ScopeGuard guarded_lambda([&] { executed = true; });
29 EXPECT_FALSE(executed);
30 }
31 EXPECT_TRUE(executed);
32 }
33
34 static bool static_executed = false;
set_static_executed()35 void set_static_executed() { static_executed = true; }
36
TEST(ScopeGuard,ExecutesFunction)37 TEST(ScopeGuard, ExecutesFunction) {
38 {
39 ScopeGuard guarded_function(set_static_executed);
40
41 EXPECT_FALSE(static_executed);
42 }
43 EXPECT_TRUE(static_executed);
44 }
45
TEST(ScopeGuard,ExecutesPwFunction)46 TEST(ScopeGuard, ExecutesPwFunction) {
47 bool executed = false;
48 pw::Function<void()> pw_function([&]() { executed = true; });
49 {
50 ScopeGuard guarded_pw_function(std::move(pw_function));
51 EXPECT_FALSE(executed);
52 }
53 EXPECT_TRUE(executed);
54 }
55
TEST(ScopeGuard,Dismiss)56 TEST(ScopeGuard, Dismiss) {
57 bool executed = false;
58 {
59 ScopeGuard guard([&] { executed = true; });
60 EXPECT_FALSE(executed);
61 guard.Dismiss();
62 EXPECT_FALSE(executed);
63 }
64 EXPECT_FALSE(executed);
65 }
66
TEST(ScopeGuard,MoveConstructor)67 TEST(ScopeGuard, MoveConstructor) {
68 bool executed = false;
69 ScopeGuard first_guard([&] { executed = true; });
70 {
71 ScopeGuard second_guard(std::move(first_guard));
72 EXPECT_FALSE(executed);
73 }
74 EXPECT_TRUE(executed);
75 }
76
TEST(ScopeGuard,MoveOperator)77 TEST(ScopeGuard, MoveOperator) {
78 bool executed = false;
79 ScopeGuard first_guard([&] { executed = true; });
80 {
81 ScopeGuard second_guard = std::move(first_guard);
82 EXPECT_FALSE(executed);
83 }
84 EXPECT_TRUE(executed);
85 }
86
87 } // namespace
88 } // namespace pw
89