Debian Codegraph @

proto/decode_test.go

raw
1 package proto
2
3 import (
4 "errors"
5 "io"
6 "testing"
7 )
8
9 func TestUnarshalFromShortBuffer(t *testing.T) {
10 m := message{
11 A: 1,
12 B: 2,
13 C: 3,
14 S: submessage{
15 X: "hello",
16 Y: "world",
17 },
18 }
19
20 b, _ := Marshal(m)
21
22 for i := range b {
23 switch i {
24 case 0, 2, 4, 6:
25 continue // these land on field boundaries, making the input valid
26 }
27 t.Run("", func(t *testing.T) {
28 msg := &message{}
29 err := Unmarshal(b[:i], msg)
30 if !errors.Is(err, io.ErrUnexpectedEOF) {
31 t.Errorf("error mismatch, want io.ErrUnexpectedEOF but got %q", err)
32 }
33 })
34 }
35 }
36
37 func TestUnmarshalFixture(t *testing.T) {
38 type Message struct {
39 A uint
40 B uint32
41 C uint64
42 D string
43 }
44
45 b := loadProtobuf(t, "message.pb")
46 m := Message{}
47
48 if err := Unmarshal(b, &m); err != nil {
49 t.Fatal(err)
50 }
51
52 if m.A != 10 {
53 t.Error("m.A mismatch, want 10 but got", m.A)
54 }
55
56 if m.B != 20 {
57 t.Error("m.B mismatch, want 20 but got", m.B)
58 }
59
60 if m.C != 30 {
61 t.Error("m.C mismatch, want 30 but got", m.C)
62 }
63
64 if m.D != "Hello World!" {
65 t.Errorf("m.D mismatch, want \"Hello World!\" but got %q", m.D)
66 }
67 }
68
69 func BenchmarkDecodeTag(b *testing.B) {
70 c := [8]byte{}
71 n, _ := encodeTag(c[:], 1, varint)
72
73 for range b.N {
74 decodeTag(c[:n])
75 }
76 }
77
78 func BenchmarkDecodeMessage(b *testing.B) {
79 data, _ := Marshal(message{
80 A: 1,
81 B: 100,
82 C: 10000,
83 S: submessage{
84 X: "",
85 Y: "Hello World!",
86 },
87 })
88
89 msg := message{}
90 b.SetBytes(int64(len(data)))
91
92 for range b.N {
93 if err := Unmarshal(data, &msg); err != nil {
94 b.Fatal(err)
95 }
96 msg = message{}
97 }
98 }
99
100 func BenchmarkDecodeMap(b *testing.B) {
101 type message struct {
102 M map[int]int
103 }
104
105 data, _ := Marshal(message{
106 M: map[int]int{
107 0: 0,
108 1: 1,
109 2: 2,
110 3: 3,
111 4: 4,
112 },
113 })
114
115 msg := message{}
116 b.SetBytes(int64(len(data)))
117
118 for range b.N {
119 if err := Unmarshal(data, &msg); err != nil {
120 b.Fatal(err)
121 }
122 msg = message{}
123 }
124 }
125
126 func BenchmarkDecodeSlice(b *testing.B) {
127 type message struct {
128 S []int
129 }
130
131 data, _ := Marshal(message{
132 S: []int{
133 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
134 },
135 })
136
137 msg := message{}
138 b.SetBytes(int64(len(data)))
139
140 for range b.N {
141 if err := Unmarshal(data, &msg); err != nil {
142 b.Fatal(err)
143 }
144 msg = message{}
145 }
146 }