1 /*
2  * Copyright (C) 2016 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 #ifndef CHRE_PLATFORM_LINUX_EXPECT_ASSERT_H_
18 #define CHRE_PLATFORM_LINUX_EXPECT_ASSERT_H_
19 
20 #include <cassert>
21 
22 #ifdef GTEST
23 
24 #include "chre/platform/log.h"
25 #include "gmock/gmock.h"
26 
27 class MockAssert;
28 extern MockAssert *gMockAssert;
29 
30 class AssertInterface {
31  public:
~AssertInterface()32   virtual ~AssertInterface() {}
33   virtual void doAssert() = 0;
34 };
35 
36 class MockAssert : public AssertInterface {
37  public:
MockAssert()38   MockAssert() {
39     gMockAssert = this;
40   }
~MockAssert()41   ~MockAssert() {
42     gMockAssert = nullptr;
43   }
44 
45   MOCK_METHOD0(doAssert, void());
46 };
47 
48 /**
49  * Helper macro that wraps a statement in a block that sets up the mock for
50  * CHRE_ASSERT and expects it to be called at least once. This allows for
51  * verification that the code to be tested throws an expected assertion failure,
52  * and also handles the failure gracefully when assertions are compiled out.
53  * Triggered assertions are logged using LOGI, so they can be manually checked
54  * in the test output.
55  *
56  * Example:
57  * @code{.cpp}
58  *   TEST(DynamicVector, InsertToSparseIndexFails) {
59  *     DynamicVector<int> vector;
60  *     EXPECT_CHRE_ASSERT(EXPECT_FALSE(vector.insert(5));
61  *   }
62  * @endcode
63  */
64 #define EXPECT_CHRE_ASSERT(statement)                                     \
65   do {                                                                    \
66     ASSERT_EQ(gMockAssert, nullptr);                                      \
67     MockAssert chreMockAssert;                                            \
68     EXPECT_CALL(chreMockAssert, doAssert()).Times(::testing::AtLeast(1)); \
69     statement;                                                            \
70   } while (0)
71 
72 #endif  // GTEST
73 
74 #endif  // CHRE_PLATFORM_LINUX_EXPECT_ASSERT_H_
75