Debian Codegraph @

policy/fifo/fifo_test.go

raw symbols SCIP
1 package fifo_test
2
3 import (
4 "strings"
5 "testing"
6
7 "github.com/Code-Hex/go-generics-cache/policy/fifo"
8 )
9
10 func TestSet(t *testing.T) {
11 // set capacity is 1
12 cache := fifo.NewCache[string, int](fifo.WithCapacity(1))
13 cache.Set("foo", 1)
14 if got := cache.Len(); got != 1 {
15 t.Fatalf("invalid length: %d", got)
16 }
17 if got, ok := cache.Get("foo"); got != 1 || !ok {
18 t.Fatalf("invalid value got %d, cachehit %v", got, ok)
19 }
20
21 // if over the cap
22 cache.Set("bar", 2)
23 if got := cache.Len(); got != 1 {
24 t.Fatalf("invalid length: %d", got)
25 }
26 bar, ok := cache.Get("bar")
27 if bar != 2 || !ok {
28 t.Fatalf("invalid value bar %d, cachehit %v", bar, ok)
29 }
30
31 // checks deleted oldest
32 if _, ok := cache.Get("foo"); ok {
33 t.Fatalf("invalid eviction the oldest value for foo %v", ok)
34 }
35
36 // valid: if over the cap but same key
37 cache.Set("bar", 100)
38 if got := cache.Len(); got != 1 {
39 t.Fatalf("invalid length: %d", got)
40 }
41 bar, ok = cache.Get("bar")
42 if bar != 100 || !ok {
43 t.Fatalf("invalid replacing value bar %d, cachehit %v", bar, ok)
44 }
45 }
46
47 func TestDelete(t *testing.T) {
48 cache := fifo.NewCache[string, int](fifo.WithCapacity(1))
49 cache.Set("foo", 1)
50 if got := cache.Len(); got != 1 {
51 t.Fatalf("invalid length: %d", got)
52 }
53
54 cache.Delete("foo2")
55 if got := cache.Len(); got != 1 {
56 t.Fatalf("invalid length after deleted does not exist key: %d", got)
57 }
58
59 cache.Delete("foo")
60 if got := cache.Len(); got != 0 {
61 t.Fatalf("invalid length after deleted: %d", got)
62 }
63 if _, ok := cache.Get("foo"); ok {
64 t.Fatalf("invalid get after deleted %v", ok)
65 }
66 }
67
68 func TestKeys(t *testing.T) {
69 cache := fifo.NewCache[string, int]()
70 cache.Set("foo", 1)
71 cache.Set("bar", 2)
72 cache.Set("baz", 3)
73 cache.Set("bar", 4) // again
74 cache.Set("foo", 5) // again
75
76 got := strings.Join(cache.Keys(), ",")
77 want := strings.Join([]string{
78 "baz",
79 "bar",
80 "foo",
81 }, ",")
82 if got != want {
83 t.Errorf("want %q, but got %q", want, got)
84 }
85 if len(cache.Keys()) != cache.Len() {
86 t.Errorf("want number of keys %d, but got %d", len(cache.Keys()), cache.Len())
87 }
88 }