From ca5b4c0016926bbadef467e81c9642610d8ee59d Mon Sep 17 00:00:00 2001 From: Marcel Ludwig Date: Fri, 23 Oct 2020 15:04:07 +0200 Subject: [PATCH] Fix a panic for unknown cty types, return cty.NullVal of type cty.String as fallback #44 Add test for json 'null' values --- eval/context_test.go | 6 +++++- internal/seetie/convert.go | 14 +++++++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/eval/context_test.go b/eval/context_test.go index 385ed7d26..47713492c 100644 --- a/eval/context_test.go +++ b/eval/context_test.go @@ -78,6 +78,10 @@ func TestNewHTTPContext(t *testing.T) { method = req.method title = req.json_body.slice.foo `, http.Header{"method": {http.MethodGet}}}, + {"Variables / GET /w json body & null value", http.MethodGet, http.Header{"Content-Type": {"application/json"}}, bytes.NewBufferString(`{"json": null}`), "", baseCtx, ` + method = req.method + title = req.json_body.json + `, http.Header{"method": {http.MethodGet}, "title": {""}}}, } log, _ := test.NewNullLogger() @@ -134,7 +138,7 @@ func TestNewHTTPContext(t *testing.T) { result := seetie.ValueToStringSlice(cv) if !reflect.DeepEqual(v, result) { - t.Errorf("Expected %q, got: %v", v, cv) + t.Errorf("Expected %q, got: %#v", v, cv) } } }) diff --git a/internal/seetie/convert.go b/internal/seetie/convert.go index 05051a809..1184b0601 100644 --- a/internal/seetie/convert.go +++ b/internal/seetie/convert.go @@ -5,7 +5,6 @@ import ( "math/big" "net/http" "net/url" - "reflect" "regexp" "strconv" "strings" @@ -81,7 +80,7 @@ func GoToValue(v interface{}) cty.Value { case map[string]interface{}: return MapToValue(v.(map[string]interface{})) } - return cty.NilVal + return cty.NullVal(cty.String) } func MapToValue(m map[string]interface{}) cty.Value { @@ -96,8 +95,6 @@ func MapToValue(m map[string]interface{}) cty.Value { continue } switch v.(type) { - case bool, float64, string: - ctyMap[k] = GoToValue(v) case []string: var list []interface{} for _, s := range v.([]string) { @@ -109,7 +106,7 @@ func MapToValue(m map[string]interface{}) cty.Value { case map[string]interface{}: ctyMap[k] = MapToValue(v.(map[string]interface{})) default: - panic(reflect.TypeOf(v).String() + " not implemented") + ctyMap[k] = GoToValue(v) } } @@ -168,6 +165,10 @@ var whitespaceRegex = regexp.MustCompile(`^\s*$`) // ValueToString explicitly drops all other (unknown) types and // converts non whitespace strings or numbers to its string representation. func ValueToString(v cty.Value) string { + if v.IsNull() { + return "" + } + switch v.Type() { case cty.String: str := v.AsString() @@ -221,6 +222,9 @@ func ToString(s interface{}) string { // isTuple checks by type name since tuple is not comparable by type. func isTuple(v cty.Value) bool { + if v.IsNull() { + return false + } return v.Type().FriendlyNameForConstraint() == "tuple" }