Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: collections API #963

Merged
merged 16 commits into from
Sep 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* [#920](https://github.com/NibiruChain/nibiru/pull/920) - refactor(proto): pricefeed module files consistency
* [#926](https://github.com/NibiruChain/nibiru/pull/926) - feat: use spot twap for funding rate calculation
* [#932](https://github.com/NibiruChain/nibiru/pull/932) - refactor(perp): rename premium fraction to funding rate
* [#963](https://github.com/NibiruChain/nibiru/pull/963) - test: add collections api tests

### Features

Expand Down
24 changes: 1 addition & 23 deletions collections/collections.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package collections

import (
"bytes"

"github.com/gogo/protobuf/proto"

"github.com/cosmos/cosmos-sdk/codec"
Expand Down Expand Up @@ -47,30 +45,10 @@ func (c storeCodec) unmarshal(bytes []byte, o Object) {
}
}

// setObject is used when no object functionality is needed.
type setObject struct{}

func (n setObject) String() string {
panic("must never be called")
}

func (n setObject) Marshal() ([]byte, error) {
return []byte{}, nil
}

func (n setObject) Unmarshal(b []byte) error {
if !bytes.Equal(b, []byte{}) {
panic("bad usage")
}
return nil
}

var _ Object = (*setObject)(nil)

// TODO(mercilex): improve typeName api
func typeName(o Object) string {
switch o.(type) {
case *setObject, setObject:
case *nilObject, nilObject:
return "no-op-object"
}
pm, ok := o.(proto.Message)
Expand Down
4 changes: 2 additions & 2 deletions collections/item.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,12 @@ func (i Item[V, PV]) getStore(ctx sdk.Context) sdk.KVStore {
func (i Item[V, PV]) Get(ctx sdk.Context) (V, error) {
s := i.getStore(ctx)
bytes := s.Get(itemKey)

var v V
if bytes == nil {
var v V
return v, notFoundError(i.typeName, "item")
}

var v V
i.cdc.unmarshal(bytes, PV(&v))
return v, nil
}
Expand Down
35 changes: 35 additions & 0 deletions collections/item_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package collections

import (
"testing"

wellknown "github.com/gogo/protobuf/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestItemEmpty(t *testing.T) {
sk, ctx, cdc := deps()
item := NewItem[wellknown.BytesValue](cdc, sk, 0)

val, err := item.Get(ctx)
assert.EqualValues(t, wellknown.BytesValue{}, val)
assert.Error(t, err)
}

func TestItemGetWithDefault(t *testing.T) {
sk, ctx, cdc := deps()
item := NewItem[wellknown.BytesValue](cdc, sk, 0)

val := item.GetOr(ctx, wellknown.BytesValue{Value: []byte("foo")})
assert.EqualValues(t, wellknown.BytesValue{Value: []byte("foo")}, val)
}

func TestItemSetAndGet(t *testing.T) {
sk, ctx, cdc := deps()
item := NewItem[wellknown.BytesValue](cdc, sk, 0)
item.Set(ctx, wellknown.BytesValue{Value: []byte("bar")})
val, err := item.Get(ctx)
require.Nil(t, err)
require.EqualValues(t, wellknown.BytesValue{Value: []byte("bar")}, val)
}
37 changes: 37 additions & 0 deletions collections/keys/numeric_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package keys

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestUint8(t *testing.T) {
t.Run("bijectivity", func(t *testing.T) {
key := Uint8Key(0xFF)
bytes := key.KeyBytes()
idx, result := key.FromKeyBytes(bytes)
require.Equalf(t, key, result, "%s <-> %s", key.String(), result.String())
require.Equal(t, 1, idx)
})

t.Run("empty", func(t *testing.T) {
var k Uint8Key
require.Equal(t, []byte{0}, k.KeyBytes())
})
}

func TestUint64(t *testing.T) {
t.Run("bijectivity", func(t *testing.T) {
key := Uint64Key(0x0123456789ABCDEF)
bytes := key.KeyBytes()
idx, result := key.FromKeyBytes(bytes)
require.Equalf(t, key, result, "%s <-> %s", key.String(), result.String())
require.Equal(t, 8, idx)
})

t.Run("empty", func(t *testing.T) {
var k Uint64Key
require.Equal(t, []byte{0, 0, 0, 0, 0, 0, 0, 0}, k.KeyBytes())
})
}
47 changes: 35 additions & 12 deletions collections/keyset.go
Original file line number Diff line number Diff line change
@@ -1,76 +1,99 @@
package collections

import (
"bytes"

"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"

"github.com/NibiruChain/nibiru/collections/keys"
)

// nilObject is used when no object functionality is needed.
// Essentially a null object useful for keysets.
type nilObject struct{}

func (n nilObject) String() string {
panic("must never be called")
}

func (n nilObject) Marshal() ([]byte, error) {
return []byte{}, nil
}

func (n nilObject) Unmarshal(b []byte) error {
if !bytes.Equal(b, []byte{}) {
panic("bad usage")
}
return nil
}

var _ Object = (*nilObject)(nil)

// KeySet wraps the default Map, but is used only for
// keys.Key presence and ranging functionalities.
type KeySet[K keys.Key] Map[K, setObject, *setObject]
type KeySet[K keys.Key] Map[K, nilObject, *nilObject]

// KeySetIterator wraps the default MapIterator, but is used only
// for keys.Key ranging.
type KeySetIterator[K keys.Key] MapIterator[K, setObject, *setObject]
type KeySetIterator[K keys.Key] MapIterator[K, nilObject, *nilObject]

// NewKeySet instantiates a new KeySet.
func NewKeySet[K keys.Key](cdc codec.BinaryCodec, sk sdk.StoreKey, prefix uint8) KeySet[K] {
return KeySet[K]{
cdc: newStoreCodec(cdc),
sk: sk,
prefix: []byte{prefix},
typeName: typeName(new(setObject)),
typeName: typeName(new(nilObject)),
}
}

// Has reports whether the key K is present or not in the set.
func (s KeySet[K]) Has(ctx sdk.Context, k K) bool {
_, err := (Map[K, setObject, *setObject])(s).Get(ctx, k)
_, err := (Map[K, nilObject, *nilObject])(s).Get(ctx, k)
return err == nil
}

// Insert inserts the key K in the set.
func (s KeySet[K]) Insert(ctx sdk.Context, k K) {
(Map[K, setObject, *setObject])(s).Insert(ctx, k, setObject{})
(Map[K, nilObject, *nilObject])(s).Insert(ctx, k, nilObject{})
}

// Delete deletes the key from the set.
// Does not check if the key exists or not.
func (s KeySet[K]) Delete(ctx sdk.Context, k K) {
_ = (Map[K, setObject, *setObject])(s).Delete(ctx, k)
_ = (Map[K, nilObject, *nilObject])(s).Delete(ctx, k)
}

// Iterate returns a KeySetIterator over the provided keys.Range of keys.
func (s KeySet[K]) Iterate(ctx sdk.Context, r keys.Range[K]) KeySetIterator[K] {
mi := (Map[K, setObject, *setObject])(s).Iterate(ctx, r)
mi := (Map[K, nilObject, *nilObject])(s).Iterate(ctx, r)
return (KeySetIterator[K])(mi)
}

// Close closes the KeySetIterator.
// No other operation is valid.
func (s KeySetIterator[K]) Close() {
(MapIterator[K, setObject, *setObject])(s).Close()
(MapIterator[K, nilObject, *nilObject])(s).Close()
}

// Next moves the iterator onto the next key.
func (s KeySetIterator[K]) Next() {
(MapIterator[K, setObject, *setObject])(s).Next()
(MapIterator[K, nilObject, *nilObject])(s).Next()
}

// Valid checks if the iterator is still valid.
func (s KeySetIterator[K]) Valid() bool {
return (MapIterator[K, setObject, *setObject])(s).Valid()
return (MapIterator[K, nilObject, *nilObject])(s).Valid()
}

// Key returns the current iterator key.
func (s KeySetIterator[K]) Key() K {
return (MapIterator[K, setObject, *setObject])(s).Key()
return (MapIterator[K, nilObject, *nilObject])(s).Key()
}

// Keys consumes the iterator fully and returns all the available keys.
// The KeySetIterator is closed after this operation.
func (s KeySetIterator[K]) Keys() []K {
return (MapIterator[K, setObject, *setObject])(s).Keys()
return (MapIterator[K, nilObject, *nilObject])(s).Keys()
}
58 changes: 58 additions & 0 deletions collections/keyset_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package collections

import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/NibiruChain/nibiru/collections/keys"
)

func TestKeyset(t *testing.T) {
sk, ctx, cdc := deps()
keyset := NewKeySet[keys.StringKey](cdc, sk, 0)

key := keys.String("id")

// test insert and get
keyset.Insert(ctx, key)
require.True(t, keyset.Has(ctx, key))

// test delete and get error
keyset.Delete(ctx, key)
require.False(t, keyset.Has(ctx, key))
}

func TestKeyset_Iterate(t *testing.T) {
sk, ctx, cdc := deps()
keyset := NewKeySet[keys.StringKey](cdc, sk, 0)
keyset.Insert(ctx, "a")
keyset.Insert(ctx, "aa")
keyset.Insert(ctx, "b")
keyset.Insert(ctx, "bb")

expectedKeys := []keys.StringKey{"a", "aa", "b", "bb"}

iter := keyset.Iterate(ctx, keys.NewRange[keys.StringKey]())
defer iter.Close()
for i, o := range iter.Keys() {
require.Equal(t, expectedKeys[i], o)
}
}

func TestKeysetIterator(t *testing.T) {
sk, ctx, cdc := deps()

keyset := NewKeySet[keys.StringKey](cdc, sk, 0)
keyset.Insert(ctx, "a")

iter := keyset.Iterate(ctx, keys.NewRange[keys.StringKey]())
defer iter.Close()

assert.True(t, iter.Valid())
assert.EqualValues(t, "a", iter.Key())

iter.Next()
assert.False(t, iter.Valid())
}
39 changes: 30 additions & 9 deletions collections/map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"testing"

wellknown "github.com/gogo/protobuf/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/NibiruChain/nibiru/collections/keys"
Expand Down Expand Up @@ -55,11 +56,22 @@ func TestMap(t *testing.T) {
require.ErrorIs(t, err, ErrNotFound)
}

func TestMap_Iterate(t *testing.T) {
func TestMapGetOrDefault(t *testing.T) {
sk, ctx, cdc := deps()
m := NewMap[keys.StringKey, wellknown.UInt64Value, *wellknown.UInt64Value](cdc, sk, 0)
assert.EqualValues(t, wellknown.UInt64Value{Value: 123}, m.GetOr(ctx, "foo", wellknown.UInt64Value{Value: 123}))

m.Insert(ctx, "foo", wellknown.UInt64Value{Value: 456})
assert.EqualValues(t, wellknown.UInt64Value{Value: 456}, m.GetOr(ctx, "foo", wellknown.UInt64Value{Value: 123}))
}

func TestMapIterate(t *testing.T) {
sk, ctx, cdc := deps()
m := NewMap[keys.StringKey, wellknown.BytesValue, *wellknown.BytesValue](cdc, sk, 0)

objs := []KeyValue[keys.StringKey, wellknown.BytesValue, *wellknown.BytesValue]{kv("a"), kv("aa"), kv("b"), kv("bb")}
expectedObjs := []KeyValue[keys.StringKey, wellknown.BytesValue, *wellknown.BytesValue]{
kv("a"), kv("aa"), kv("b"), kv("bb"),
}

m.Insert(ctx, "a", obj("a"))
m.Insert(ctx, "aa", obj("aa"))
Expand All @@ -70,17 +82,26 @@ func TestMap_Iterate(t *testing.T) {
iter := m.Iterate(ctx, keys.NewRange[keys.StringKey]())
defer iter.Close()
for i, o := range iter.KeyValues() {
require.Equal(t, objs[i], o)
require.Equal(t, expectedObjs[i], o)
}

// test iteration descending
dIter := m.Iterate(ctx, keys.NewRange[keys.StringKey]())
defer dIter.Close()
for i, o := range iter.KeyValues() {
require.Equal(t, objs[len(objs)-1-i], o)
reverseIter := m.Iterate(ctx, keys.NewRange[keys.StringKey]().Descending())
defer reverseIter.Close()
for i, o := range reverseIter.KeyValues() {
require.Equal(t, expectedObjs[len(expectedObjs)-1-i], o)
}

// test all keys
// test key iteration
keyIter := m.Iterate(ctx, keys.NewRange[keys.StringKey]())
defer keyIter.Close()
for i, o := range keyIter.Keys() {
require.Equal(t, expectedObjs[i].Key, o)
}

// test all values
valIter := m.Iterate(ctx, keys.NewRange[keys.StringKey]())
defer valIter.Close()
for i, o := range valIter.Values() {
require.Equal(t, expectedObjs[i].Value, o)
}
}
File renamed without changes.