Skip to content

Commit

Permalink
Merge pull request adnanh#11 from moorereason/fix-extractparam
Browse files Browse the repository at this point in the history
Fix ExtractParameter and add tests
  • Loading branch information
adnanh committed Mar 19, 2015
2 parents 10755eb + 8a627f7 commit d8a2158
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
6 changes: 3 additions & 3 deletions helpers/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,16 @@ func ExtractParameter(s string, params interface{}) (string, bool) {
if paramsValue := reflect.ValueOf(params); paramsValue.Kind() == reflect.Slice {
if paramsValueSliceLength := paramsValue.Len(); paramsValueSliceLength > 0 {

if p := strings.SplitN(s, ".", 3); len(p) > 3 {
index, err := strconv.ParseInt(p[1], 10, 64)
if p := strings.SplitN(s, ".", 2); len(p) > 1 {
index, err := strconv.ParseInt(p[0], 10, 64)

if err != nil {
return "", false
} else if paramsValueSliceLength <= int(index) {
return "", false
}

return ExtractParameter(p[2], params.([]map[string]interface{})[index])
return ExtractParameter(p[1], params.([]interface{})[index])
}
}

Expand Down
29 changes: 29 additions & 0 deletions helpers/helpers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package helpers

import "testing"

var extractParameterTests = []struct {
s string
params map[string]interface{}
value string
ok bool
}{
{"a", map[string]interface{}{"a": "z"}, "z", true},
{"a.b", map[string]interface{}{"a": map[string]interface{}{"b": "z"}}, "z", true},
{"a.b.c", map[string]interface{}{"a": map[string]interface{}{"b": map[string]interface{}{"c": "z"}}}, "z", true},
{"a.1.b", map[string]interface{}{"a": []interface{}{map[string]interface{}{"b": "y"}, map[string]interface{}{"b": "z"}}}, "z", true},
{"a.1.b.c", map[string]interface{}{"a": []interface{}{map[string]interface{}{"b": map[string]interface{}{"c": "y"}}, map[string]interface{}{"b": map[string]interface{}{"c": "z"}}}}, "z", true},
// failures
{"a.X", map[string]interface{}{"a": map[string]interface{}{"b": "z"}}, "", false},
{"a.500.b", map[string]interface{}{"a": map[string]interface{}{"b": "z"}}, "", false},
{"a.501.b", map[string]interface{}{"a": []interface{}{map[string]interface{}{"b": "y"}, map[string]interface{}{"b": "z"}}}, "", false},
}

func TestExtractParameter(t *testing.T) {
for _, tt := range extractParameterTests {
s, ok := ExtractParameter(tt.s, tt.params)
if ok != tt.ok || s != tt.value {
t.Errorf("failed to extract parameter %q:\nexpected {value:%#v, ok:%#v},\ngot {value:%#v, ok:%#v}", tt.s, tt.value, tt.ok, s, ok)
}
}
}

0 comments on commit d8a2158

Please sign in to comment.