blob: 69ae0cc2783a85fc1e441f4acbc3e98b479f6b8d [file] [log] [blame]
Rob Pikeaaa3a622010-03-20 22:32:34 -07001// Go support for Protocol Buffers - Google's data interchange format
2//
David Symondsee6e9c52012-11-29 08:51:07 +11003// Copyright 2010 The Go Authors. All rights reserved.
Rob Pikeaaa3a622010-03-20 22:32:34 -07004// http://code.google.com/p/goprotobuf/
5//
6// Redistribution and use in source and binary forms, with or without
7// modification, are permitted provided that the following conditions are
8// met:
9//
10// * Redistributions of source code must retain the above copyright
11// notice, this list of conditions and the following disclaimer.
12// * Redistributions in binary form must reproduce the above
13// copyright notice, this list of conditions and the following disclaimer
14// in the documentation and/or other materials provided with the
15// distribution.
16// * Neither the name of Google Inc. nor the names of its
17// contributors may be used to endorse or promote products derived from
18// this software without specific prior written permission.
19//
20// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32package proto_test
33
34import (
35 "bytes"
David Symonds4dc589e2012-12-06 14:05:48 +110036 "errors"
37 "io/ioutil"
David Symonds1d72f7a2011-08-19 18:28:52 +100038 "strings"
Rob Pikeaaa3a622010-03-20 22:32:34 -070039 "testing"
David Symondsaa922ff2011-07-19 14:58:06 +100040
Rob Pike3f6f2d82011-12-18 13:55:35 -080041 "code.google.com/p/goprotobuf/proto"
David Symondsaa922ff2011-07-19 14:58:06 +100042
David Symonds704096f2012-03-15 15:10:26 +110043 pb "./testdata"
Rob Pikeaaa3a622010-03-20 22:32:34 -070044)
45
David Symondsaa922ff2011-07-19 14:58:06 +100046func newTestMessage() *pb.MyMessage {
47 msg := &pb.MyMessage{
48 Count: proto.Int32(42),
49 Name: proto.String("Dave"),
50 Quote: proto.String(`"I didn't want to go."`),
Rob Pike9caa5b92010-05-11 16:04:57 -070051 Pet: []string{"bunny", "kitty", "horsey"},
David Symondsaa922ff2011-07-19 14:58:06 +100052 Inner: &pb.InnerMessage{
53 Host: proto.String("footrest.syd"),
54 Port: proto.Int32(7001),
55 Connected: proto.Bool(true),
Rob Pikeaaa3a622010-03-20 22:32:34 -070056 },
David Symondsaa922ff2011-07-19 14:58:06 +100057 Others: []*pb.OtherMessage{
David Symonds92dd6c12012-03-23 10:59:49 +110058 {
David Symondsaa922ff2011-07-19 14:58:06 +100059 Key: proto.Int64(0xdeadbeef),
Rob Pikeaaa3a622010-03-20 22:32:34 -070060 Value: []byte{1, 65, 7, 12},
61 },
David Symonds92dd6c12012-03-23 10:59:49 +110062 {
David Symondsaa922ff2011-07-19 14:58:06 +100063 Weight: proto.Float32(6.022),
64 Inner: &pb.InnerMessage{
65 Host: proto.String("lesha.mtv"),
66 Port: proto.Int32(8002),
Rob Pikeaaa3a622010-03-20 22:32:34 -070067 },
68 },
69 },
David Symondsefeca9a2012-05-08 10:36:04 +100070 Bikeshed: pb.MyMessage_BLUE.Enum(),
David Symondsaa922ff2011-07-19 14:58:06 +100071 Somegroup: &pb.MyMessage_SomeGroup{
72 GroupField: proto.Int32(8),
David Symonds9f402812011-04-28 18:08:44 +100073 },
David Symonds1d72f7a2011-08-19 18:28:52 +100074 // One normally wouldn't do this.
75 // This is an undeclared tag 13, as a varint (wire type 0) with value 4.
76 XXX_unrecognized: []byte{13<<3 | 0, 4},
Rob Pikeaaa3a622010-03-20 22:32:34 -070077 }
David Symondsaa922ff2011-07-19 14:58:06 +100078 ext := &pb.Ext{
79 Data: proto.String("Big gobs for big rats"),
David Symondse37856c2011-06-22 12:52:53 +100080 }
David Symondsaa922ff2011-07-19 14:58:06 +100081 if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil {
David Symondse37856c2011-06-22 12:52:53 +100082 panic(err)
83 }
David Symonds61826da2012-05-05 09:31:28 +100084 greetings := []string{"adg", "easy", "cow"}
85 if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil {
86 panic(err)
87 }
David Symonds1d72f7a2011-08-19 18:28:52 +100088
89 // Add an unknown extension. We marshal a pb.Ext, and fake the ID.
90 b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")})
91 if err != nil {
92 panic(err)
93 }
David Symonds54531052011-12-08 12:00:31 +110094 b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...)
95 proto.SetRawExtension(msg, 201, b)
David Symonds1d72f7a2011-08-19 18:28:52 +100096
97 // Extensions can be plain fields, too, so let's test that.
David Symonds54531052011-12-08 12:00:31 +110098 b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19)
99 proto.SetRawExtension(msg, 202, b)
David Symonds1d72f7a2011-08-19 18:28:52 +1000100
David Symondse37856c2011-06-22 12:52:53 +1000101 return msg
Rob Pikeaaa3a622010-03-20 22:32:34 -0700102}
103
104const text = `count: 42
105name: "Dave"
106quote: "\"I didn't want to go.\""
107pet: "bunny"
108pet: "kitty"
109pet: "horsey"
110inner: <
111 host: "footrest.syd"
112 port: 7001
113 connected: true
114>
115others: <
116 key: 3735928559
David Symonds4c95bfe2011-09-13 14:43:27 +1000117 value: "\001A\007\014"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700118>
119others: <
120 weight: 6.022
121 inner: <
122 host: "lesha.mtv"
123 port: 8002
124 >
125>
126bikeshed: BLUE
David Symonds9f402812011-04-28 18:08:44 +1000127SomeGroup {
128 group_field: 8
129}
David Symonds1d72f7a2011-08-19 18:28:52 +1000130/* 2 unknown bytes */
131tag13: 4
Rob Pikeb7907bf2012-02-13 14:25:20 +1100132[testdata.Ext.more]: <
David Symondse37856c2011-06-22 12:52:53 +1000133 data: "Big gobs for big rats"
134>
David Symonds61826da2012-05-05 09:31:28 +1000135[testdata.greeting]: "adg"
136[testdata.greeting]: "easy"
137[testdata.greeting]: "cow"
David Symonds1d72f7a2011-08-19 18:28:52 +1000138/* 13 unknown bytes */
David Symonds54531052011-12-08 12:00:31 +1100139tag201: "\t3G skiing"
David Symonds1d72f7a2011-08-19 18:28:52 +1000140/* 3 unknown bytes */
David Symonds54531052011-12-08 12:00:31 +1100141tag202: 19
Rob Pikeaaa3a622010-03-20 22:32:34 -0700142`
143
David Symonds4dc589e2012-12-06 14:05:48 +1100144func TestMarshalText(t *testing.T) {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700145 buf := new(bytes.Buffer)
David Symonds4dc589e2012-12-06 14:05:48 +1100146 if err := proto.MarshalText(buf, newTestMessage()); err != nil {
147 t.Fatalf("proto.MarshalText: %v", err)
148 }
Rob Pikeaaa3a622010-03-20 22:32:34 -0700149 s := buf.String()
150 if s != text {
151 t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, text)
152 }
153}
154
David Symonds4dc589e2012-12-06 14:05:48 +1100155func BenchmarkMarshalTextBuffered(b *testing.B) {
David Symondsdbdc4212012-11-08 08:20:35 +1100156 buf := new(bytes.Buffer)
157 m := newTestMessage()
158 for i := 0; i < b.N; i++ {
159 buf.Reset()
160 proto.MarshalText(buf, m)
161 }
162}
163
David Symonds4dc589e2012-12-06 14:05:48 +1100164func BenchmarkMarshalTextUnbuffered(b *testing.B) {
165 w := ioutil.Discard
166 m := newTestMessage()
167 for i := 0; i < b.N; i++ {
168 proto.MarshalText(w, m)
169 }
170}
171
Rob Pikeaaa3a622010-03-20 22:32:34 -0700172func compact(src string) string {
David Symondse37856c2011-06-22 12:52:53 +1000173 // s/[ \n]+/ /g; s/ $//;
Rob Pikeaaa3a622010-03-20 22:32:34 -0700174 dst := make([]byte, len(src))
David Symonds1d72f7a2011-08-19 18:28:52 +1000175 space, comment := false, false
Rob Pikeaaa3a622010-03-20 22:32:34 -0700176 j := 0
177 for i := 0; i < len(src); i++ {
David Symonds1d72f7a2011-08-19 18:28:52 +1000178 if strings.HasPrefix(src[i:], "/*") {
179 comment = true
180 i++
181 continue
182 }
183 if comment && strings.HasPrefix(src[i:], "*/") {
184 comment = false
185 i++
186 continue
187 }
188 if comment {
189 continue
190 }
Rob Pikeaaa3a622010-03-20 22:32:34 -0700191 c := src[i]
192 if c == ' ' || c == '\n' {
193 space = true
194 continue
195 }
David Symonds9f402812011-04-28 18:08:44 +1000196 if j > 0 && (dst[j-1] == ':' || dst[j-1] == '<' || dst[j-1] == '{') {
197 space = false
198 }
199 if c == '{' {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700200 space = false
201 }
202 if space {
203 dst[j] = ' '
204 j++
205 space = false
206 }
207 dst[j] = c
208 j++
209 }
210 if space {
211 dst[j] = ' '
212 j++
213 }
214 return string(dst[0:j])
215}
216
217var compactText = compact(text)
218
219func TestCompactText(t *testing.T) {
David Symondsaa922ff2011-07-19 14:58:06 +1000220 s := proto.CompactTextString(newTestMessage())
Rob Pikeaaa3a622010-03-20 22:32:34 -0700221 if s != compactText {
David Symonds4c95bfe2011-09-13 14:43:27 +1000222 t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v\n===\n", s, compactText)
223 }
224}
225
226func TestStringEscaping(t *testing.T) {
227 testCases := []struct {
228 in *pb.Strings
229 out string
230 }{
231 {
232 // Test data from C++ test (TextFormatTest.StringEscape).
233 // Single divergence: we don't escape apostrophes.
234 &pb.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces")},
235 "string_field: \"\\\"A string with ' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"\n",
236 },
237 {
238 // Test data from the same C++ test.
239 &pb.Strings{StringField: proto.String("\350\260\267\346\255\214")},
240 "string_field: \"\\350\\260\\267\\346\\255\\214\"\n",
241 },
David Symondsfa94a1e2012-09-24 13:21:49 +1000242 {
243 // Some UTF-8.
244 &pb.Strings{StringField: proto.String("\x00\x01\xff\x81")},
245 `string_field: "\000\001\377\201"` + "\n",
246 },
David Symonds4c95bfe2011-09-13 14:43:27 +1000247 }
248
249 for i, tc := range testCases {
250 var buf bytes.Buffer
David Symonds4dc589e2012-12-06 14:05:48 +1100251 if err := proto.MarshalText(&buf, tc.in); err != nil {
252 t.Errorf("proto.MarsalText: %v", err)
253 continue
254 }
David Symondsfa94a1e2012-09-24 13:21:49 +1000255 s := buf.String()
256 if s != tc.out {
David Symonds4c95bfe2011-09-13 14:43:27 +1000257 t.Errorf("#%d: Got:\n%s\nExpected:\n%s\n", i, s, tc.out)
David Symondsfa94a1e2012-09-24 13:21:49 +1000258 continue
259 }
260
261 // Check round-trip.
262 pb := new(pb.Strings)
263 if err := proto.UnmarshalText(s, pb); err != nil {
264 t.Errorf("#%d: UnmarshalText: %v", i, err)
265 continue
266 }
267 if !proto.Equal(pb, tc.in) {
268 t.Errorf("#%d: Round-trip failed:\nstart: %v\n end: %v", i, tc.in, pb)
David Symonds4c95bfe2011-09-13 14:43:27 +1000269 }
Rob Pikeaaa3a622010-03-20 22:32:34 -0700270 }
271}
David Symonds4dc589e2012-12-06 14:05:48 +1100272
273// A limitedWriter accepts some output before it fails.
274// This is a proxy for something like a nearly-full or imminently-failing disk,
275// or a network connection that is about to die.
276type limitedWriter struct {
277 b bytes.Buffer
278 limit int
279}
280
281var outOfSpace = errors.New("insufficient space")
282
283func (w *limitedWriter) Write(p []byte) (n int, err error) {
284 var avail = w.limit - w.b.Len()
285 if avail <= 0 {
286 return 0, outOfSpace
287 }
288 if len(p) <= avail {
289 return w.b.Write(p)
290 }
291 n, _ = w.b.Write(p[:avail])
292 return n, outOfSpace
293}
294
295func TestMarshalTextFailing(t *testing.T) {
296 // Try lots of different sizes to exercise more error code-paths.
297 for lim := 0; lim < len(text); lim++ {
298 buf := new(limitedWriter)
299 buf.limit = lim
300 err := proto.MarshalText(buf, newTestMessage())
301 // We expect a certain error, but also some partial results in the buffer.
302 if err != outOfSpace {
303 t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", err, outOfSpace)
304 }
305 s := buf.b.String()
306 x := text[:buf.limit]
307 if s != x {
308 t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, x)
309 }
310 }
311}