xref: /aosp_15_r20/external/pigweed/pw_assert/assert_test.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2020 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_assert/assert.h"
16 
17 #include "pw_status/status.h"
18 #include "pw_unit_test/framework.h"
19 
20 namespace {
21 
22 // PW_ASSERT() should always be enabled, and always evaluate the expression.
TEST(Assert,AssertTrue)23 TEST(Assert, AssertTrue) {
24   int evaluated = 1;
25   PW_ASSERT(++evaluated);
26   EXPECT_EQ(evaluated, 2);
27 }
28 
29 // PW_DASSERT() might be disabled sometimes.
TEST(Assert,DebugAssertTrue)30 TEST(Assert, DebugAssertTrue) {
31   int evaluated = 1;
32   PW_DASSERT(++evaluated);
33   if (PW_ASSERT_ENABLE_DEBUG == 1) {
34     EXPECT_EQ(evaluated, 2);
35   } else {
36     EXPECT_EQ(evaluated, 1);
37   }
38 }
39 
TEST(Assert,AssertOkEvaluatesExpressionAndDoesNotCrashOnOk)40 TEST(Assert, AssertOkEvaluatesExpressionAndDoesNotCrashOnOk) {
41   int evaluated = 1;
42   PW_ASSERT_OK(([&]() {
43     ++evaluated;
44     return pw::OkStatus();
45   })());
46   EXPECT_EQ(evaluated, 2);
47 }
48 
49 // Unfortunately, we don't have the infrastructure to test failure handling
50 // automatically, since the harness crashes in the process of running this
51 // test. The unsatisfying alternative is to test the functionality manually,
52 // then disable the test.
53 
TEST(Assert,AssertFalse)54 TEST(Assert, AssertFalse) {
55   if (false) {
56     PW_ASSERT(false);
57   }
58 }
59 
TEST(Assert,DebugAssertFalse)60 TEST(Assert, DebugAssertFalse) {
61   if (false) {
62     PW_DASSERT(false);
63   }
64 }
65 
66 }  // namespace
67