blob: f19468abfdaee67b814de4e1cbace62f81335f77 [file] [log] [blame]
Josh Gao916ea5e2019-11-14 17:59:57 -08001/*
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
21struct __attribute__((packed)) Bomb {
22 Bomb() : magic_(123) {}
23
24 ~Bomb() { exit(42); }
25
26 int get() const { return magic_; }
27
28 private:
29 [[maybe_unused]] char padding_;
30 int magic_;
31};
32
33TEST(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
45TEST(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
57TEST(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}