Skip to content

Commit

Permalink
Add helper test functions in dot/state
Browse files Browse the repository at this point in the history
  • Loading branch information
qdm12 committed Jan 21, 2022
1 parent 5ef00c4 commit 1292bb1
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 8 deletions.
14 changes: 6 additions & 8 deletions dot/state/base_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
package state

import (
"bytes"
"testing"

"github.com/ChainSafe/gossamer/lib/common"
Expand All @@ -18,14 +17,13 @@ func TestTrie_StoreAndLoadFromDB(t *testing.T) {
db := NewInMemoryDB(t)
tt := trie.NewEmptyTrie()

rt := trie.GenerateRandomTests(t, 1000)
for _, test := range rt {
tt.Put(test.Key(), test.Value())
generator := newGenerator()
const size = 500
kv := generateKeyValues(t, generator, size)

val := tt.Get(test.Key())
if !bytes.Equal(val, test.Value()) {
t.Errorf("Fail to get key %x with value %x: got %x", test.Key(), test.Value(), val)
}
for keyString, value := range kv {
key := []byte(keyString)
tt.Put(key, value)
}

err := tt.Store(db)
Expand Down
72 changes: 72 additions & 0 deletions dot/state/helpers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package state

import (
"math/rand"
"testing"
"time"

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

// newGenerator creates a new PRNG seeded with the
// unix nanoseconds value of the current time.
func newGenerator() (prng *rand.Rand) {
seed := time.Now().UnixNano()
source := rand.NewSource(seed)
return rand.New(source)
}

func generateKeyValues(tb testing.TB, generator *rand.Rand, size int) (kv map[string][]byte) {
tb.Helper()

kv = make(map[string][]byte, size)

const maxKeySize, maxValueSize = 510, 128
for i := 0; i < size; i++ {
populateKeyValueMap(tb, kv, generator, maxKeySize, maxValueSize)
}

return kv
}

func populateKeyValueMap(tb testing.TB, kv map[string][]byte,
generator *rand.Rand, maxKeySize, maxValueSize int) {
tb.Helper()

for {
const minKeySize = 2
key := generateRandBytesMinMax(tb, minKeySize, maxKeySize, generator)

keyString := string(key)

_, keyExists := kv[keyString]

if keyExists && key[1] != byte(0) {
continue
}

const minValueSize = 2
value := generateRandBytesMinMax(tb, minValueSize, maxValueSize, generator)

kv[keyString] = value

break
}
}

func generateRandBytesMinMax(tb testing.TB, minSize, maxSize int,
generator *rand.Rand) (b []byte) {
tb.Helper()
size := minSize +
generator.Intn(maxSize-minSize)
return generateRandBytes(tb, size, generator)
}

func generateRandBytes(tb testing.TB, size int,
generator *rand.Rand) (b []byte) {
tb.Helper()
b = make([]byte, size)
_, err := generator.Read(b)
require.NoError(tb, err)
return b
}

0 comments on commit 1292bb1

Please sign in to comment.