diff options
author | Cameron Moore <moorereason@gmail.com> | 2018-10-02 20:29:20 -0500 |
---|---|---|
committer | Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com> | 2018-10-03 09:36:27 +0300 |
commit | 0d5110d03324380cb4a288d3fa08c1b86ba227da (patch) | |
tree | 83633efa58205a066e7af9e886ea6fcf0bae723c | |
parent | d3b81ee58e8fd3a0ab8265a2898d66cbcdf6a7c1 (diff) |
tpl: Cast IsSet key to int for indexed types
Don't assume that the user sends an int as the key when checking against
indexed types.
Fixes #3681
-rw-r--r-- | tpl/collections/collections.go | 6 | ||||
-rw-r--r-- | tpl/collections/collections_test.go | 18 |
2 files changed, 15 insertions, 9 deletions
diff --git a/tpl/collections/collections.go b/tpl/collections/collections.go index 1d817077f..6d11d75f4 100644 --- a/tpl/collections/collections.go +++ b/tpl/collections/collections.go @@ -344,7 +344,11 @@ func (ns *Namespace) IsSet(a interface{}, key interface{}) (bool, error) { switch av.Kind() { case reflect.Array, reflect.Chan, reflect.Slice: - if int64(av.Len()) > kv.Int() { + k, err := cast.ToIntE(key) + if err != nil { + return false, fmt.Errorf("isset unable to use key of type %T as index", key) + } + if av.Len() > k { return true, nil } case reflect.Map: diff --git a/tpl/collections/collections_test.go b/tpl/collections/collections_test.go index 8f122569c..dc8929f39 100644 --- a/tpl/collections/collections_test.go +++ b/tpl/collections/collections_test.go @@ -438,22 +438,24 @@ func TestIsSet(t *testing.T) { key interface{} expect bool isErr bool - errStr string }{ - {[]interface{}{1, 2, 3, 5}, 2, true, false, ""}, - {[]interface{}{1, 2, 3, 5}, 22, false, false, ""}, + {[]interface{}{1, 2, 3, 5}, 2, true, false}, + {[]interface{}{1, 2, 3, 5}, "2", true, false}, + {[]interface{}{1, 2, 3, 5}, 2.0, true, false}, - {map[string]interface{}{"a": 1, "b": 2}, "b", true, false, ""}, - {map[string]interface{}{"a": 1, "b": 2}, "bc", false, false, ""}, + {[]interface{}{1, 2, 3, 5}, 22, false, false}, - {time.Now(), "Day", false, false, ""}, - {nil, "nil", false, false, ""}, + {map[string]interface{}{"a": 1, "b": 2}, "b", true, false}, + {map[string]interface{}{"a": 1, "b": 2}, "bc", false, false}, + + {time.Now(), "Day", false, false}, + {nil, "nil", false, false}, + {[]interface{}{1, 2, 3, 5}, TstX{}, false, true}, } { errMsg := fmt.Sprintf("[%d] %v", i, test) result, err := ns.IsSet(test.a, test.key) if test.isErr { - assert.EqualError(t, err, test.errStr, errMsg) continue } |