From 8c978d24769d29a369c0c8359febd8b66e03c66b Mon Sep 17 00:00:00 2001 From: mossid Date: Tue, 16 Oct 2018 03:02:48 +0900 Subject: [PATCH] add tests and restriction for TypeTable --- x/params/subspace/table.go | 17 ++++++++++++++++ x/params/subspace/table_test.go | 35 +++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 x/params/subspace/table_test.go diff --git a/x/params/subspace/table.go b/x/params/subspace/table.go index 628ebef477..19e41da090 100644 --- a/x/params/subspace/table.go +++ b/x/params/subspace/table.go @@ -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") diff --git a/x/params/subspace/table_test.go b/x/params/subspace/table_test.go new file mode 100644 index 0000000000..8f9142e1ec --- /dev/null +++ b/x/params/subspace/table_test.go @@ -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{}) }) +}