From a485b9a263718a2af6db207d3f09aa16f8b86e6f Mon Sep 17 00:00:00 2001 From: Alexander Bezobchuk Date: Sun, 30 Jun 2019 16:31:09 -0400 Subject: [PATCH] Merge PR #4648: Flatten events by type when stringified --- types/events.go | 22 +++++++++++++++++++--- types/events_test.go | 18 ++++++++++++++++++ types/result.go | 2 +- 3 files changed, 38 insertions(+), 4 deletions(-) diff --git a/types/events.go b/types/events.go index a105c8d06618..a0d28db5d328 100644 --- a/types/events.go +++ b/types/events.go @@ -164,10 +164,26 @@ func (se StringEvents) String() string { return strings.TrimRight(sb.String(), "\n") } +// Flatten returns a flattened version of StringEvents by grouping all attributes +// per unique event type. +func (se StringEvents) Flatten() StringEvents { + flatEvents := make(map[string][]Attribute) + + for _, e := range se { + flatEvents[e.Type] = append(flatEvents[e.Type], e.Attributes...) + } + + var res StringEvents + for ty, attrs := range flatEvents { + res = append(res, StringEvent{Type: ty, Attributes: attrs}) + } + + return res +} + // StringifyEvent converts an Event object to a StringEvent object. func StringifyEvent(e abci.Event) StringEvent { - res := StringEvent{} - res.Type = e.Type + res := StringEvent{Type: e.Type} for _, attr := range e.Attributes { res.Attributes = append( @@ -188,5 +204,5 @@ func StringifyEvents(events []abci.Event) StringEvents { res = append(res, StringifyEvent(e)) } - return res + return res.Flatten() } diff --git a/types/events_test.go b/types/events_test.go index 538f1ed8bdfb..d00364eac0ba 100644 --- a/types/events_test.go +++ b/types/events_test.go @@ -1,6 +1,7 @@ package types import ( + "encoding/json" "testing" "github.com/stretchr/testify/require" @@ -51,3 +52,20 @@ func TestEventManager(t *testing.T) { require.Len(t, em.Events(), 2) require.Equal(t, em.Events(), events.AppendEvent(event)) } + +func TestStringifyEvents(t *testing.T) { + e := Events{ + NewEvent("message", NewAttribute("sender", "foo")), + NewEvent("message", NewAttribute("module", "bank")), + } + se := StringifyEvents(e.ToABCIEvents()) + + expectedTxtStr := "\t\t- message\n\t\t\t- sender: foo\n\t\t\t- module: bank" + require.Equal(t, expectedTxtStr, se.String()) + + bz, err := json.Marshal(se) + require.NoError(t, err) + + expectedJSONStr := "[{\"type\":\"message\",\"attributes\":[{\"key\":\"sender\",\"value\":\"foo\"},{\"key\":\"module\",\"value\":\"bank\"}]}]" + require.Equal(t, expectedJSONStr, string(bz)) +} diff --git a/types/result.go b/types/result.go index 31986f48ba1c..58ea83321ce4 100644 --- a/types/result.go +++ b/types/result.go @@ -240,7 +240,7 @@ func (r TxResponse) String() string { } if len(r.Events) > 0 { - sb.WriteString(fmt.Sprintf(" Tags: \n%s\n", r.Events.String())) + sb.WriteString(fmt.Sprintf(" Events: \n%s\n", r.Events.String())) } return strings.TrimSpace(sb.String())