From a21fb70eb4d809c2e054eef36ad59167f5a67c2f Mon Sep 17 00:00:00 2001 From: Roy Tang Date: Fri, 22 Jan 2021 03:55:03 +0800 Subject: [PATCH] fix(transform): fix nil returned by TransformString for ComposeTranformers (#330) TranformString should not return nil on zero value, otherwise nil will be passed to next Tranformer if there are more than 1 Transformer in ComposeTransformers. return zero value of string instead coz String Tranformer is guaranteed to return string --- transform.go | 11 +++++++---- transform_test.go | 6 ++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/transform.go b/transform.go index ccc75e08..58d5193b 100644 --- a/transform.go +++ b/transform.go @@ -18,18 +18,21 @@ func TransformString(f func(s string) string) Transformer { return func(ans interface{}) interface{} { // if the answer value passed in is the zero value of the appropriate type if isZero(reflect.ValueOf(ans)) { - // skip this `Transformer` by returning a nil value. + // skip this `Transformer` by returning a zero value of string. // The original answer will be not affected, // see survey.go#L125. - return nil + // A zero value of string should be returned to be handled by + // next Transformer in a composed Tranformer, + // see tranform.go#L75 + return "" } // "ans" is never nil here, so we don't have to check that - // see survey.go#L97 for more. + // see survey.go#L338 for more. // Make sure that the the answer's value was a typeof string. s, ok := ans.(string) if !ok { - return nil + return "" } return f(s) diff --git a/transform_test.go b/transform_test.go index 5d58ee08..46101403 100644 --- a/transform_test.go +++ b/transform_test.go @@ -41,4 +41,10 @@ func TestComposeTransformers(t *testing.T) { // the result should be lowercase. t.Errorf("TestComposeTransformers transformer failed to transform the answer to title->lowercase, expected '%s' but got '%s'.", expected, got) } + + var emptyAns string + if expected, got := "", transformer(emptyAns); expected != got { + // TransformString transformers should be skipped and return zero value string + t.Errorf("TestComposeTransformers transformer failed to skip transforming on optional empty input, expected '%s' but got '%s'.", expected, got) + } }