summaryrefslogtreecommitdiffstats
path: root/cache/cache_test.go
blob: 41e0d25849c6fa510f3d8367cc405647750fd2f8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright © 2022 siddharth ravikumar <s@ricketyspace.net>
// SPDX-License-Identifier: ISC

package cache

import (
	"testing"
	"time"
)

func TestNewCache(t *testing.T) {
	c := NewCache()
	if c == nil {
		t.Errorf("cache is nil")
		return
	}
	if c.store == nil {
		t.Errorf("cache.store is nil")
		return
	}
	// Try manually adding an item.
	c.store["foo"] = item{
		value:   "bar",
		expires: time.Now().Add(time.Second * 10),
	}
	if c.store["foo"].value != "bar" {
		t.Errorf("cache.store['foo'] is not bar")
		return
	}
}

func TestCacheSet(t *testing.T) {
	c := NewCache()
	if c == nil {
		t.Errorf("cache is nil")
		return
	}
	exp := time.Now().Add(time.Second * 10)
	c.Set("foo", "bar", exp)
	if c.store["foo"].value != "bar" {
		t.Errorf("cache.store['foo'] is not bar")
		return
	}
	if c.store["foo"].expires.Unix() != exp.Unix() {
		t.Errorf("cache.store['foo'].expires no set correctly")
		return
	}
}

func TestCacheGet(t *testing.T) {
	c := NewCache()
	if c == nil {
		t.Errorf("cache is nil")
		return
	}

	// Test 1
	exp := time.Now().Add(time.Second * 10)
	c.Set("foo", "bar", exp)
	if c.Get("foo") != "bar" {
		t.Errorf("cache.Get(foo) is not bar")
		return
	}

	// Test 2
	exp = time.Now().Add(time.Second * -10)
	c.Set("sna", "fu", exp)
	if c.Get("sna") != "" {
		t.Errorf("cache.Get(sna) is not empty: %s", c.Get("sna"))
		return
	}
}