7d48b88ca862b47286e0de07d81532eba434f2c5
[folly.git] / folly / test / SingletonVaultCTest.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
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 <folly/Singleton.h>
18 #include <folly/SingletonVault_c.h>
19
20 #include <folly/portability/GTest.h>
21
22 FOLLY_TLS long instance_counter_instances = 0;
23
24 class InstanceCounter {
25  public:
26   InstanceCounter() {
27     instance_counter_instances++;
28   }
29
30   ~InstanceCounter() {
31     instance_counter_instances--;
32   }
33 };
34
35 TEST(SingletonVault, singletonReturnsSingletonInstance) {
36   SingletonVault_t *c = SingletonVault_singleton();
37   auto *cpp = folly::SingletonVault::singleton();
38   EXPECT_EQ(c, cpp);
39 }
40
41 struct TestTag {};
42 template <typename T, typename Tag = folly::detail::DefaultTag>
43 using SingletonTest = folly::Singleton <T, Tag, TestTag>;
44
45 TEST(SingletonVault, singletonsAreCreatedAndDestroyed) {
46   auto vault = folly::SingletonVault::singleton<TestTag>();
47   SingletonTest<InstanceCounter> counter_singleton;
48   SingletonVault_registrationComplete((SingletonVault_t*) vault);
49   SingletonTest<InstanceCounter>::try_get();
50   EXPECT_EQ(instance_counter_instances, 1);
51   SingletonVault_destroyInstances((SingletonVault_t*) vault);
52   EXPECT_EQ(instance_counter_instances, 0);
53 }