Skip to content

Commit da44c9e

Browse files
committed
fixed some tests
1 parent 48d58e1 commit da44c9e

File tree

3 files changed

+49
-1
lines changed

3 files changed

+49
-1
lines changed

cache.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ func WithJanitorInterval[K comparable, V any](d time.Duration) Option[K, V] {
157157
// There are several Cache replacement policies available with you specified any options.
158158
func New[K comparable, V any](opts ...Option[K, V]) *Cache[K, V] {
159159
ctx, cancel := context.WithCancel(context.Background())
160-
cache := NewContext[K, V](ctx)
160+
cache := NewContext(ctx, opts...)
161161
runtime.SetFinalizer(cache, func(self *Cache[K, V]) {
162162
cancel()
163163
})

cache_internal_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package cache
22

33
import (
44
"context"
5+
"runtime"
56
"testing"
67
"time"
78
)
@@ -26,3 +27,29 @@ func TestDeletedCache(t *testing.T) {
2627
t.Fatal("want false")
2728
}
2829
}
30+
31+
func TestFinalizeCache(t *testing.T) {
32+
if runtime.GOARCH != "amd64" {
33+
t.Skipf("Skipping on non-amd64 machine")
34+
}
35+
36+
done := make(chan struct{})
37+
wait := make(chan struct{})
38+
go func() {
39+
c := New[string, int]()
40+
c.janitor.run(func() {
41+
close(done)
42+
})
43+
c = nil
44+
close(wait)
45+
}()
46+
<-wait
47+
48+
runtime.GC()
49+
50+
select {
51+
case <-done:
52+
case <-time.After(10 * time.Second):
53+
t.Fatal("expected to call a function which is set as finalizer")
54+
}
55+
}

cache_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@ package cache_test
22

33
import (
44
"math/rand"
5+
"runtime"
56
"sync"
67
"testing"
8+
"time"
79

810
cache "github.com/Code-Hex/go-generics-cache"
911
"github.com/Code-Hex/go-generics-cache/policy/clock"
@@ -103,3 +105,22 @@ func TestMultiThread(t *testing.T) {
103105
})
104106
}
105107
}
108+
109+
func TestCallJanitor(t *testing.T) {
110+
c := cache.New(
111+
cache.WithJanitorInterval[string, int](100 * time.Millisecond),
112+
)
113+
114+
c.Set("1", 10, cache.WithExpiration(10*time.Millisecond))
115+
c.Set("2", 20, cache.WithExpiration(20*time.Millisecond))
116+
c.Set("3", 30, cache.WithExpiration(30*time.Millisecond))
117+
118+
<-time.After(300 * time.Millisecond)
119+
120+
keys := c.Keys()
121+
if len(keys) != 0 {
122+
t.Errorf("want items is empty but got %d", len(keys))
123+
}
124+
125+
runtime.GC()
126+
}

0 commit comments

Comments
 (0)