-
Notifications
You must be signed in to change notification settings - Fork 6
/
decoder_test.go
74 lines (63 loc) · 2 KB
/
decoder_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
package encoding
import (
"bytes"
"io"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
// TestDecoder tests that we can decode a trace without errors.
// This does not check the correctness of the events, just that we can decode them.
// The correctness of the events is checked in the TestDecodeEncode test.
func TestDecoder(t *testing.T) {
// Read the test trace.
data, err := os.ReadFile(filepath.Join("..", "..", "testdata", "trace.bin"))
require.NoError(t, err)
// Create a decoder
dec := NewDecoder(bytes.NewReader(data))
// Decode each event and count them.
var count int
for {
e := Event{}
if err := dec.Decode(&e); err != nil {
require.Equal(t, io.EOF, err)
break
}
count++
}
// Check that we decoded the correct number of events.
require.Equal(t, 151, count)
}
// TestDecodeEncode tests that we can decode and encode a trace.
// This is a round-trip test that checks that the encoded trace is the same as
// the original.
func TestDecodeEncode(t *testing.T) {
// Read the test trace.
inTrace, err := os.ReadFile(filepath.Join("..", "..", "testdata", "trace.bin"))
require.NoError(t, err)
// Create a decoder
dec := NewDecoder(bytes.NewReader(inTrace))
// Create an encoder
var outTrace bytes.Buffer
enc := NewEncoder(&outTrace)
// Decode and encode each event.
for {
beforeLen := outTrace.Len()
e := Event{}
if err := dec.Decode(&e); err != nil {
require.Equal(t, io.EOF, err)
break
}
require.NoError(t, enc.Encode(&e))
// Check output after each event to understand errors without having to
// diff the whole binary output.
gotEncoded := outTrace.Bytes()[beforeLen:]
wantEncoded := inTrace[beforeLen : beforeLen+len(gotEncoded)]
require.Equal(t, wantEncoded, gotEncoded, "failed to encode event: %v", e)
}
// Check that the length of the encoded trace is the same as the original.
require.Equal(t, len(inTrace), outTrace.Len())
// Check that the encoded trace is the same as the original.
require.Equal(t, inTrace, outTrace.Bytes())
}