xref: /aosp_15_r20/external/grpc-grpc/test/core/gprpp/no_destruct_test.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 // Copyright 2022 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://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,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "src/core/lib/gprpp/no_destruct.h"
16 
17 #include <stdlib.h>
18 
19 #include <memory>
20 
21 #include "gtest/gtest.h"
22 
23 namespace grpc_core {
24 namespace testing {
25 namespace {
26 
27 class CrashOnDestruction {
28  public:
Exists()29   void Exists() {}
30 
31  private:
~CrashOnDestruction()32   ~CrashOnDestruction() { abort(); }
33 };
34 
35 NoDestruct<std::unique_ptr<int>> g_test_int(new int(42));
36 NoDestruct<CrashOnDestruction> g_test_crash_on_destruction;
37 
TEST(NoDestruct,Works)38 TEST(NoDestruct, Works) { EXPECT_EQ(42, **g_test_int); }
39 
TEST(NoDestruct,CrashOnDestructionIsAccessible)40 TEST(NoDestruct, CrashOnDestructionIsAccessible) {
41   g_test_crash_on_destruction->Exists();
42 }
43 
44 bool g_thing_constructed = false;
45 
46 class Thing {
47  public:
Thing()48   Thing() {
49     EXPECT_FALSE(g_thing_constructed);
50     g_thing_constructed = true;
51   }
52 
Add(int i,int j)53   int Add(int i, int j) { return i + j; }
54 
55  private:
56   ~Thing() = delete;
57 };
58 
TEST(GlobalSingleton,Works)59 TEST(GlobalSingleton, Works) {
60   // Thing should be eagerly constructed, so we should not observe it being not
61   // constructed.
62   EXPECT_TRUE(g_thing_constructed);
63   // We should be able to fetch the global Thing and use it.
64   EXPECT_EQ(NoDestructSingleton<Thing>::Get()->Add(1, 2), 3);
65 }
66 
67 }  // namespace
68 }  // namespace testing
69 }  // namespace grpc_core
70 
main(int argc,char ** argv)71 int main(int argc, char** argv) {
72   ::testing::InitGoogleTest(&argc, argv);
73   return RUN_ALL_TESTS();
74 }
75