add tests and restriction for TypeTable

This commit is contained in:
mossid 2018-10-16 03:02:48 +09:00
parent 73d83b02cb
commit 8c978d2476
2 changed files with 52 additions and 0 deletions

View File

@ -26,8 +26,25 @@ func NewTypeTable(keytypes ...interface{}) (res TypeTable) {
return
}
func isAlphaNumeric(key []byte) bool {
for _, b := range key {
if !((48 <= b && b <= 57) || // numeric
(65 <= b && b <= 90) || // upper case
(97 <= b && b <= 122)) { // lower case
return false
}
}
return true
}
// Register single key-type pair
func (t TypeTable) RegisterType(key []byte, ty interface{}) TypeTable {
if len(key) == 0 {
panic("cannot register empty key")
}
if !isAlphaNumeric(key) {
panic("non alphanumeric parameter key")
}
keystr := string(key)
if _, ok := t.m[keystr]; ok {
panic("duplicate parameter key")

View File

@ -0,0 +1,35 @@
package subspace
import (
"testing"
"github.com/stretchr/testify/require"
)
type testparams struct {
i int64
b bool
}
func (tp *testparams) KeyValuePairs() KeyValuePairs {
return KeyValuePairs{
{[]byte("i"), &tp.i},
{[]byte("b"), &tp.b},
}
}
func TestTypeTable(t *testing.T) {
table := NewTypeTable()
require.Panics(t, func() { table.RegisterType([]byte(""), nil) })
require.Panics(t, func() { table.RegisterType([]byte("!@#$%"), nil) })
require.Panics(t, func() { table.RegisterType([]byte("hello,"), nil) })
require.Panics(t, func() { table.RegisterType([]byte("hello"), nil) })
require.NotPanics(t, func() { table.RegisterType([]byte("hello"), bool(false)) })
require.NotPanics(t, func() { table.RegisterType([]byte("world"), int64(0)) })
require.Panics(t, func() { table.RegisterType([]byte("hello"), bool(false)) })
require.NotPanics(t, func() { table.RegisterParamSet(&testparams{}) })
require.Panics(t, func() { table.RegisterParamSet(&testparams{}) })
}