Skip to content

Commit

Permalink
fixed a bug in msg decoder when time.Time was parsed as string
Browse files Browse the repository at this point in the history
  • Loading branch information
kopaygorodsky committed Sep 24, 2021
1 parent f7f5483 commit feb8e63
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 3 deletions.
30 changes: 27 additions & 3 deletions pubsub/message/decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"reflect"
"strings"
"time"

"github.com/go-foreman/foreman/runtime/scheme"
"github.com/mitchellh/mapstructure"
Expand Down Expand Up @@ -108,9 +109,10 @@ func (j jsonDecoder) decodeUnstructured(unstructured *Unstructured) (Object, err
}

decoderConf := mapstructure.DecoderConfig{
Squash: true,
TagName: "json",
Result: &nestedObj,
Squash: true,
TagName: "json",
DecodeHook: mapstructure.ComposeDecodeHookFunc(toTimeHookFunc()),
Result: &nestedObj,
}

decoder, err := mapstructure.NewDecoder(&decoderConf)
Expand Down Expand Up @@ -189,3 +191,25 @@ func (j jsonDecoder) setGroupKind(obj Object) error {

return nil
}

func toTimeHookFunc() mapstructure.DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
if t != reflect.TypeOf(time.Time{}) {
return data, nil
}

switch f.Kind() {
case reflect.String:
return time.Parse(time.RFC3339, data.(string))
case reflect.Float64:
return time.Unix(0, int64(data.(float64))*int64(time.Millisecond)), nil
case reflect.Int64:
return time.Unix(0, data.(int64)*int64(time.Millisecond)), nil
default:
return data, nil
}
}
}
22 changes: 22 additions & 0 deletions pubsub/message/decoder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"strings"
"testing"
"time"

"github.com/go-foreman/foreman/runtime/scheme"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -42,6 +43,11 @@ type WithAnon struct {
ChildType
}

type WithTime struct {
ObjectMeta
CreatedAt time.Time
}

type WithAnonAndJsonTag struct {
ObjectMeta
SomeVal int
Expand Down Expand Up @@ -161,6 +167,22 @@ func TestJsonDecoder(t *testing.T) {
assert.EqualValues(t, instance, decodedObj)
})

t.Run("encode and decode a struct with time", func(t *testing.T) {
knownRegistry.AddKnownTypes(group, &WithTime{})
instance := &WithTime{CreatedAt: time.Now()}

marshaled, err := decoder.Marshal(instance)
require.NoError(t, err)
assert.NotEmpty(t, marshaled)

decodedObj, err := decoder.Unmarshal(marshaled)
require.NoError(t, err)

decoded, _ := decodedObj.(*WithTime)

assert.True(t, instance.CreatedAt.Equal(decoded.CreatedAt))
})

//@todo these 2 cases should work too
//t.Run("squashing of an anonymous struct with json tag", func(t *testing.T) {
// knownRegistry.AddKnownTypes(group, &WithAnonAndJsonTag{})
Expand Down

0 comments on commit feb8e63

Please sign in to comment.