From 9106a3c76e375badd20947da4913b917e6033716 Mon Sep 17 00:00:00 2001 From: ferhat elmas Date: Thu, 18 Jun 2020 17:57:48 +0200 Subject: [PATCH] Improve the test of marshal for structs bug --- enriched_activities.go | 19 ++++++++++++------- types_test.go | 6 +++++- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/enriched_activities.go b/enriched_activities.go index 83b6f03..e488dfe 100644 --- a/enriched_activities.go +++ b/enriched_activities.go @@ -76,15 +76,20 @@ func (a *EnrichedActivity) UnmarshalJSON(b []byte) error { // MarshalJSON encodes the EnrichedActivity to a valid JSON bytes slice. It's required because of // the custom JSON fields and time formats. func (a EnrichedActivity) MarshalJSON() ([]byte, error) { - fields := structs.New(a).Fields() - data := make(map[string]interface{}, len(fields)) + s := structs.New(a) + fields := s.Fields() + data := s.Map() for _, f := range fields { - if f.Kind() == reflect.Struct { - tag := f.Tag("json") - if !strings.HasSuffix(tag, ",omitempty") || !structs.IsZero(f.Value()) { - data[strings.TrimSuffix(tag, ",omitempty")] = f.Value() - } + tag := f.Tag("json") + root := strings.TrimSuffix(tag, ",omitempty") + + if f.Kind() != reflect.Struct || + (strings.HasSuffix(tag, ",omitempty") && + structs.IsZero(f.Value())) { + continue } + + data[root] = f.Value() } for k, v := range a.Extra { data[k] = v diff --git a/types_test.go b/types_test.go index 477b274..1883676 100644 --- a/types_test.go +++ b/types_test.go @@ -42,9 +42,13 @@ func TestEnrichedActivityMarshal(t *testing.T) { ID: "my_id", Extra: map[string]interface{}{"a": 1, "b": "c"}, }, + ReactionCounts: map[string]int{ + "comment": 1, + }, + Score: 100.0, } b, err := json.Marshal(e) require.NoError(t, err) - require.JSONEq(t, `{"actor": {"id":"my_id","data":{"a":1,"b":"c"}}}`, string(b)) + require.JSONEq(t, `{"actor": {"id":"my_id","data":{"a":1,"b":"c"}},"reaction_counts":{"comment":1},"score":100.0}`, string(b)) }