forked from donovanhide/eventsource
-
Notifications
You must be signed in to change notification settings - Fork 8
/
codec_test.go
67 lines (60 loc) · 1.66 KB
/
codec_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
package eventsource
import (
"bytes"
"testing"
)
type testEvent struct {
id, event, data string
}
func (e *testEvent) Id() string { return e.id }
func (e *testEvent) Event() string { return e.event }
func (e *testEvent) Data() string { return e.data }
var encoderTests = []struct {
event *testEvent
output string
}{
{&testEvent{"1", "Add", "This is a test"}, "id: 1\nevent: Add\ndata: This is a test\n\n"},
{&testEvent{"", "", "This message, it\nhas two lines."}, "data: This message, it\ndata: has two lines.\n\n"},
}
func TestRoundTrip(t *testing.T) {
for _, tt := range encoderTests {
buf := new(bytes.Buffer)
enc := NewEncoder(buf, false)
want := tt.event
if err := enc.Encode(want); err != nil {
t.Fatal(err)
}
if buf.String() != tt.output {
t.Errorf("Expected: %s Got: %s", tt.output, buf.String())
}
dec := NewDecoder(buf)
ev, err := dec.Decode()
if err != nil {
t.Fatal(err)
}
if ev.Id() != want.Id() || ev.Event() != want.Event() || ev.Data() != want.Data() {
t.Errorf("Expected: %s %s %s Got: %s %s %s", want.Id(), want.Event(), want.Data(), ev.Id(), ev.Event(), ev.Data())
}
}
}
func TestEncodeComment(t *testing.T) {
buf := new(bytes.Buffer)
enc := NewEncoder(buf, false)
text := "This is a comment"
comm := comment{value: "This is a comment"}
expected := ":" + text + "\n"
if err := enc.Encode(comm); err != nil {
t.Fatal(err)
}
if buf.String() != expected {
t.Errorf("Expected: %s Got: %s", expected, buf.String())
}
}
func TestEncodeUnknownValue(t *testing.T) {
buf := new(bytes.Buffer)
enc := NewEncoder(buf, false)
badValue := 3
if err := enc.Encode(badValue); err == nil {
t.Error("Expected error")
}
}