Skip to content
Prev Previous commit
Next Next commit
Fix Unmarshal(nil) error and add tests for ParsePayload on a zero-val…
…ue Event{}
  • Loading branch information
evankanderson committed Aug 10, 2023
commit 2b545ee043cfceef526df2be5ad97add46c2778e
12 changes: 8 additions & 4 deletions github/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,16 @@ func (e Event) String() string {

// ParsePayload parses the event payload. For recognized event types,
// a value of the corresponding struct type will be returned.
func (e *Event) ParsePayload() (interface{}, error) {
func (e *Event) ParsePayload() (payload interface{}, err error) {
// It would be nice if e.Type were the snake_case name of the event,
// but the existing interface uses the struct name instead.
payload := EventForType(typeToMessageMapping[e.GetType()])
err := json.Unmarshal(*e.RawPayload, &payload)
return payload, err
typed := EventForType(typeToMessageMapping[e.GetType()])
if typed != nil {
payload = typed
}
err = json.Unmarshal(e.GetRawPayload(), &payload)

return
}

// Payload returns the parsed event payload. For recognized event types,
Expand Down
5 changes: 5 additions & 0 deletions github/event_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ func TestPayload_NoPanic(t *testing.T) {
e.Payload()
}

func TestEmptyEvent_NoPanic(t *testing.T) {
e := &Event{}
e.ParsePayload()
}

func TestEvent_Marshal(t *testing.T) {
testJSONMarshal(t, &Event{}, "{}")

Expand Down
9 changes: 9 additions & 0 deletions github/messages_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,15 @@ func TestAllMessageTypesMapped(t *testing.T) {
}
}

func TestUnknownMessageType(t *testing.T) {
if obj := EventForType("unknown"); obj != nil {
t.Errorf("EventForType(unknown) = %#v, want nil", obj)
}
if obj := EventForType(""); obj != nil {
t.Errorf(`EventForType("") = %#v, want nil`, obj)
}
}

func TestParseWebHook_BadMessageType(t *testing.T) {
if _, err := ParseWebHook("bogus message type", []byte("{}")); err == nil {
t.Fatal("ParseWebHook returned nil; wanted error")
Expand Down