File: cbor_test.go

package info (click to toggle)
golang-github-ugorji-go-codec 1.2.8-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bookworm-proposed-updates, experimental, forky, sid, trixie
  • size: 2,532 kB
  • sloc: sh: 462; python: 100; makefile: 4
file content (399 lines) | stat: -rw-r--r-- 10,552 bytes parent folder | download
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
// Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.

package codec

import (
	"bufio"
	"bytes"
	"encoding/hex"
	"math"
	"os"
	"reflect"
	"regexp"
	"strings"
	"testing"
)

func TestCborIndefiniteLength(t *testing.T) {
	var h Handle = testCborH
	defer testSetup(t, &h)()
	bh := testBasicHandle(h)
	defer func(oldMapType reflect.Type) {
		bh.MapType = oldMapType
	}(bh.MapType)
	bh.MapType = testMapStrIntfTyp
	// var (
	// 	M1 map[string][]byte
	// 	M2 map[uint64]bool
	// 	L1 []interface{}
	// 	S1 []string
	// 	B1 []byte
	// )
	var v, vv interface{}
	// define it (v), encode it using indefinite lengths, decode it (vv), compare v to vv
	v = map[string]interface{}{
		"one-byte-key":   []byte{1, 2, 3, 4, 5, 6},
		"two-string-key": "two-value",
		"three-list-key": []interface{}{true, false, uint64(1), int64(-1)},
	}
	var buf bytes.Buffer
	// buf.Reset()
	e := NewEncoder(&buf, h)
	buf.WriteByte(cborBdIndefiniteMap)
	//----
	buf.WriteByte(cborBdIndefiniteString)
	e.MustEncode("one-")
	e.MustEncode("byte-")
	e.MustEncode("key")
	buf.WriteByte(cborBdBreak)

	buf.WriteByte(cborBdIndefiniteBytes)
	e.MustEncode([]byte{1, 2, 3})
	e.MustEncode([]byte{4, 5, 6})
	buf.WriteByte(cborBdBreak)

	//----
	buf.WriteByte(cborBdIndefiniteString)
	e.MustEncode("two-")
	e.MustEncode("string-")
	e.MustEncode("key")
	buf.WriteByte(cborBdBreak)

	buf.WriteByte(cborBdIndefiniteString)
	e.MustEncode([]byte("two-")) // encode as bytes, to check robustness of code
	e.MustEncode([]byte("value"))
	buf.WriteByte(cborBdBreak)

	//----
	buf.WriteByte(cborBdIndefiniteString)
	e.MustEncode("three-")
	e.MustEncode("list-")
	e.MustEncode("key")
	buf.WriteByte(cborBdBreak)

	buf.WriteByte(cborBdIndefiniteArray)
	e.MustEncode(true)
	e.MustEncode(false)
	e.MustEncode(uint64(1))
	e.MustEncode(int64(-1))
	buf.WriteByte(cborBdBreak)

	buf.WriteByte(cborBdBreak) // close map

	NewDecoderBytes(buf.Bytes(), h).MustDecode(&vv)
	if err := deepEqual(v, vv); err != nil {
		t.Logf("-------- Before and After marshal do not match: Error: %v", err)
		if testVerbose {
			t.Logf("    ....... GOLDEN:  (%T) %#v", v, v)
			t.Logf("    ....... DECODED: (%T) %#v", vv, vv)
		}
		t.FailNow()
	}
}

type testCborGolden struct {
	Base64     string      `codec:"cbor"`
	Hex        string      `codec:"hex"`
	Roundtrip  bool        `codec:"roundtrip"`
	Decoded    interface{} `codec:"decoded"`
	Diagnostic string      `codec:"diagnostic"`
	Skip       bool        `codec:"skip"`
}

// Some tests are skipped because they include numbers outside the range of int64/uint64
func TestCborGoldens(t *testing.T) {
	var h Handle = testCborH
	defer testSetup(t, &h)()
	bh := testBasicHandle(h)
	defer func(oldMapType reflect.Type) {
		bh.MapType = oldMapType
	}(bh.MapType)
	bh.MapType = testMapStrIntfTyp

	// decode test-cbor-goldens.json into a list of []*testCborGolden
	// for each one,
	// - decode hex into []byte bs
	// - decode bs into interface{} v
	// - compare both using deepequal
	// - for any miss, record it
	var gs []*testCborGolden
	f, err := os.Open("test-cbor-goldens.json")
	if err != nil {
		t.Logf("error opening test-cbor-goldens.json: %v", err)
		t.FailNow()
	}
	defer f.Close()
	jh := new(JsonHandle)
	jh.MapType = testMapStrIntfTyp
	// d := NewDecoder(f, jh)
	d := NewDecoder(bufio.NewReader(f), jh)
	// err = d.Decode(&gs)
	d.MustDecode(&gs)
	if err != nil {
		t.Logf("error json decoding test-cbor-goldens.json: %v", err)
		t.FailNow()
	}

	tagregex := regexp.MustCompile(`[\d]+\(.+?\)`)
	hexregex := regexp.MustCompile(`h'([0-9a-fA-F]*)'`)
	for i, g := range gs {
		// fmt.Printf("%v, skip: %v, isTag: %v, %s\n", i, g.Skip, tagregex.MatchString(g.Diagnostic), g.Diagnostic)
		// skip tags or simple or those with prefix, as we can't verify them.
		if g.Skip || strings.HasPrefix(g.Diagnostic, "simple(") || tagregex.MatchString(g.Diagnostic) {
			// fmt.Printf("%v: skipped\n", i)
			if testVerbose {
				t.Logf("[%v] skipping because skip=true OR unsupported simple value or Tag Value", i)
			}
			continue
		}
		// println("++++++++++++", i, "g.Diagnostic", g.Diagnostic)
		if hexregex.MatchString(g.Diagnostic) {
			// println(i, "g.Diagnostic matched hex")
			if s2 := g.Diagnostic[2 : len(g.Diagnostic)-1]; s2 == "" {
				g.Decoded = zeroByteSlice
			} else if bs2, err2 := hex.DecodeString(s2); err2 == nil {
				g.Decoded = bs2
			}
			// fmt.Printf("%v: hex: %v\n", i, g.Decoded)
		}
		bs, err := hex.DecodeString(g.Hex)
		if err != nil {
			t.Logf("[%v] error hex decoding %s [%v]: %v", i, g.Hex, g.Hex, err)
			t.FailNow()
		}
		var v interface{}
		NewDecoderBytes(bs, h).MustDecode(&v)
		if _, ok := v.(RawExt); ok {
			continue
		}
		// check the diagnostics to compare
		switch g.Diagnostic {
		case "Infinity":
			b := math.IsInf(v.(float64), 1)
			testCborError(t, i, math.Inf(1), v, nil, &b)
		case "-Infinity":
			b := math.IsInf(v.(float64), -1)
			testCborError(t, i, math.Inf(-1), v, nil, &b)
		case "NaN":
			// println(i, "checking NaN")
			b := math.IsNaN(v.(float64))
			testCborError(t, i, math.NaN(), v, nil, &b)
		case "undefined":
			b := v == nil
			testCborError(t, i, nil, v, nil, &b)
		default:
			v0 := g.Decoded
			// testCborCoerceJsonNumber(reflect.ValueOf(&v0))
			testCborError(t, i, v0, v, deepEqual(v0, v), nil)
		}
	}
}

func testCborError(t *testing.T, i int, v0, v1 interface{}, err error, equal *bool) {
	if err == nil && equal == nil {
		// fmt.Printf("%v testCborError passed (err and equal nil)\n", i)
		return
	}
	if err != nil {
		t.Logf("[%v] deepEqual error: %v", i, err)
		if testVerbose {
			t.Logf("    ....... GOLDEN:  (%T) %#v", v0, v0)
			t.Logf("    ....... DECODED: (%T) %#v", v1, v1)
		}
		t.FailNow()
	}
	if equal != nil && !*equal {
		t.Logf("[%v] values not equal", i)
		if testVerbose {
			t.Logf("    ....... GOLDEN:  (%T) %#v", v0, v0)
			t.Logf("    ....... DECODED: (%T) %#v", v1, v1)
		}
		t.FailNow()
	}
	// fmt.Printf("%v testCborError passed (checks passed)\n", i)
}

func TestCborHalfFloat(t *testing.T) {
	var h Handle = testCborH
	defer testSetup(t, &h)()
	m := map[uint16]float64{
		// using examples from
		// https://en.wikipedia.org/wiki/Half-precision_floating-point_format
		0x3c00: 1,
		0x3c01: 1 + math.Pow(2, -10),
		0xc000: -2,
		0x7bff: 65504,
		0x0400: math.Pow(2, -14),
		0x03ff: math.Pow(2, -14) - math.Pow(2, -24),
		0x0001: math.Pow(2, -24),
		0x0000: 0,
		0x8000: -0.0,
	}
	var ba [3]byte
	ba[0] = cborBdFloat16
	var res float64
	for k, v := range m {
		res = 0
		bigenstd.PutUint16(ba[1:], k)
		testUnmarshalErr(&res, ba[:3], h, t, "-")
		if res == v {
			if testVerbose {
				t.Logf("equal floats: from %x %b, %v", k, k, v)
			}
		} else {
			t.Logf("unequal floats: from %x %b, %v != %v", k, k, res, v)
			t.FailNow()
		}
	}
}

func TestCborSkipTags(t *testing.T) {
	defer testSetup(t, nil)()
	type Tcbortags struct {
		A string
		M map[string]interface{}
		// A []interface{}
	}
	var b8 [8]byte
	var w bytesEncAppender
	w.b = []byte{}

	// To make it easier,
	//    - use tags between math.MaxUint8 and math.MaxUint16 (incl SelfDesc)
	//    - use 1 char strings for key names
	//    - use 3-6 char strings for map keys
	//    - use integers that fit in 2 bytes (between 0x20 and 0xff)

	var tags = [...]uint64{math.MaxUint8 * 2, math.MaxUint8 * 8, 55799, math.MaxUint16 / 2}
	var tagIdx int
	var doAddTag bool
	addTagFn8To16 := func() {
		if !doAddTag {
			return
		}
		// writes a tag between MaxUint8 and MaxUint16 (culled from cborEncDriver.encUint)
		w.writen1(cborBaseTag + 0x19)
		// bigenHelper.writeUint16
		bigenstd.PutUint16(b8[:2], uint16(tags[tagIdx%len(tags)]))
		w.writeb(b8[:2])
		tagIdx++
	}

	var v Tcbortags
	v.A = "cbor"
	v.M = make(map[string]interface{})
	v.M["111"] = uint64(111)
	v.M["111.11"] = 111.11
	v.M["true"] = true
	// v.A = append(v.A, 222, 22.22, "true")

	// make stream manually (interspacing tags around it)
	// WriteMapStart - e.encLen(cborBaseMap, length) - encUint(length, bd)
	// EncodeStringEnc - e.encStringBytesS(cborBaseString, v)

	fnEncode := func() {
		w.b = w.b[:0]
		addTagFn8To16()
		// write v (Tcbortags, with 3 fields = map with 3 entries)
		w.writen1(2 + cborBaseMap) // 3 fields = 3 entries
		// write v.A
		var s = "A"
		w.writen1(byte(len(s)) + cborBaseString)
		w.writestr(s)
		w.writen1(byte(len(v.A)) + cborBaseString)
		w.writestr(v.A)
		//w.writen1(0)

		addTagFn8To16()
		s = "M"
		w.writen1(byte(len(s)) + cborBaseString)
		w.writestr(s)

		addTagFn8To16()
		w.writen1(byte(len(v.M)) + cborBaseMap)

		addTagFn8To16()
		s = "111"
		w.writen1(byte(len(s)) + cborBaseString)
		w.writestr(s)
		w.writen2(cborBaseUint+0x18, uint8(111))

		addTagFn8To16()
		s = "111.11"
		w.writen1(byte(len(s)) + cborBaseString)
		w.writestr(s)
		w.writen1(cborBdFloat64)
		bigenstd.PutUint64(b8[:8], math.Float64bits(111.11))
		w.writeb(b8[:8])

		addTagFn8To16()
		s = "true"
		w.writen1(byte(len(s)) + cborBaseString)
		w.writestr(s)
		w.writen1(cborBdTrue)
	}

	var h CborHandle
	h.SkipUnexpectedTags = true
	h.Canonical = true

	var gold []byte
	NewEncoderBytes(&gold, &h).MustEncode(v)
	// xdebug2f("encoded:    gold: %v", gold)

	// w.b is the encoded bytes
	var v2 Tcbortags
	doAddTag = false
	fnEncode()
	// xdebug2f("manual:  no-tags: %v", w.b)

	testDeepEqualErr(gold, w.b, t, "cbor-skip-tags--bytes---")
	NewDecoderBytes(w.b, &h).MustDecode(&v2)
	testDeepEqualErr(v, v2, t, "cbor-skip-tags--no-tags-")

	var v3 Tcbortags
	doAddTag = true
	fnEncode()
	// xdebug2f("manual: has-tags: %v", w.b)
	NewDecoderBytes(w.b, &h).MustDecode(&v3)
	testDeepEqualErr(v, v2, t, "cbor-skip-tags--has-tags")

	// Github 300 - tests naked path
	{
		expected := []interface{}{"x", uint64(0x0)}
		toDecode := []byte{0x82, 0x61, 0x78, 0x00}

		var raw interface{}

		NewDecoderBytes(toDecode, &h).MustDecode(&raw)
		testDeepEqualErr(expected, raw, t, "cbor-skip-tags--gh-300---no-skips")

		toDecode = []byte{0xd9, 0xd9, 0xf7, 0x82, 0x61, 0x78, 0x00}
		raw = nil
		NewDecoderBytes(toDecode, &h).MustDecode(&raw)
		testDeepEqualErr(expected, raw, t, "cbor-skip-tags--gh-300--has-skips")
	}
}

func TestCborMalformed(t *testing.T) {
	if !testRecoverPanicToErr {
		t.Skip(testSkipIfNotRecoverPanicToErrMsg)
	}
	var h Handle = testCborH
	defer testSetup(t, &h)()
	var bad = [][]byte{
		[]byte("\x9b\x00\x00000000"),
		[]byte("\x9b\x00\x00\x81112233"),
	}

	var out interface{}
	for _, v := range bad {
		out = nil
		err := testUnmarshal(&out, v, h)
		if err == nil {
			t.Logf("missing expected error decoding malformed cbor")
			t.FailNow()
		}
	}
}