all repos — volatile @ 7711e07c600847e0d27ed8730f254f501fb87f50

A (dead) simple volatile data storage written in Go.

volatile_test.go (view raw)

 1package volatile
 2
 3import (
 4	"testing"
 5	"time"
 6)
 7
 8func TestVolatile_SetGet(t *testing.T) {
 9	cache := NewVolatile[string, string](2*time.Second, 1*time.Second)
10
11	key := "key1"
12	value := "value1"
13	cache.Set(key, &value)
14
15	got, err := cache.Get(key)
16	if err != nil {
17		t.Fatalf("unexpected error: %v", err)
18	}
19	if *got != value {
20		t.Errorf("got %v, want %v", *got, value)
21	}
22
23	if !cache.Has(key) {
24		t.Errorf("expected key %v to exist", key)
25	}
26}
27
28func TestVolatile_Remove(t *testing.T) {
29	cache := NewVolatile[string, string](2*time.Second, 1*time.Second)
30
31	key := "key1"
32	value := "value1"
33	cache.Set(key, &value)
34
35	got, err := cache.Remove(key)
36	if err != nil {
37		t.Fatalf("unexpected error: %v", err)
38	}
39	if *got != value {
40		t.Errorf("got %v, want %v", *got, value)
41	}
42
43	if cache.Has(key) {
44		t.Errorf("expected key %v to be removed", key)
45	}
46}
47
48func TestVolatile_Clean(t *testing.T) {
49	cache := NewVolatile[string, string](100*time.Millisecond, 50*time.Millisecond)
50
51	key := "key1"
52	value := "value1"
53	cache.Set(key, &value)
54
55	time.Sleep(150 * time.Millisecond) // Wait for the element to expire
56
57	if cache.Has(key) {
58		t.Errorf("expected key %v to be expired and removed", key)
59	}
60
61	_, err := cache.Get(key)
62	if err == nil {
63		t.Errorf("expected error when getting expired key %v", key)
64	}
65}
66
67func TestVolatile_AutomaticCleanup(t *testing.T) {
68	cache := NewVolatile[string, string](100*time.Millisecond, 50*time.Millisecond)
69
70	key1 := "key1"
71	value1 := "value1"
72	cache.Set(key1, &value1)
73
74	key2 := "key2"
75	value2 := "value2"
76	cache.Set(key2, &value2)
77
78	time.Sleep(150 * time.Millisecond) // Wait for the elements to expire
79
80	if cache.Has(key1) || cache.Has(key2) {
81		t.Errorf("expected all keys to be expired and removed")
82	}
83}