ev/event/events_test.go

83 lines
1.5 KiB
Go
Raw Permalink Normal View History

2022-08-04 14:37:51 -06:00
package event_test
import (
"bytes"
2022-08-06 09:52:36 -06:00
"context"
2022-08-14 10:56:00 -06:00
"encoding/json"
2022-08-04 14:37:51 -06:00
"testing"
"github.com/matryer/is"
2023-09-29 10:07:24 -06:00
"go.sour.is/ev/event"
2022-08-04 14:37:51 -06:00
)
type DummyEvent struct {
Value string
2023-04-02 16:45:17 -06:00
event.IsEvent
2022-08-04 14:37:51 -06:00
}
2022-08-15 08:05:04 -06:00
func (e *DummyEvent) MarshalBinary() ([]byte, error) {
2022-08-14 10:56:00 -06:00
return json.Marshal(e)
}
2022-08-15 08:05:04 -06:00
func (e *DummyEvent) UnmarshalBinary(b []byte) error {
2022-08-14 10:56:00 -06:00
return json.Unmarshal(b, e)
}
2022-08-04 14:37:51 -06:00
func TestEventEncode(t *testing.T) {
is := is.New(t)
2022-08-06 09:52:36 -06:00
ctx := context.Background()
2022-08-04 14:37:51 -06:00
2022-08-06 09:52:36 -06:00
err := event.Register(ctx, &DummyEvent{})
is.NoErr(err)
2022-08-04 14:37:51 -06:00
var lis event.Events = event.NewEvents(
&DummyEvent{Value: "testA"},
&DummyEvent{Value: "testB"},
&DummyEvent{Value: "testC"},
)
lis.SetStreamID("test")
blis, err := event.EncodeEvents(lis...)
is.NoErr(err)
for _, b := range blis {
sp := bytes.SplitN(b, []byte{'\t'}, 4)
is.Equal(len(sp), 4)
is.Equal(string(sp[1]), "test")
is.Equal(string(sp[2]), "event_test.DummyEvent")
}
2022-08-06 09:52:36 -06:00
chk, err := event.DecodeEvents(ctx, blis...)
2022-08-04 14:37:51 -06:00
is.NoErr(err)
for i := range chk {
is.Equal(lis[i], chk[i])
}
}
2023-05-29 09:48:20 -06:00
type exampleAgg struct{ value string }
func (a *exampleAgg) ApplyEvent(lis ...event.Event) {
for _, e := range lis {
switch e := e.(type) {
case interface{ Payload() exampleEvSetValue }:
a.value = e.Payload().value
}
}
}
type exampleEvSetValue struct{ value string }
func TestApplyEventGeneric(t *testing.T) {
payload := &exampleAgg{}
var agg = event.AsAggregate(payload)
agg.ApplyEvent(event.NewEvents(
event.AsEvent(exampleEvSetValue{"hello"}),
)...)
is := is.New(t)
is.Equal(payload.value, "hello")
}