echoip/http/cache_test.go

77 lines
1.8 KiB
Go
Raw Normal View History

2019-12-25 21:04:26 +01:00
package http
import (
"fmt"
"net"
"testing"
)
func TestCacheCapacity(t *testing.T) {
var tests = []struct {
addCount, capacity, size int
}{
{1, 0, 0},
{1, 2, 1},
{2, 2, 2},
{3, 2, 2},
}
for i, tt := range tests {
c := NewCache(tt.capacity)
2020-09-05 22:07:35 +02:00
var responses []Response
2019-12-25 21:04:26 +01:00
for i := 0; i < tt.addCount; i++ {
ip := net.ParseIP(fmt.Sprintf("192.0.2.%d", i))
2020-09-05 22:07:35 +02:00
r := Response{IP: ip}
2019-12-25 21:04:26 +01:00
responses = append(responses, r)
c.Set(ip, r)
}
if got := len(c.entries); got != tt.size {
t.Errorf("#%d: len(entries) = %d, want %d", i, got, tt.size)
}
if tt.capacity > 0 && tt.addCount > tt.capacity && tt.capacity == tt.size {
lastAdded := responses[tt.addCount-1]
if _, ok := c.Get(lastAdded.IP); !ok {
t.Errorf("#%d: Get(%s) = (_, %t), want (_, %t)", i, lastAdded.IP.String(), ok, !ok)
}
firstAdded := responses[0]
if _, ok := c.Get(firstAdded.IP); ok {
t.Errorf("#%d: Get(%s) = (_, %t), want (_, %t)", i, firstAdded.IP.String(), ok, !ok)
}
}
}
}
2020-09-11 20:51:04 +02:00
func TestCacheDuplicate(t *testing.T) {
c := NewCache(10)
ip := net.ParseIP("192.0.2.1")
response := Response{IP: ip}
c.Set(ip, response)
c.Set(ip, response)
want := 1
if got := len(c.entries); got != want {
t.Errorf("want %d entries, got %d", want, got)
}
if got := c.values.Len(); got != want {
t.Errorf("want %d values, got %d", want, got)
}
}
2020-09-11 21:16:43 +02:00
func TestCacheResize(t *testing.T) {
c := NewCache(10)
for i := 1; i <= 10; i++ {
ip := net.ParseIP(fmt.Sprintf("192.0.2.%d", i))
r := Response{IP: ip}
c.Set(ip, r)
}
if got, want := len(c.entries), 10; got != want {
t.Errorf("want %d entries, got %d", want, got)
}
if err := c.Resize(5); err != nil {
t.Fatal(err)
}
r := Response{IP: net.ParseIP("192.0.2.42")}
c.Set(r.IP, r)
if got, want := len(c.entries), 5; got != want {
t.Errorf("want %d entries, got %d", want, got)
}
}