blob: 81a4b9ce1a4c654d8959a4a446658fb2c46c487f [file] [log] [blame]
James Kuszmaul397f6fe2020-01-04 16:21:52 -08001/*----------------------------------------------------------------------------*/
2/* Copyright (c) 2019 FIRST. All Rights Reserved. */
3/* Open Source Software - may be modified and shared by FRC teams. The code */
4/* must be accompanied by the FIRST BSD license file in the root directory of */
5/* the project. */
6/*----------------------------------------------------------------------------*/
7
8#include "wpi/ManagedStatic.h" // NOLINT(build/include_order)
9
10#include "gtest/gtest.h"
11
12static int refCount = 0;
13
14struct StaticTestClass {
15 StaticTestClass() { refCount++; }
16 ~StaticTestClass() { refCount--; }
17
18 void Func() {}
19};
20
21namespace wpi {
22TEST(ManagedStaticTest, LazyDoesNotInitialize) {
23 {
24 refCount = 0;
25 wpi::ManagedStatic<StaticTestClass> managedStatic;
26 ASSERT_EQ(refCount, 0);
27 }
28 ASSERT_EQ(refCount, 0);
29 wpi_shutdown();
30}
31
32TEST(ManagedStaticTest, LazyInitDoesntDestruct) {
33 {
34 refCount = 0;
35 wpi::ManagedStatic<StaticTestClass> managedStatic;
36 ASSERT_EQ(refCount, 0);
37 managedStatic->Func();
38 ASSERT_EQ(refCount, 1);
39 }
40 ASSERT_EQ(refCount, 1);
41 wpi_shutdown();
42 ASSERT_EQ(refCount, 0);
43}
44
45TEST(ManagedStaticTest, EagerInit) {
46 {
47 refCount = 0;
48 StaticTestClass* test = new StaticTestClass{};
49 ASSERT_EQ(refCount, 1);
50 wpi::ManagedStatic<StaticTestClass> managedStatic(
51 test, [](void* val) { delete static_cast<StaticTestClass*>(val); });
52 ASSERT_EQ(refCount, 1);
53 managedStatic->Func();
54 ASSERT_EQ(refCount, 1);
55 }
56 ASSERT_EQ(refCount, 1);
57 wpi_shutdown();
58 ASSERT_EQ(refCount, 0);
59}
60} // namespace wpi