Skip to content

Commit

Permalink
Improve ParseTime mismatched format and value
Browse files Browse the repository at this point in the history
  • Loading branch information
ddelemeny committed Apr 25, 2024
1 parent 8afe6fb commit 8511e91
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
15 changes: 10 additions & 5 deletions pkg/utils/parse_time.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
8 changes: 8 additions & 0 deletions pkg/utils/parse_time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
})
}

0 comments on commit 8511e91

Please sign in to comment.