1 /*
2  * Copyright (C) 2019 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/no_destructor.h"
18 
19 #include <gtest/gtest.h>
20 
21 struct __attribute__((packed)) Bomb {
BombBomb22   Bomb() : magic_(123) {}
23 
~BombBomb24   ~Bomb() { exit(42); }
25 
getBomb26   int get() const { return magic_; }
27 
28  private:
29   [[maybe_unused]] char padding_;
30   int magic_;
31 };
32 
TEST(no_destructor,bomb)33 TEST(no_destructor, bomb) {
34   ASSERT_EXIT(({
35                 {
36                   Bomb b;
37                   if (b.get() != 123) exit(1);
38                 }
39 
40                 exit(0);
41               }),
42               ::testing::ExitedWithCode(42), "");
43 }
44 
TEST(no_destructor,defused)45 TEST(no_destructor, defused) {
46   ASSERT_EXIT(({
47                 {
48                   android::base::NoDestructor<Bomb> b;
49                   if (b->get() != 123) exit(1);
50                 }
51 
52                 exit(0);
53               }),
54               ::testing::ExitedWithCode(0), "");
55 }
56 
TEST(no_destructor,operators)57 TEST(no_destructor, operators) {
58   android::base::NoDestructor<Bomb> b;
59   const android::base::NoDestructor<Bomb>& c = b;
60   ASSERT_EQ(123, b.get()->get());
61   ASSERT_EQ(123, b->get());
62   ASSERT_EQ(123, (*b).get());
63   ASSERT_EQ(123, c.get()->get());
64   ASSERT_EQ(123, c->get());
65   ASSERT_EQ(123, (*c).get());
66 }
67