options: Add namespace to Apply()

This commit is contained in:
Alexander Neumann 2017-03-25 17:20:03 +01:00
parent 2924ebc124
commit a8a7701f60
2 changed files with 14 additions and 6 deletions

View file

@ -69,7 +69,8 @@ func (o Options) Extract(ns string) Options {
}
// Apply sets the options on dst via reflection, using the struct tag `option`.
func (o Options) Apply(dst interface{}) error {
// The namespace argument (ns) is only used for error messages.
func (o Options) Apply(ns string, dst interface{}) error {
v := reflect.ValueOf(dst).Elem()
fields := make(map[string]reflect.StructField)
@ -92,6 +93,9 @@ func (o Options) Apply(dst interface{}) error {
for key, value := range o {
field, ok := fields[key]
if !ok {
if ns != "" {
key = ns + "." + key
}
return errors.Fatalf("option %v is not known", key)
}

View file

@ -163,7 +163,7 @@ func TestOptionsApply(t *testing.T) {
for i, test := range setTests {
t.Run(fmt.Sprintf("test-%d", i), func(t *testing.T) {
var dst Target
err := test.input.Apply(&dst)
err := test.input.Apply("", &dst)
if err != nil {
t.Fatal(err)
}
@ -176,25 +176,29 @@ func TestOptionsApply(t *testing.T) {
}
var invalidSetTests = []struct {
input Options
err string
input Options
namespace string
err string
}{
{
Options{
"first_name": "foobar",
},
"option first_name is not known",
"ns",
"option ns.first_name is not known",
},
{
Options{
"id": "foobar",
},
"ns",
`strconv.ParseInt: parsing "foobar": invalid syntax`,
},
{
Options{
"timeout": "2134",
},
"ns",
`time: missing unit in duration 2134`,
},
}
@ -203,7 +207,7 @@ func TestOptionsApplyInvalid(t *testing.T) {
for i, test := range invalidSetTests {
t.Run(fmt.Sprintf("test-%d", i), func(t *testing.T) {
var dst Target
err := test.input.Apply(&dst)
err := test.input.Apply(test.namespace, &dst)
if err == nil {
t.Fatalf("expected error %v not found", test.err)
}