blob: ecc80406b003421a59d378d05ceb12d137940a62 [file] [log] [blame]
Austin Schuh36244a12019-09-21 17:52:38 -07001// Copyright 2018 The Abseil 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// https://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 "absl/base/internal/atomic_hook.h"
16
17#include "gtest/gtest.h"
18#include "absl/base/attributes.h"
19
20namespace {
21
22int value = 0;
23void TestHook(int x) { value = x; }
24
25TEST(AtomicHookTest, NoDefaultFunction) {
26 ABSL_CONST_INIT static absl::base_internal::AtomicHook<void(*)(int)> hook;
27 value = 0;
28
29 // Test the default DummyFunction.
30 EXPECT_TRUE(hook.Load() == nullptr);
31 EXPECT_EQ(value, 0);
32 hook(1);
33 EXPECT_EQ(value, 0);
34
35 // Test a stored hook.
36 hook.Store(TestHook);
37 EXPECT_TRUE(hook.Load() == TestHook);
38 EXPECT_EQ(value, 0);
39 hook(1);
40 EXPECT_EQ(value, 1);
41
42 // Calling Store() with the same hook should not crash.
43 hook.Store(TestHook);
44 EXPECT_TRUE(hook.Load() == TestHook);
45 EXPECT_EQ(value, 1);
46 hook(2);
47 EXPECT_EQ(value, 2);
48}
49
50TEST(AtomicHookTest, WithDefaultFunction) {
51 // Set the default value to TestHook at compile-time.
52 ABSL_CONST_INIT static absl::base_internal::AtomicHook<void (*)(int)> hook(
53 TestHook);
54 value = 0;
55
56 // Test the default value is TestHook.
57 EXPECT_TRUE(hook.Load() == TestHook);
58 EXPECT_EQ(value, 0);
59 hook(1);
60 EXPECT_EQ(value, 1);
61
62 // Calling Store() with the same hook should not crash.
63 hook.Store(TestHook);
64 EXPECT_TRUE(hook.Load() == TestHook);
65 EXPECT_EQ(value, 1);
66 hook(2);
67 EXPECT_EQ(value, 2);
68}
69
70} // namespace