mirror of
https://github.com/optim-enterprises-bv/vault.git
synced 2025-10-30 02:02:43 +00:00
helper/backend: add default values
This commit is contained in:
@@ -44,7 +44,18 @@ type Path struct {
|
||||
|
||||
// FieldSchema is a basic schema to describe the format of a path field.
|
||||
type FieldSchema struct {
|
||||
Type FieldType
|
||||
Type FieldType
|
||||
Default interface{}
|
||||
}
|
||||
|
||||
// DefaultOrZero returns the default value if it is set, or otherwise
|
||||
// the zero value of the type.
|
||||
func (s *FieldSchema) DefaultOrZero() interface{} {
|
||||
if s.Default != nil {
|
||||
return s.Default
|
||||
}
|
||||
|
||||
return s.Type.Zero()
|
||||
}
|
||||
|
||||
func (t FieldType) Zero() interface{} {
|
||||
|
||||
31
helper/backend/backend_test.go
Normal file
31
helper/backend/backend_test.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package backend
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFieldSchemaDefaultOrZero(t *testing.T) {
|
||||
cases := map[string]struct {
|
||||
Schema *FieldSchema
|
||||
Value interface{}
|
||||
}{
|
||||
"default set": {
|
||||
&FieldSchema{Type: TypeString, Default: "foo"},
|
||||
"foo",
|
||||
},
|
||||
|
||||
"default not set": {
|
||||
&FieldSchema{Type: TypeString},
|
||||
"",
|
||||
},
|
||||
}
|
||||
|
||||
for name, tc := range cases {
|
||||
actual := tc.Schema.DefaultOrZero()
|
||||
if !reflect.DeepEqual(actual, tc.Value) {
|
||||
t.Fatalf("bad: %s\n\nExpected: %#v\nGot: %#v",
|
||||
name, tc.Value, actual)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ func (d *FieldData) Get(k string) interface{} {
|
||||
|
||||
value, ok := d.GetOk(k)
|
||||
if !ok {
|
||||
value = schema.Type.Zero()
|
||||
value = schema.DefaultOrZero()
|
||||
}
|
||||
|
||||
return value
|
||||
@@ -47,7 +47,7 @@ func (d *FieldData) GetOk(k string) (interface{}, bool) {
|
||||
}
|
||||
|
||||
if ok && result == nil {
|
||||
result = schema.Type.Zero()
|
||||
result = schema.DefaultOrZero()
|
||||
}
|
||||
|
||||
return result, ok
|
||||
|
||||
@@ -43,6 +43,18 @@ func TestFieldDataGet(t *testing.T) {
|
||||
"",
|
||||
},
|
||||
|
||||
"string type, unset value with default": {
|
||||
map[string]*FieldSchema{
|
||||
"foo": &FieldSchema{
|
||||
Type: TypeString,
|
||||
Default: "bar",
|
||||
},
|
||||
},
|
||||
map[string]interface{}{},
|
||||
"foo",
|
||||
"bar",
|
||||
},
|
||||
|
||||
"int type, int value": {
|
||||
map[string]*FieldSchema{
|
||||
"foo": &FieldSchema{Type: TypeInt},
|
||||
|
||||
Reference in New Issue
Block a user