|
| 1 | +package simple |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + "time" |
| 6 | + |
| 7 | + cache "github.com/Code-Hex/go-generics-cache" |
| 8 | +) |
| 9 | + |
| 10 | +func TestContains(t *testing.T) { |
| 11 | + t.Run("without expiration", func(t *testing.T) { |
| 12 | + cache := NewCache[string, int]() |
| 13 | + cache.Set("foo", 1) |
| 14 | + cache.Set("bar", 2) |
| 15 | + cache.Set("baz", 3) |
| 16 | + for _, key := range []string{ |
| 17 | + "foo", |
| 18 | + "bar", |
| 19 | + "baz", |
| 20 | + } { |
| 21 | + if !cache.Contains(key) { |
| 22 | + t.Errorf("not found: %s", key) |
| 23 | + } |
| 24 | + } |
| 25 | + if cache.Contains("not found") { |
| 26 | + t.Errorf("found") |
| 27 | + } |
| 28 | + }) |
| 29 | + |
| 30 | + t.Run("with expiration", func(t *testing.T) { |
| 31 | + c := NewCache[string, int]() |
| 32 | + key := "foo" |
| 33 | + exp := time.Hour |
| 34 | + c.Set(key, 1, cache.WithExpiration(exp)) |
| 35 | + // modify directly |
| 36 | + item, ok := c.items[key] |
| 37 | + if !ok { |
| 38 | + t.Fatal("unexpected not found key") |
| 39 | + } |
| 40 | + item.CreatedAt = time.Now().Add(-2 * exp) |
| 41 | + |
| 42 | + if c.Contains(key) { |
| 43 | + t.Errorf("found") |
| 44 | + } |
| 45 | + }) |
| 46 | +} |
| 47 | + |
| 48 | +func TestGet(t *testing.T) { |
| 49 | + c := NewCache[string, int]() |
| 50 | + key := "foo" |
| 51 | + exp := time.Hour |
| 52 | + c.Set(key, 1, cache.WithExpiration(exp)) |
| 53 | + _, ok := c.Get(key) |
| 54 | + if !ok { |
| 55 | + t.Fatal("unexpected not found") |
| 56 | + } |
| 57 | + // modify directly |
| 58 | + item, ok := c.items[key] |
| 59 | + if !ok { |
| 60 | + t.Fatal("unexpected not found key") |
| 61 | + } |
| 62 | + item.CreatedAt = time.Now().Add(-2 * exp) |
| 63 | + _, ok2 := c.Get(key) |
| 64 | + if ok2 { |
| 65 | + t.Fatal("unexpected found (expired)") |
| 66 | + } |
| 67 | +} |
0 commit comments