From 0764726e3eefb1f5f9378935217ba8eeaf06324e Mon Sep 17 00:00:00 2001 From: Alisdair McDiarmid Date: Wed, 16 Mar 2022 08:49:50 -0400 Subject: [PATCH] functions: Fix sum() of all strings The sum() function accepts a collection of values which must all convert to numbers. It is valid for this to be a collection of string values representing numbers. Previously the function would panic if the first element of a collection was a non-number type, as we didn't attempt to convert it to a number before calling the cty `Add` method. --- internal/lang/funcs/collection.go | 4 ++++ internal/lang/funcs/collection_test.go | 9 +++++++++ 2 files changed, 13 insertions(+) diff --git a/internal/lang/funcs/collection.go b/internal/lang/funcs/collection.go index 0272b2463..2b772f35c 100644 --- a/internal/lang/funcs/collection.go +++ b/internal/lang/funcs/collection.go @@ -527,6 +527,10 @@ var SumFunc = function.New(&function.Spec{ if s.IsNull() { return cty.NilVal, function.NewArgErrorf(0, "argument must be list, set, or tuple of number values") } + s, err = convert.Convert(s, cty.Number) + if err != nil { + return cty.NilVal, function.NewArgErrorf(0, "argument must be list, set, or tuple of number values") + } for _, v := range arg[1:] { if v.IsNull() { return cty.NilVal, function.NewArgErrorf(0, "argument must be list, set, or tuple of number values") diff --git a/internal/lang/funcs/collection_test.go b/internal/lang/funcs/collection_test.go index 2a1927acf..d470f357e 100644 --- a/internal/lang/funcs/collection_test.go +++ b/internal/lang/funcs/collection_test.go @@ -1629,6 +1629,15 @@ func TestSum(t *testing.T) { cty.NilVal, "can't compute sum of opposing infinities", }, + { + cty.ListVal([]cty.Value{ + cty.StringVal("1"), + cty.StringVal("2"), + cty.StringVal("3"), + }), + cty.NumberIntVal(6), + "", + }, } for _, test := range tests {