Skip to content

Commit

Permalink
Merge PR #4648: Flatten events by type when stringified
Browse files Browse the repository at this point in the history
  • Loading branch information
alexanderbez authored Jun 30, 2019
1 parent 997c412 commit a485b9a
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 4 deletions.
22 changes: 19 additions & 3 deletions types/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -188,5 +204,5 @@ func StringifyEvents(events []abci.Event) StringEvents {
res = append(res, StringifyEvent(e))
}

return res
return res.Flatten()
}
18 changes: 18 additions & 0 deletions types/events_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package types

import (
"encoding/json"
"testing"

"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -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))
}
2 changes: 1 addition & 1 deletion types/result.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down

0 comments on commit a485b9a

Please sign in to comment.