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_compilation_testing/negative_compilation.h"
18 #include "pw_status/status.h"
19 #include "pw_unit_test/framework.h"
20
21 namespace {
22
23 // PW_ASSERT() should always be enabled, and always evaluate the expression.
TEST(Assert,AssertTrue)24 TEST(Assert, AssertTrue) {
25 int evaluated = 1;
26 PW_ASSERT(++evaluated);
27 EXPECT_EQ(evaluated, 2);
28 }
29
30 // PW_DASSERT() might be disabled sometimes.
TEST(Assert,DebugAssertTrue)31 TEST(Assert, DebugAssertTrue) {
32 int evaluated = 1;
33 PW_DASSERT(++evaluated);
34 if (PW_ASSERT_ENABLE_DEBUG == 1) {
35 EXPECT_EQ(evaluated, 2);
36 } else {
37 EXPECT_EQ(evaluated, 1);
38 }
39 }
40
TEST(Assert,AssertOkEvaluatesExpressionAndDoesNotCrashOnOk)41 TEST(Assert, AssertOkEvaluatesExpressionAndDoesNotCrashOnOk) {
42 int evaluated = 1;
43 PW_ASSERT_OK(([&]() {
44 ++evaluated;
45 return pw::OkStatus();
46 })());
47 EXPECT_EQ(evaluated, 2);
48 }
49
50 // Unfortunately, we don't have the infrastructure to test failure handling
51 // automatically, since the harness crashes in the process of running this
52 // test. The unsatisfying alternative is to test the functionality manually,
53 // then disable the test.
54
TEST(Assert,AssertFalse)55 TEST(Assert, AssertFalse) {
56 if (false) {
57 PW_ASSERT(false);
58 }
59 }
60
TEST(Assert,DebugAssertFalse)61 TEST(Assert, DebugAssertFalse) {
62 if (false) {
63 PW_DASSERT(false);
64 }
65 }
66
67 #if PW_NC_TEST(ConstexprAssert)
68 PW_NC_EXPECT("PW_ASSERT_failed_in_constant_expression");
69
70 #line 1 "example.cc" // DOCSTAG: [pw_assert-constexpr-example]
DivideEvenNumberBy2(int value)71 constexpr int DivideEvenNumberBy2(int value) {
72 PW_ASSERT(value % 2 == 0); // value must be even!
73 return value / 2;
74 }
75
76 constexpr int kResult = DivideEvenNumberBy2(11); // This fails the PW_ASSERT!
77 // DOCSTAG: [pw_assert-constexpr-example]
78
79 #endif // PW_NC_TEST
80
81 } // namespace
82