forked from hallgren/eventsourcing
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserializer_test.go
118 lines (105 loc) · 2.58 KB
/
serializer_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package eventsourcing_test
import (
"encoding/json"
"reflect"
"sync"
"testing"
"github.com/hallgren/eventsourcing"
)
func initSerializers(t *testing.T) []*eventsourcing.Serializer {
var result []*eventsourcing.Serializer
s := eventsourcing.NewSerializer(json.Marshal, json.Unmarshal)
err := s.Register(&SomeAggregate{}, s.Events(&SomeData{}, &SomeData2{}))
if err != nil {
t.Fatalf("could not register aggregate events %v", err)
}
result = append(result, s)
return result
}
type SomeAggregate struct {
eventsourcing.AggregateRoot
}
func (s *SomeAggregate) Transition(event eventsourcing.Event) {}
type SomeData struct {
A int
B string
}
type SomeData2 struct {
A int
B string
}
var data = SomeData{
1,
"b",
}
var metaData = make(map[string]interface{})
func TestSerializeDeserialize(t *testing.T) {
serializers := initSerializers(t)
metaData["foo"] = "bar"
for _, s := range serializers {
t.Run(reflect.TypeOf(s).Elem().Name(), func(t *testing.T) {
d, err := s.Marshal(data)
if err != nil {
t.Fatalf("could not Marshal data, %v", err)
}
f, ok := s.Type("SomeAggregate", "SomeData")
if !ok {
t.Fatal("could not find event type registered for SomeAggregate/SomeData")
}
data2 := f()
err = s.Unmarshal(d, &data2)
if err != nil {
t.Fatalf("Could not Unmarshal data, %v", err)
}
/*
if data2.A != data.A {
t.Fatalf("wrong value in A expected: %d, actual: %d", data.A, data2.A)
}
*/
m, err := s.Marshal(metaData)
if err != nil {
t.Fatalf("could not Marshal metadata, %v", err)
}
metaData2 := map[string]interface{}{}
err = s.Unmarshal(m, &metaData2)
if err != nil {
t.Fatalf("Could not Unmarshal metadata, %v", err)
}
if metaData["foo"] != metaData2["foo"] {
t.Fatalf("wrong value in metadata key foo expected: bar, actual: %v", metaData2["foo"])
}
})
}
}
func TestConcurrentUnmarshal(t *testing.T) {
serializers := initSerializers(t)
metaData["foo"] = "bar"
for _, s := range serializers {
d, err := s.Marshal(data)
if err != nil {
t.Fatalf("could not Marshal data, %v", err)
}
wg := sync.WaitGroup{}
wg.Add(10)
for i := 0; i < 10; i++ {
go func(j int) {
defer wg.Done()
f, ok := s.Type("SomeAggregate", "SomeData")
if !ok {
t.Fatal("could not find event type registered for SomeAggregate/SomeData")
}
dataOut := f()
err2 := s.Unmarshal(d, &dataOut)
if err2 != nil {
t.Errorf("Could not Unmarshal data, %v", err2)
}
switch dataOut.(type) {
case *SomeData:
default:
t.Errorf("wrong type")
}
}(i)
}
wg.Wait()
}
}