cbor_test.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. // Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved.
  2. // Use of this source code is governed by a MIT license found in the LICENSE file.
  3. package codec
  4. import (
  5. "bufio"
  6. "bytes"
  7. "encoding/hex"
  8. "math"
  9. "os"
  10. "regexp"
  11. "strings"
  12. "testing"
  13. )
  14. func TestCborIndefiniteLength(t *testing.T) {
  15. oldMapType := testCborH.MapType
  16. defer func() {
  17. testCborH.MapType = oldMapType
  18. }()
  19. testCborH.MapType = testMapStrIntfTyp
  20. // var (
  21. // M1 map[string][]byte
  22. // M2 map[uint64]bool
  23. // L1 []interface{}
  24. // S1 []string
  25. // B1 []byte
  26. // )
  27. var v, vv interface{}
  28. // define it (v), encode it using indefinite lengths, decode it (vv), compare v to vv
  29. v = map[string]interface{}{
  30. "one-byte-key": []byte{1, 2, 3, 4, 5, 6},
  31. "two-string-key": "two-value",
  32. "three-list-key": []interface{}{true, false, uint64(1), int64(-1)},
  33. }
  34. var buf bytes.Buffer
  35. // buf.Reset()
  36. e := NewEncoder(&buf, testCborH)
  37. buf.WriteByte(cborBdIndefiniteMap)
  38. //----
  39. buf.WriteByte(cborBdIndefiniteString)
  40. e.MustEncode("one-")
  41. e.MustEncode("byte-")
  42. e.MustEncode("key")
  43. buf.WriteByte(cborBdBreak)
  44. buf.WriteByte(cborBdIndefiniteBytes)
  45. e.MustEncode([]byte{1, 2, 3})
  46. e.MustEncode([]byte{4, 5, 6})
  47. buf.WriteByte(cborBdBreak)
  48. //----
  49. buf.WriteByte(cborBdIndefiniteString)
  50. e.MustEncode("two-")
  51. e.MustEncode("string-")
  52. e.MustEncode("key")
  53. buf.WriteByte(cborBdBreak)
  54. buf.WriteByte(cborBdIndefiniteString)
  55. e.MustEncode([]byte("two-")) // encode as bytes, to check robustness of code
  56. e.MustEncode([]byte("value"))
  57. buf.WriteByte(cborBdBreak)
  58. //----
  59. buf.WriteByte(cborBdIndefiniteString)
  60. e.MustEncode("three-")
  61. e.MustEncode("list-")
  62. e.MustEncode("key")
  63. buf.WriteByte(cborBdBreak)
  64. buf.WriteByte(cborBdIndefiniteArray)
  65. e.MustEncode(true)
  66. e.MustEncode(false)
  67. e.MustEncode(uint64(1))
  68. e.MustEncode(int64(-1))
  69. buf.WriteByte(cborBdBreak)
  70. buf.WriteByte(cborBdBreak) // close map
  71. NewDecoderBytes(buf.Bytes(), testCborH).MustDecode(&vv)
  72. if err := deepEqual(v, vv); err != nil {
  73. logT(t, "-------- Before and After marshal do not match: Error: %v", err)
  74. logTv(t, " ....... GOLDEN: (%T) %#v", v, v)
  75. logTv(t, " ....... DECODED: (%T) %#v", vv, vv)
  76. failT(t)
  77. }
  78. }
  79. type testCborGolden struct {
  80. Base64 string `codec:"cbor"`
  81. Hex string `codec:"hex"`
  82. Roundtrip bool `codec:"roundtrip"`
  83. Decoded interface{} `codec:"decoded"`
  84. Diagnostic string `codec:"diagnostic"`
  85. Skip bool `codec:"skip"`
  86. }
  87. // Some tests are skipped because they include numbers outside the range of int64/uint64
  88. func TestCborGoldens(t *testing.T) {
  89. oldMapType := testCborH.MapType
  90. defer func() {
  91. testCborH.MapType = oldMapType
  92. }()
  93. testCborH.MapType = testMapStrIntfTyp
  94. // decode test-cbor-goldens.json into a list of []*testCborGolden
  95. // for each one,
  96. // - decode hex into []byte bs
  97. // - decode bs into interface{} v
  98. // - compare both using deepequal
  99. // - for any miss, record it
  100. var gs []*testCborGolden
  101. f, err := os.Open("test-cbor-goldens.json")
  102. if err != nil {
  103. logT(t, "error opening test-cbor-goldens.json: %v", err)
  104. failT(t)
  105. }
  106. defer f.Close()
  107. jh := new(JsonHandle)
  108. jh.MapType = testMapStrIntfTyp
  109. // d := NewDecoder(f, jh)
  110. d := NewDecoder(bufio.NewReader(f), jh)
  111. // err = d.Decode(&gs)
  112. d.MustDecode(&gs)
  113. if err != nil {
  114. logT(t, "error json decoding test-cbor-goldens.json: %v", err)
  115. failT(t)
  116. }
  117. tagregex := regexp.MustCompile(`[\d]+\(.+?\)`)
  118. hexregex := regexp.MustCompile(`h'([0-9a-fA-F]*)'`)
  119. for i, g := range gs {
  120. // fmt.Printf("%v, skip: %v, isTag: %v, %s\n", i, g.Skip, tagregex.MatchString(g.Diagnostic), g.Diagnostic)
  121. // skip tags or simple or those with prefix, as we can't verify them.
  122. if g.Skip || strings.HasPrefix(g.Diagnostic, "simple(") || tagregex.MatchString(g.Diagnostic) {
  123. // fmt.Printf("%v: skipped\n", i)
  124. logTv(t, "[%v] skipping because skip=true OR unsupported simple value or Tag Value", i)
  125. continue
  126. }
  127. // println("++++++++++++", i, "g.Diagnostic", g.Diagnostic)
  128. if hexregex.MatchString(g.Diagnostic) {
  129. // println(i, "g.Diagnostic matched hex")
  130. if s2 := g.Diagnostic[2 : len(g.Diagnostic)-1]; s2 == "" {
  131. g.Decoded = zeroByteSlice
  132. } else if bs2, err2 := hex.DecodeString(s2); err2 == nil {
  133. g.Decoded = bs2
  134. }
  135. // fmt.Printf("%v: hex: %v\n", i, g.Decoded)
  136. }
  137. bs, err := hex.DecodeString(g.Hex)
  138. if err != nil {
  139. logT(t, "[%v] error hex decoding %s [%v]: %v", i, g.Hex, g.Hex, err)
  140. failT(t)
  141. }
  142. var v interface{}
  143. NewDecoderBytes(bs, testCborH).MustDecode(&v)
  144. if _, ok := v.(RawExt); ok {
  145. continue
  146. }
  147. // check the diagnostics to compare
  148. switch g.Diagnostic {
  149. case "Infinity":
  150. b := math.IsInf(v.(float64), 1)
  151. testCborError(t, i, math.Inf(1), v, nil, &b)
  152. case "-Infinity":
  153. b := math.IsInf(v.(float64), -1)
  154. testCborError(t, i, math.Inf(-1), v, nil, &b)
  155. case "NaN":
  156. // println(i, "checking NaN")
  157. b := math.IsNaN(v.(float64))
  158. testCborError(t, i, math.NaN(), v, nil, &b)
  159. case "undefined":
  160. b := v == nil
  161. testCborError(t, i, nil, v, nil, &b)
  162. default:
  163. v0 := g.Decoded
  164. // testCborCoerceJsonNumber(reflect.ValueOf(&v0))
  165. testCborError(t, i, v0, v, deepEqual(v0, v), nil)
  166. }
  167. }
  168. }
  169. func testCborError(t *testing.T, i int, v0, v1 interface{}, err error, equal *bool) {
  170. if err == nil && equal == nil {
  171. // fmt.Printf("%v testCborError passed (err and equal nil)\n", i)
  172. return
  173. }
  174. if err != nil {
  175. logT(t, "[%v] deepEqual error: %v", i, err)
  176. logTv(t, " ....... GOLDEN: (%T) %#v", v0, v0)
  177. logTv(t, " ....... DECODED: (%T) %#v", v1, v1)
  178. failT(t)
  179. }
  180. if equal != nil && !*equal {
  181. logT(t, "[%v] values not equal", i)
  182. logTv(t, " ....... GOLDEN: (%T) %#v", v0, v0)
  183. logTv(t, " ....... DECODED: (%T) %#v", v1, v1)
  184. failT(t)
  185. }
  186. // fmt.Printf("%v testCborError passed (checks passed)\n", i)
  187. }
  188. func TestCborHalfFloat(t *testing.T) {
  189. m := map[uint16]float64{
  190. // using examples from
  191. // https://en.wikipedia.org/wiki/Half-precision_floating-point_format
  192. 0x3c00: 1,
  193. 0x3c01: 1 + math.Pow(2, -10),
  194. 0xc000: -2,
  195. 0x7bff: 65504,
  196. 0x0400: math.Pow(2, -14),
  197. 0x03ff: math.Pow(2, -14) - math.Pow(2, -24),
  198. 0x0001: math.Pow(2, -24),
  199. 0x0000: 0,
  200. 0x8000: -0.0,
  201. }
  202. var ba [3]byte
  203. ba[0] = cborBdFloat16
  204. var res float64
  205. for k, v := range m {
  206. res = 0
  207. bigen.PutUint16(ba[1:], k)
  208. testUnmarshalErr(&res, ba[:3], testCborH, t, "-")
  209. if res == v {
  210. logTv(t, "equal floats: from %x %b, %v", k, k, v)
  211. } else {
  212. failT(t, "unequal floats: from %x %b, %v != %v", k, k, res, v)
  213. }
  214. }
  215. }
  216. func TestCborSkipTags(t *testing.T) {
  217. type Tcbortags struct {
  218. A string
  219. M map[string]interface{}
  220. // A []interface{}
  221. }
  222. var b8 [8]byte
  223. var w bytesEncAppender
  224. w.b = []byte{}
  225. // To make it easier,
  226. // - use tags between math.MaxUint8 and math.MaxUint16 (incl SelfDesc)
  227. // - use 1 char strings for key names
  228. // - use 3-6 char strings for map keys
  229. // - use integers that fit in 2 bytes (between 0x20 and 0xff)
  230. var tags = [...]uint64{math.MaxUint8 * 2, math.MaxUint8 * 8, 55799, math.MaxUint16 / 2}
  231. var tagIdx int
  232. var doAddTag bool
  233. addTagFn8To16 := func() {
  234. if !doAddTag {
  235. return
  236. }
  237. // writes a tag between MaxUint8 and MaxUint16 (culled from cborEncDriver.encUint)
  238. w.writen1(cborBaseTag + 0x19)
  239. // bigenHelper.writeUint16
  240. bigen.PutUint16(b8[:2], uint16(tags[tagIdx%len(tags)]))
  241. w.writeb(b8[:2])
  242. tagIdx++
  243. }
  244. var v Tcbortags
  245. v.A = "cbor"
  246. v.M = make(map[string]interface{})
  247. v.M["111"] = uint64(111)
  248. v.M["111.11"] = 111.11
  249. v.M["true"] = true
  250. // v.A = append(v.A, 222, 22.22, "true")
  251. // make stream manually (interspacing tags around it)
  252. // WriteMapStart - e.encLen(cborBaseMap, length) - encUint(length, bd)
  253. // EncodeStringEnc - e.encStringBytesS(cborBaseString, v)
  254. fnEncode := func() {
  255. w.b = w.b[:0]
  256. addTagFn8To16()
  257. // write v (Tcbortags, with 3 fields = map with 3 entries)
  258. w.writen1(2 + cborBaseMap) // 3 fields = 3 entries
  259. // write v.A
  260. var s = "A"
  261. w.writen1(byte(len(s)) + cborBaseString)
  262. w.writestr(s)
  263. w.writen1(byte(len(v.A)) + cborBaseString)
  264. w.writestr(v.A)
  265. //w.writen1(0)
  266. addTagFn8To16()
  267. s = "M"
  268. w.writen1(byte(len(s)) + cborBaseString)
  269. w.writestr(s)
  270. addTagFn8To16()
  271. w.writen1(byte(len(v.M)) + cborBaseMap)
  272. addTagFn8To16()
  273. s = "111"
  274. w.writen1(byte(len(s)) + cborBaseString)
  275. w.writestr(s)
  276. w.writen2(cborBaseUint+0x18, uint8(111))
  277. addTagFn8To16()
  278. s = "111.11"
  279. w.writen1(byte(len(s)) + cborBaseString)
  280. w.writestr(s)
  281. w.writen1(cborBdFloat64)
  282. bigen.PutUint64(b8[:8], math.Float64bits(111.11))
  283. w.writeb(b8[:8])
  284. addTagFn8To16()
  285. s = "true"
  286. w.writen1(byte(len(s)) + cborBaseString)
  287. w.writestr(s)
  288. w.writen1(cborBdTrue)
  289. }
  290. var h CborHandle
  291. h.SkipUnexpectedTags = true
  292. h.Canonical = true
  293. var gold []byte
  294. NewEncoderBytes(&gold, &h).MustEncode(v)
  295. // xdebug2f("encoded: gold: %v", gold)
  296. // w.b is the encoded bytes
  297. var v2 Tcbortags
  298. doAddTag = false
  299. fnEncode()
  300. // xdebug2f("manual: no-tags: %v", w.b)
  301. testDeepEqualErr(gold, w.b, t, "cbor-skip-tags--bytes---")
  302. NewDecoderBytes(w.b, &h).MustDecode(&v2)
  303. testDeepEqualErr(v, v2, t, "cbor-skip-tags--no-tags-")
  304. var v3 Tcbortags
  305. doAddTag = true
  306. fnEncode()
  307. // xdebug2f("manual: has-tags: %v", w.b)
  308. NewDecoderBytes(w.b, &h).MustDecode(&v3)
  309. testDeepEqualErr(v, v2, t, "cbor-skip-tags--has-tags")
  310. // Github 300 - tests naked path
  311. {
  312. expected := []interface{}{"x", uint64(0x0)}
  313. toDecode := []byte{0x82, 0x61, 0x78, 0x00}
  314. var raw interface{}
  315. NewDecoderBytes(toDecode, &h).MustDecode(&raw)
  316. testDeepEqualErr(expected, raw, t, "cbor-skip-tags--gh-300---no-skips")
  317. toDecode = []byte{0xd9, 0xd9, 0xf7, 0x82, 0x61, 0x78, 0x00}
  318. raw = nil
  319. NewDecoderBytes(toDecode, &h).MustDecode(&raw)
  320. testDeepEqualErr(expected, raw, t, "cbor-skip-tags--gh-300--has-skips")
  321. }
  322. }