Debian Codegraph @

test/unit/internals/lru_cache.cpp

raw
1 #include <gtest/gtest.h>
2
3 #include "utils/lru_cache.hpp"
4
5 using cpptrace::detail::lru_cache;
6 using cpptrace::detail::nullopt;
7
8 namespace {
9
10 TEST(LruCacheTest, DefaultConstructor) {
11 lru_cache<int, int> cache;
12 EXPECT_EQ(cache.size(), 0);
13 }
14
15 TEST(LruCacheTest, MaybeGet) {
16 lru_cache<int, int> cache;
17 auto result = cache.maybe_get(42);
18 EXPECT_FALSE(result.has_value());
19 }
20
21 TEST(LruCacheTest, InsertAndGet) {
22 lru_cache<int, int> cache;
23 cache.insert(42, 50);
24 auto result = cache.maybe_get(42);
25 ASSERT_TRUE(result.has_value());
26 EXPECT_EQ(result.unwrap(), 50);
27 }
28
29 TEST(LruCacheTest, ConstGet) {
30 lru_cache<int, int> cache;
31 cache.insert(42, 50);
32 const lru_cache<int, int>& cache_ref = cache;
33 auto result = cache_ref.maybe_get(42);
34 ASSERT_TRUE(result.has_value());
35 EXPECT_EQ(result.unwrap(), 50);
36 }
37
38 TEST(LruCacheTest, Set) {
39 lru_cache<int, int> cache;
40 cache.set(42, 50);
41 auto result = cache.maybe_get(42);
42 ASSERT_TRUE(result.has_value());
43 EXPECT_EQ(result.unwrap(), 50);
44 cache.set(42, 60);
45 auto result2 = cache.maybe_get(42);
46 ASSERT_TRUE(result2.has_value());
47 EXPECT_EQ(result2.unwrap(), 60);
48 }
49
50 TEST(LruCacheTest, NoMaxSize) {
51 lru_cache<int, int> cache;
52 for(int i = 0; i < 1000; i++) {
53 cache.insert(i, i + 50);
54 }
55 EXPECT_EQ(cache.size(), 1000);
56 for(int i = 0; i < 1000; i++) {
57 EXPECT_EQ(cache.maybe_get(i).unwrap(), i + 50);
58 }
59 }
60
61 TEST(LruCacheTest, MaxSize) {
62 lru_cache<int, int> cache(20);
63 for(int i = 0; i < 1000; i++) {
64 cache.insert(i, i + 50);
65 }
66 EXPECT_EQ(cache.size(), 20);
67 for(int i = 0; i < 1000 - 20; i++) {
68 EXPECT_FALSE(cache.maybe_get(i).has_value());
69 }
70 for(int i = 1000 - 20; i < 1000; i++) {
71 EXPECT_EQ(cache.maybe_get(i).unwrap(), i + 50);
72 }
73 }
74
75 TEST(LruCacheTest, SizeAfterInserts) {
76 lru_cache<int, int> cache;
77 for(int i = 0; i < 1000; i++) {
78 cache.insert(i, i + 50);
79 }
80 EXPECT_EQ(cache.size(), 1000);
81 cache.set_max_size(20);
82 EXPECT_EQ(cache.size(), 20);
83 for(int i = 0; i < 1000 - 20; i++) {
84 EXPECT_FALSE(cache.maybe_get(i).has_value());
85 }
86 for(int i = 1000 - 20; i < 1000; i++) {
87 EXPECT_EQ(cache.maybe_get(i).unwrap(), i + 50);
88 }
89 }
90
91 TEST(LruCacheTest, Touch) {
92 lru_cache<int, int> cache(20);
93 for(int i = 0; i < 1000; i++) {
94 cache.maybe_touch(0);
95 cache.insert(i, i + 50);
96 }
97 EXPECT_EQ(cache.size(), 20);
98 for(int i = 1000 - 19; i < 1000; i++) {
99 EXPECT_EQ(cache.maybe_get(i).unwrap(), i + 50);
100 }
101 EXPECT_EQ(cache.maybe_get(0).unwrap(), 50);
102 }
103
104 }