-
Notifications
You must be signed in to change notification settings - Fork 0
/
message_test.go
77 lines (71 loc) · 2.66 KB
/
message_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
package opinionatedevents
import (
"encoding/json"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestMessageSerialization(t *testing.T) {
t.Run("marshals and unmarshals correctly", func(t *testing.T) {
// init the message
message, err := NewMessage("test.test", &testMessagePayload{Value: "42"})
assert.NoError(t, err)
// marshal and unmarshal it
serialized, err := message.MarshalJSON()
assert.NoError(t, err)
unserialized := &Message{}
err = json.Unmarshal(serialized, unserialized)
assert.NoError(t, err)
// assert that they are equal
assert.Equal(t, message.uuid, unserialized.uuid)
assert.Equal(t, message.name, unserialized.name)
assert.Equal(t, message.publishedAt.UTC().Format(time.RFC3339), unserialized.publishedAt.UTC().Format(time.RFC3339))
assert.Equal(t, message.payload, unserialized.payload)
// assert the payload
payload := &testMessagePayload{}
err = unserialized.GetPayload(payload)
assert.NoError(t, err)
assert.Equal(t, "42", payload.Value)
})
t.Run("unmarshals correctly when no deliver at present", func(t *testing.T) {
// unmarsal a message without deliver at
serialized := `{"name":"test","meta":{"uuid":"12345","published_at":"2021-10-10T12:32:00Z"},"payload":""}`
unserialized := &Message{}
err := json.Unmarshal([]byte(serialized), unserialized)
assert.NoError(t, err)
// assert other than deliver at
assert.Equal(t, "test", unserialized.name)
assert.Equal(t, "12345", unserialized.uuid)
assert.Equal(t, "2021-10-10T12:32:00Z", unserialized.publishedAt.UTC().Format(time.RFC3339))
// assert that deliver at is equal to published at
assert.Equal(t, unserialized.publishedAt.Unix(), unserialized.deliverAt.Unix())
})
t.Run("does not accept invalid JSON", func(t *testing.T) {
messages := []struct {
value string
valid bool
}{
// valid
{value: `{"name":"test","meta":{"uuid":"12345","published_at":"2021-10-10T12:32:00Z"},"payload":""}`, valid: true},
// missing name
{value: `{"meta":{"uuid":"12345","published_at":"2021-10-10T12:32:00Z"},"payload":""}`, valid: false},
// missing uuid
{value: `{"name":"test","meta":{"published_at":"2021-10-10T12:32:00Z"},"payload":""}`, valid: false},
// missing published at
{value: `{"name":"test","meta":{"uuid":"12345"},"payload":""}`, valid: false},
}
for i, message := range messages {
unserialized := &Message{}
err := json.Unmarshal([]byte(message.value), unserialized)
if message.valid {
assert.NoError(t, err, fmt.Sprintf("error at index %d\n", i))
} else {
assert.Error(t, err, fmt.Sprintf("error at index %d\n", i))
}
}
})
}
type testMessagePayload struct {
Value string `json:"value"`
}