neo-go/pkg/core/cache/cache_test.go

61 lines
1.5 KiB
Go
Raw Normal View History

2020-06-05 09:11:22 +00:00
package cache
2019-11-08 15:40:21 +00:00
import (
"testing"
2020-06-05 09:11:22 +00:00
"github.com/nspcc-dev/neo-go/pkg/crypto/hash"
"github.com/nspcc-dev/neo-go/pkg/util"
2019-11-08 15:40:21 +00:00
"github.com/stretchr/testify/require"
)
func TestRelayCache_Add(t *testing.T) {
const capacity = 3
2020-06-05 09:11:22 +00:00
payloads := getDifferentItems(t, capacity+1)
c := NewFIFOCache(capacity)
2019-11-08 15:40:21 +00:00
require.Equal(t, 0, c.queue.Len())
require.Equal(t, 0, len(c.elems))
for i := 1; i < capacity; i++ {
c.Add(&payloads[i])
2019-11-15 10:32:40 +00:00
require.True(t, c.Has(payloads[i].Hash()))
2019-11-08 15:40:21 +00:00
require.Equal(t, i, c.queue.Len())
require.Equal(t, i, len(c.elems))
}
// add already existing payload
c.Add(&payloads[1])
require.Equal(t, capacity-1, c.queue.Len())
require.Equal(t, capacity-1, len(c.elems))
c.Add(&payloads[0])
require.Equal(t, capacity, c.queue.Len())
require.Equal(t, capacity, len(c.elems))
// capacity does not exceed maximum
c.Add(&payloads[capacity])
require.Equal(t, capacity, c.queue.Len())
require.Equal(t, capacity, len(c.elems))
// recent payloads are still present in cache
require.Equal(t, &payloads[0], c.Get(payloads[0].Hash()))
for i := 2; i <= capacity; i++ {
require.Equal(t, &payloads[i], c.Get(payloads[i].Hash()))
}
// oldest payload was removed
2019-11-15 10:32:40 +00:00
require.Equal(t, nil, c.Get(payloads[1].Hash()))
2019-11-08 15:40:21 +00:00
}
2020-06-05 09:11:22 +00:00
type testHashable []byte
2019-11-08 15:40:21 +00:00
2020-06-05 09:11:22 +00:00
// Hash implements Hashable.
func (h testHashable) Hash() util.Uint256 { return hash.Sha256(h) }
2019-11-08 15:40:21 +00:00
2020-06-05 09:11:22 +00:00
func getDifferentItems(t *testing.T, n int) []testHashable {
items := make([]testHashable, n)
for i := range items {
items[i] = []byte{byte(i)}
2020-06-05 09:11:22 +00:00
}
return items
2019-11-08 15:40:21 +00:00
}