| 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: |
| 29 |
void Exists() {} |
| 30 |
|
| 31 |
private: |
| 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 |
|
| 38 |
TEST(NoDestruct, Works) { EXPECT_EQ(42, **g_test_int); } |
| 39 |
|
| 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: |
| 48 |
Thing() { |
| 49 |
EXPECT_FALSE(g_thing_constructed); |
| 50 |
g_thing_constructed = true; |
| 51 |
} |
| 52 |
|
| 53 |
int Add(int i, int j) { return i + j; } |
| 54 |
|
| 55 |
private: |
| 56 |
~Thing() = delete; |
| 57 |
}; |
| 58 |
|
| 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 |
|
| 71 |
int main(int argc, char** argv) { |
| 72 |
::testing::InitGoogleTest(&argc, argv); |
| 73 |
return RUN_ALL_TESTS(); |
| 74 |
} |