From 8511e91ae9944d8644c146209872eb7a7beb5208 Mon Sep 17 00:00:00 2001 From: Damien de Lemeny Date: Thu, 25 Apr 2024 16:15:02 -0500 Subject: [PATCH] Improve ParseTime mismatched format and value --- pkg/utils/parse_time.go | 15 ++++++++++----- pkg/utils/parse_time_test.go | 8 ++++++++ 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/pkg/utils/parse_time.go b/pkg/utils/parse_time.go index b8279d8..3f0fc0b 100644 --- a/pkg/utils/parse_time.go +++ b/pkg/utils/parse_time.go @@ -74,12 +74,17 @@ func ParseTime(value any, timeOutputFormat string) (time.Time, error) { return time.Unix(0, value_i64), nil } default: - value_string := value.(string) - timeValue, err := timefmt.Parse(value_string, timeOutputFormat) - if err != nil { - return time.Time{}, err + switch value.(type) { + case string: + value_string := value.(string) + timeValue, err := timefmt.Parse(value_string, timeOutputFormat) + if err != nil { + return time.Time{}, err + } + return timeValue, nil + default: + return time.Time{}, fmt.Errorf("ParseTime expected string value for custom parsing format: timeOutputFormat:%s, value:%s (%s)", timeOutputFormat, fmt.Sprint(value), reflect.TypeOf(value)) } - return timeValue, nil } return time.Time{}, fmt.Errorf("timeOutputFormat not supported yet %s", timeOutputFormat) } diff --git a/pkg/utils/parse_time_test.go b/pkg/utils/parse_time_test.go index cf538da..b00b370 100644 --- a/pkg/utils/parse_time_test.go +++ b/pkg/utils/parse_time_test.go @@ -71,4 +71,12 @@ func TestParseTime(t *testing.T) { } }) } + + t.Run("Error on incoherent format and value", func(t *testing.T) { + value := 1711629296987654321 + format := "%Y-%m-%d %H:%M:%S.%f" + _, err := ParseTime(value, format) + + assert.ErrorContains(err, fmt.Sprintf("ParseTime expected string value for custom parsing format: timeOutputFormat:%s, value:%s (%s)", format, fmt.Sprint(value), "int")) + }) }