Skip to content

Commit

Permalink
Fix schema.Dict.GetField bug
Browse files Browse the repository at this point in the history
fixes GetField(string) to work when KeysValidator is not set, and ads
tests for it. Using asserts library for consistent output compared
to existing tests.
  • Loading branch information
smyrman committed Nov 22, 2017
1 parent 14f9636 commit 326f807
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
1 change: 1 addition & 0 deletions schema/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ type Connection struct {
Field string
}

// Validate implements the FieldValidator interface.
func (v *Connection) Validate(value interface{}) (interface{}, error) {
// No validation perform at this time.
return value, nil
Expand Down
6 changes: 4 additions & 2 deletions schema/dict.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,10 @@ func (v Dict) Validate(value interface{}) (interface{}, error) {

// GetField implements the FieldGetter interface.
func (v Dict) GetField(name string) *Field {
if _, err := v.KeysValidator.Validate(name); err != nil {
return nil
if v.KeysValidator != nil {
if _, err := v.KeysValidator.Validate(name); err != nil {
return nil
}
}
return &v.Values
}
31 changes: 31 additions & 0 deletions schema/dict_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
package schema_test

import (
"reflect"
"testing"

"github.com/rs/rest-layer/schema"
Expand Down Expand Up @@ -116,3 +117,33 @@ func TestDictValidate(t *testing.T) {
testCases[i].Run(t)
}
}

func TestDictGetField(t *testing.T) {
f := schema.Field{Description: "foobar", Filterable: true}
t.Run("{KeysValidator=nil}.GetField(valid)", func(t *testing.T) {
d := schema.Dict{KeysValidator: nil, Values: f}
if gf := d.GetField("something"); !reflect.DeepEqual(f, *gf) {
t.Errorf("d.GetField(valid) returned %#v, expected %#v", *gf, f)
}
})

t.Run("{KeysValidator=String}.GetField(valid)", func(t *testing.T) {
d := schema.Dict{
KeysValidator: schema.String{Allowed: []string{"foo", "bar"}},
Values: f,
}
if gf := d.GetField("foo"); !reflect.DeepEqual(f, *gf) {
t.Errorf("d.GetField(valid) returned %#v, expected %#v", *gf, f)
}
})

t.Run("{KeysValidator=String}.GetField(invalid)", func(t *testing.T) {
d := schema.Dict{
KeysValidator: schema.String{Allowed: []string{"foo", "bar"}},
Values: f,
}
if gf := d.GetField("invalid"); gf != nil {
t.Errorf("d.GetField(invalid) returned %#v, expected nil", *gf)
}
})
}

0 comments on commit 326f807

Please sign in to comment.