codec_test.go 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068
  1. // Copyright (c) 2012-2015 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. // Test works by using a slice of interfaces.
  5. // It can test for encoding/decoding into/from a nil interface{}
  6. // or passing the object to encode/decode into.
  7. //
  8. // There are basically 2 main tests here.
  9. // First test internally encodes and decodes things and verifies that
  10. // the artifact was as expected.
  11. // Second test will use python msgpack to create a bunch of golden files,
  12. // read those files, and compare them to what it should be. It then
  13. // writes those files back out and compares the byte streams.
  14. //
  15. // Taken together, the tests are pretty extensive.
  16. //
  17. // The following manual tests must be done:
  18. // - TestCodecUnderlyingType
  19. import (
  20. "bytes"
  21. "encoding/gob"
  22. "fmt"
  23. "io/ioutil"
  24. "math"
  25. "math/rand"
  26. "net"
  27. "net/rpc"
  28. "os"
  29. "os/exec"
  30. "path/filepath"
  31. "reflect"
  32. "runtime"
  33. "strconv"
  34. "strings"
  35. "sync/atomic"
  36. "testing"
  37. "time"
  38. )
  39. func init() {
  40. testPreInitFns = append(testPreInitFns, testInit)
  41. fmt.Printf("sizeof: Decoder: %v, Encoder: %v, decNaked: %v\n",
  42. reflect.TypeOf((*Decoder)(nil)).Elem().Size(),
  43. reflect.TypeOf((*Encoder)(nil)).Elem().Size(),
  44. reflect.TypeOf((*decNaked)(nil)).Elem().Size(),
  45. )
  46. }
  47. // make this a mapbyslice
  48. type testMbsT []interface{}
  49. func (_ testMbsT) MapBySlice() {}
  50. type testVerifyArg int
  51. const (
  52. testVerifyMapTypeSame testVerifyArg = iota
  53. testVerifyMapTypeStrIntf
  54. testVerifyMapTypeIntfIntf
  55. // testVerifySliceIntf
  56. testVerifyForPython
  57. )
  58. const testSkipRPCTests = false
  59. var (
  60. testTableNumPrimitives int
  61. testTableIdxTime int
  62. testTableNumMaps int
  63. )
  64. var (
  65. skipVerifyVal interface{} = &(struct{}{})
  66. testMapStrIntfTyp = reflect.TypeOf(map[string]interface{}(nil))
  67. // For Go Time, do not use a descriptive timezone.
  68. // It's unnecessary, and makes it harder to do a reflect.DeepEqual.
  69. // The Offset already tells what the offset should be, if not on UTC and unknown zone name.
  70. timeLoc = time.FixedZone("", -8*60*60) // UTC-08:00 //time.UTC-8
  71. timeToCompare1 = time.Date(2012, 2, 2, 2, 2, 2, 2000, timeLoc).UTC()
  72. timeToCompare2 = time.Date(1900, 2, 2, 2, 2, 2, 2000, timeLoc).UTC()
  73. timeToCompare3 = time.Unix(0, 270).UTC() // use value that must be encoded as uint64 for nanoseconds (for cbor/msgpack comparison)
  74. //timeToCompare4 = time.Time{}.UTC() // does not work well with simple cbor time encoding (overflow)
  75. timeToCompare4 = time.Unix(-2013855848, 4223).UTC()
  76. table []interface{} // main items we encode
  77. tableVerify []interface{} // we verify encoded things against this after decode
  78. tableTestNilVerify []interface{} // for nil interface, use this to verify (rules are different)
  79. tablePythonVerify []interface{} // for verifying for python, since Python sometimes
  80. // will encode a float32 as float64, or large int as uint
  81. testRpcInt = new(TestRpcInt)
  82. )
  83. func testByteBuf(in []byte) *bytes.Buffer {
  84. return bytes.NewBuffer(in)
  85. }
  86. type TestABC struct {
  87. A, B, C string
  88. }
  89. func (x *TestABC) MarshalBinary() ([]byte, error) {
  90. return []byte(fmt.Sprintf("%s %s %s", x.A, x.B, x.C)), nil
  91. }
  92. func (x *TestABC) MarshalText() ([]byte, error) {
  93. return []byte(fmt.Sprintf("%s %s %s", x.A, x.B, x.C)), nil
  94. }
  95. func (x *TestABC) MarshalJSON() ([]byte, error) {
  96. return []byte(fmt.Sprintf(`"%s %s %s"`, x.A, x.B, x.C)), nil
  97. }
  98. func (x *TestABC) UnmarshalBinary(data []byte) (err error) {
  99. ss := strings.Split(string(data), " ")
  100. x.A, x.B, x.C = ss[0], ss[1], ss[2]
  101. return
  102. }
  103. func (x *TestABC) UnmarshalText(data []byte) (err error) {
  104. return x.UnmarshalBinary(data)
  105. }
  106. func (x *TestABC) UnmarshalJSON(data []byte) (err error) {
  107. return x.UnmarshalBinary(data[1 : len(data)-1])
  108. }
  109. type TestABC2 struct {
  110. A, B, C string
  111. }
  112. func (x TestABC2) MarshalText() ([]byte, error) {
  113. return []byte(fmt.Sprintf("%s %s %s", x.A, x.B, x.C)), nil
  114. }
  115. func (x *TestABC2) UnmarshalText(data []byte) (err error) {
  116. ss := strings.Split(string(data), " ")
  117. x.A, x.B, x.C = ss[0], ss[1], ss[2]
  118. return
  119. // _, err = fmt.Sscanf(string(data), "%s %s %s", &x.A, &x.B, &x.C)
  120. }
  121. type TestSimplish struct {
  122. Ii int
  123. Ss string
  124. Ar [2]*TestSimplish
  125. Sl []*TestSimplish
  126. Mm map[string]*TestSimplish
  127. }
  128. type TestRpcABC struct {
  129. A, B, C string
  130. }
  131. type TestRpcInt struct {
  132. i int
  133. }
  134. func (r *TestRpcInt) Update(n int, res *int) error { r.i = n; *res = r.i; return nil }
  135. func (r *TestRpcInt) Square(ignore int, res *int) error { *res = r.i * r.i; return nil }
  136. func (r *TestRpcInt) Mult(n int, res *int) error { *res = r.i * n; return nil }
  137. func (r *TestRpcInt) EchoStruct(arg TestRpcABC, res *string) error {
  138. *res = fmt.Sprintf("%#v", arg)
  139. return nil
  140. }
  141. func (r *TestRpcInt) Echo123(args []string, res *string) error {
  142. *res = fmt.Sprintf("%#v", args)
  143. return nil
  144. }
  145. type TestRawValue struct {
  146. R Raw
  147. I int
  148. }
  149. type testUnixNanoTimeExt struct {
  150. // keep timestamp here, so that do not incur interface-conversion costs
  151. ts int64
  152. }
  153. // func (x *testUnixNanoTimeExt) WriteExt(interface{}) []byte { panic("unsupported") }
  154. // func (x *testUnixNanoTimeExt) ReadExt(interface{}, []byte) { panic("unsupported") }
  155. func (x *testUnixNanoTimeExt) ConvertExt(v interface{}) interface{} {
  156. switch v2 := v.(type) {
  157. case time.Time:
  158. x.ts = v2.UTC().UnixNano()
  159. case *time.Time:
  160. x.ts = v2.UTC().UnixNano()
  161. default:
  162. panic(fmt.Sprintf("unsupported format for time conversion: expecting time.Time; got %T", v))
  163. }
  164. return &x.ts
  165. }
  166. func (x *testUnixNanoTimeExt) UpdateExt(dest interface{}, v interface{}) {
  167. tt := dest.(*time.Time)
  168. switch v2 := v.(type) {
  169. case int64:
  170. *tt = time.Unix(0, v2).UTC()
  171. case *int64:
  172. *tt = time.Unix(0, *v2).UTC()
  173. case uint64:
  174. *tt = time.Unix(0, int64(v2)).UTC()
  175. case *uint64:
  176. *tt = time.Unix(0, int64(*v2)).UTC()
  177. //case float64:
  178. //case string:
  179. default:
  180. panic(fmt.Sprintf("unsupported format for time conversion: expecting int64/uint64; got %T", v))
  181. }
  182. }
  183. func testVerifyVal(v interface{}, arg testVerifyArg) (v2 interface{}) {
  184. //for python msgpack,
  185. // - all positive integers are unsigned 64-bit ints
  186. // - all floats are float64
  187. switch iv := v.(type) {
  188. case int8:
  189. if iv >= 0 {
  190. v2 = uint64(iv)
  191. } else {
  192. v2 = int64(iv)
  193. }
  194. case int16:
  195. if iv >= 0 {
  196. v2 = uint64(iv)
  197. } else {
  198. v2 = int64(iv)
  199. }
  200. case int32:
  201. if iv >= 0 {
  202. v2 = uint64(iv)
  203. } else {
  204. v2 = int64(iv)
  205. }
  206. case int64:
  207. if iv >= 0 {
  208. v2 = uint64(iv)
  209. } else {
  210. v2 = int64(iv)
  211. }
  212. case uint8:
  213. v2 = uint64(iv)
  214. case uint16:
  215. v2 = uint64(iv)
  216. case uint32:
  217. v2 = uint64(iv)
  218. case uint64:
  219. v2 = uint64(iv)
  220. case float32:
  221. v2 = float64(iv)
  222. case float64:
  223. v2 = float64(iv)
  224. case []interface{}:
  225. m2 := make([]interface{}, len(iv))
  226. for j, vj := range iv {
  227. m2[j] = testVerifyVal(vj, arg)
  228. }
  229. v2 = m2
  230. case testMbsT:
  231. m2 := make([]interface{}, len(iv))
  232. for j, vj := range iv {
  233. m2[j] = testVerifyVal(vj, arg)
  234. }
  235. v2 = testMbsT(m2)
  236. case map[string]bool:
  237. switch arg {
  238. case testVerifyMapTypeSame:
  239. m2 := make(map[string]bool)
  240. for kj, kv := range iv {
  241. m2[kj] = kv
  242. }
  243. v2 = m2
  244. case testVerifyMapTypeStrIntf, testVerifyForPython:
  245. m2 := make(map[string]interface{})
  246. for kj, kv := range iv {
  247. m2[kj] = kv
  248. }
  249. v2 = m2
  250. case testVerifyMapTypeIntfIntf:
  251. m2 := make(map[interface{}]interface{})
  252. for kj, kv := range iv {
  253. m2[kj] = kv
  254. }
  255. v2 = m2
  256. }
  257. case map[string]interface{}:
  258. switch arg {
  259. case testVerifyMapTypeSame:
  260. m2 := make(map[string]interface{})
  261. for kj, kv := range iv {
  262. m2[kj] = testVerifyVal(kv, arg)
  263. }
  264. v2 = m2
  265. case testVerifyMapTypeStrIntf, testVerifyForPython:
  266. m2 := make(map[string]interface{})
  267. for kj, kv := range iv {
  268. m2[kj] = testVerifyVal(kv, arg)
  269. }
  270. v2 = m2
  271. case testVerifyMapTypeIntfIntf:
  272. m2 := make(map[interface{}]interface{})
  273. for kj, kv := range iv {
  274. m2[kj] = testVerifyVal(kv, arg)
  275. }
  276. v2 = m2
  277. }
  278. case map[interface{}]interface{}:
  279. m2 := make(map[interface{}]interface{})
  280. for kj, kv := range iv {
  281. m2[testVerifyVal(kj, arg)] = testVerifyVal(kv, arg)
  282. }
  283. v2 = m2
  284. case time.Time:
  285. switch arg {
  286. case testVerifyForPython:
  287. if iv2 := iv.UnixNano(); iv2 >= 0 {
  288. v2 = uint64(iv2)
  289. } else {
  290. v2 = int64(iv2)
  291. }
  292. default:
  293. v2 = v
  294. }
  295. default:
  296. v2 = v
  297. }
  298. return
  299. }
  300. func testInit() {
  301. gob.Register(new(TestStrucFlex))
  302. if testInitDebug {
  303. ts0 := newTestStrucFlex(2, false, !testSkipIntf, false)
  304. logT(nil, "====> depth: %v, ts: %#v\n", 2, ts0)
  305. }
  306. for _, v := range testHandles {
  307. bh := v.getBasicHandle()
  308. // pre-fill them first
  309. bh.EncodeOptions = testEncodeOptions
  310. bh.DecodeOptions = testDecodeOptions
  311. // bh.InterfaceReset = true // TODO: remove
  312. // bh.PreferArrayOverSlice = true // TODO: remove
  313. // modify from flag'ish things
  314. bh.InternString = testInternStr
  315. bh.Canonical = testCanonical
  316. bh.CheckCircularRef = testCheckCircRef
  317. bh.StructToArray = testStructToArray
  318. bh.MaxInitLen = testMaxInitLen
  319. // mostly doing this for binc
  320. if testWriteNoSymbols {
  321. bh.AsSymbols = AsSymbolNone
  322. } else {
  323. bh.AsSymbols = AsSymbolAll
  324. }
  325. }
  326. testJsonH.Indent = int8(testJsonIndent)
  327. testJsonH.HTMLCharsAsIs = testJsonHTMLCharsAsIs
  328. testJsonH.PreferFloat = testJsonPreferFloat
  329. testMsgpackH.RawToString = true
  330. // testMsgpackH.AddExt(byteSliceTyp, 0, testMsgpackH.BinaryEncodeExt, testMsgpackH.BinaryDecodeExt)
  331. // testMsgpackH.AddExt(timeTyp, 1, testMsgpackH.TimeEncodeExt, testMsgpackH.TimeDecodeExt)
  332. // add extensions for msgpack, simple for time.Time, so we can encode/decode same way.
  333. // use different flavors of XXXExt calls, including deprecated ones.
  334. // NOTE:
  335. // DO NOT set extensions for JsonH, so we can test json(M|Unm)arshal support.
  336. var (
  337. timeExtEncFn = func(rv reflect.Value) (bs []byte, err error) {
  338. defer panicToErr(&err)
  339. bs = timeExt{}.WriteExt(rv.Interface())
  340. return
  341. }
  342. timeExtDecFn = func(rv reflect.Value, bs []byte) (err error) {
  343. defer panicToErr(&err)
  344. timeExt{}.ReadExt(rv.Interface(), bs)
  345. return
  346. }
  347. )
  348. testSimpleH.AddExt(timeTyp, 1, timeExtEncFn, timeExtDecFn)
  349. testMsgpackH.SetBytesExt(timeTyp, 1, timeExt{})
  350. testCborH.SetInterfaceExt(timeTyp, 1, &testUnixNanoTimeExt{})
  351. // testJsonH.SetInterfaceExt(timeTyp, 1, &testUnixNanoTimeExt{})
  352. // primitives MUST be an even number, so it can be used as a mapBySlice also.
  353. primitives := []interface{}{
  354. int8(-8),
  355. int16(-1616),
  356. int32(-32323232),
  357. int64(-6464646464646464),
  358. uint8(192),
  359. uint16(1616),
  360. uint32(32323232),
  361. uint64(6464646464646464),
  362. byte(192),
  363. float32(-3232.0),
  364. float64(-6464646464.0),
  365. float32(3232.0),
  366. float64(6464.0),
  367. float64(6464646464.0),
  368. false,
  369. true,
  370. "null",
  371. nil,
  372. "some&day>some<day",
  373. timeToCompare1,
  374. "",
  375. timeToCompare2,
  376. "bytestring",
  377. timeToCompare3,
  378. "none",
  379. timeToCompare4,
  380. }
  381. maps := []interface{}{
  382. map[string]bool{
  383. "true": true,
  384. "false": false,
  385. },
  386. map[string]interface{}{
  387. "true": "True",
  388. "false": false,
  389. "uint16(1616)": uint16(1616),
  390. },
  391. //add a complex combo map in here. (map has list which has map)
  392. //note that after the first thing, everything else should be generic.
  393. map[string]interface{}{
  394. "list": []interface{}{
  395. int16(1616),
  396. int32(32323232),
  397. true,
  398. float32(-3232.0),
  399. map[string]interface{}{
  400. "TRUE": true,
  401. "FALSE": false,
  402. },
  403. []interface{}{true, false},
  404. },
  405. "int32": int32(32323232),
  406. "bool": true,
  407. "LONG STRING": `
  408. 1234567890 1234567890
  409. 1234567890 1234567890
  410. 1234567890 1234567890
  411. ABCDEDFGHIJKLMNOPQRSTUVWXYZ
  412. abcdedfghijklmnopqrstuvwxyz
  413. ABCDEDFGHIJKLMNOPQRSTUVWXYZ
  414. abcdedfghijklmnopqrstuvwxyz
  415. "ABCDEDFGHIJKLMNOPQRSTUVWXYZ"
  416. ' a tab '
  417. \a\b\c\d\e
  418. \b\f\n\r\t all literally
  419. ugorji
  420. `,
  421. "SHORT STRING": "1234567890",
  422. },
  423. map[interface{}]interface{}{
  424. true: "true",
  425. uint8(138): false,
  426. "false": uint8(200),
  427. },
  428. }
  429. testTableNumPrimitives = len(primitives)
  430. testTableIdxTime = testTableNumPrimitives - 8
  431. testTableNumMaps = len(maps)
  432. table = []interface{}{}
  433. table = append(table, primitives...)
  434. table = append(table, primitives)
  435. table = append(table, testMbsT(primitives))
  436. table = append(table, maps...)
  437. table = append(table, newTestStrucFlex(0, false, !testSkipIntf, false))
  438. tableVerify = make([]interface{}, len(table))
  439. tableTestNilVerify = make([]interface{}, len(table))
  440. tablePythonVerify = make([]interface{}, len(table))
  441. lp := testTableNumPrimitives + 4
  442. av := tableVerify
  443. for i, v := range table {
  444. if i == lp {
  445. av[i] = skipVerifyVal
  446. continue
  447. }
  448. //av[i] = testVerifyVal(v, testVerifyMapTypeSame)
  449. switch v.(type) {
  450. case []interface{}:
  451. av[i] = testVerifyVal(v, testVerifyMapTypeSame)
  452. case testMbsT:
  453. av[i] = testVerifyVal(v, testVerifyMapTypeSame)
  454. case map[string]interface{}:
  455. av[i] = testVerifyVal(v, testVerifyMapTypeSame)
  456. case map[interface{}]interface{}:
  457. av[i] = testVerifyVal(v, testVerifyMapTypeSame)
  458. default:
  459. av[i] = v
  460. }
  461. }
  462. av = tableTestNilVerify
  463. for i, v := range table {
  464. if i > lp {
  465. av[i] = skipVerifyVal
  466. continue
  467. }
  468. av[i] = testVerifyVal(v, testVerifyMapTypeStrIntf)
  469. }
  470. av = tablePythonVerify
  471. for i, v := range table {
  472. if i == testTableNumPrimitives+1 || i > lp { // testTableNumPrimitives+1 is the mapBySlice
  473. av[i] = skipVerifyVal
  474. continue
  475. }
  476. av[i] = testVerifyVal(v, testVerifyForPython)
  477. }
  478. // only do the python verify up to the maps, skipping the last 2 maps.
  479. tablePythonVerify = tablePythonVerify[:testTableNumPrimitives+2+testTableNumMaps-2]
  480. }
  481. func testUnmarshal(v interface{}, data []byte, h Handle) (err error) {
  482. return testCodecDecode(data, v, h)
  483. }
  484. func testMarshal(v interface{}, h Handle) (bs []byte, err error) {
  485. return testCodecEncode(v, nil, testByteBuf, h)
  486. }
  487. func testMarshalErr(v interface{}, h Handle, t *testing.T, name string) (bs []byte, err error) {
  488. if bs, err = testMarshal(v, h); err != nil {
  489. logT(t, "Error encoding %s: %v, Err: %v", name, v, err)
  490. failT(t)
  491. }
  492. return
  493. }
  494. func testUnmarshalErr(v interface{}, data []byte, h Handle, t *testing.T, name string) (err error) {
  495. if err = testUnmarshal(v, data, h); err != nil {
  496. logT(t, "Error Decoding into %s: %v, Err: %v", name, v, err)
  497. failT(t)
  498. }
  499. return
  500. }
  501. func testDeepEqualErr(v1, v2 interface{}, t *testing.T, name string) (err error) {
  502. if err = deepEqual(v1, v2); err == nil {
  503. logT(t, "%s: values equal", name)
  504. } else {
  505. logT(t, "%s: values not equal: %v. 1: %v, 2: %v", name, err, v1, v2)
  506. failT(t)
  507. }
  508. return
  509. }
  510. // doTestCodecTableOne allows us test for different variations based on arguments passed.
  511. func doTestCodecTableOne(t *testing.T, testNil bool, h Handle,
  512. vs []interface{}, vsVerify []interface{}) {
  513. //if testNil, then just test for when a pointer to a nil interface{} is passed. It should work.
  514. //Current setup allows us test (at least manually) the nil interface or typed interface.
  515. logT(t, "================ TestNil: %v ================\n", testNil)
  516. for i, v0 := range vs {
  517. logT(t, "..............................................")
  518. logT(t, " Testing: #%d:, %T, %#v\n", i, v0, v0)
  519. b0, err := testMarshalErr(v0, h, t, "v0")
  520. if err != nil {
  521. continue
  522. }
  523. var b1 = b0
  524. if len(b1) > 256 {
  525. b1 = b1[:256]
  526. }
  527. if h.isBinary() {
  528. logT(t, " Encoded bytes: len: %v, %v\n", len(b0), b1)
  529. } else {
  530. logT(t, " Encoded string: len: %v, %v\n", len(b0), string(b1))
  531. // println("########### encoded string: " + string(b0))
  532. }
  533. var v1 interface{}
  534. if testNil {
  535. err = testUnmarshal(&v1, b0, h)
  536. } else {
  537. if v0 != nil {
  538. v0rt := reflect.TypeOf(v0) // ptr
  539. if v0rt.Kind() == reflect.Ptr {
  540. err = testUnmarshal(v0, b0, h)
  541. v1 = v0
  542. } else {
  543. rv1 := reflect.New(v0rt)
  544. err = testUnmarshal(rv1.Interface(), b0, h)
  545. v1 = rv1.Elem().Interface()
  546. // v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface()
  547. }
  548. }
  549. }
  550. logT(t, " v1 returned: %T, %#v", v1, v1)
  551. // if v1 != nil {
  552. // logT(t, " v1 returned: %T, %#v", v1, v1)
  553. // //we always indirect, because ptr to typed value may be passed (if not testNil)
  554. // v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface()
  555. // }
  556. if err != nil {
  557. logT(t, "-------- Error: %v. Partial return: %v", err, v1)
  558. failT(t)
  559. continue
  560. }
  561. v0check := vsVerify[i]
  562. if v0check == skipVerifyVal {
  563. logT(t, " Nil Check skipped: Decoded: %T, %#v\n", v1, v1)
  564. continue
  565. }
  566. if err = deepEqual(v0check, v1); err == nil {
  567. logT(t, "++++++++ Before and After marshal matched\n")
  568. } else {
  569. // logT(t, "-------- Before and After marshal do not match: Error: %v"+
  570. // " ====> GOLDEN: (%T) %#v, DECODED: (%T) %#v\n", err, v0check, v0check, v1, v1)
  571. logT(t, "-------- FAIL: Before and After marshal do not match: Error: %v", err)
  572. logT(t, " ....... GOLDEN: (%T) %#v", v0check, v0check)
  573. logT(t, " ....... DECODED: (%T) %#v", v1, v1)
  574. failT(t)
  575. }
  576. }
  577. }
  578. func testCodecTableOne(t *testing.T, h Handle) {
  579. testOnce.Do(testInitAll)
  580. // func TestMsgpackAllExperimental(t *testing.T) {
  581. // dopts := testDecOpts(nil, nil, false, true, true),
  582. numPrim, numMap, idxTime, idxMap := testTableNumPrimitives, testTableNumMaps, testTableIdxTime, testTableNumPrimitives+2
  583. //println("#################")
  584. switch v := h.(type) {
  585. case *MsgpackHandle:
  586. var oldWriteExt, oldRawToString bool
  587. oldWriteExt, v.WriteExt = v.WriteExt, true
  588. oldRawToString, v.RawToString = v.RawToString, true
  589. // defer func() { v.WriteExt, v.RawToString = oldWriteExt, oldRawToString }()
  590. doTestCodecTableOne(t, false, h, table, tableVerify)
  591. v.WriteExt, v.RawToString = oldWriteExt, oldRawToString
  592. case *JsonHandle:
  593. //skip []interface{} containing time.Time, as it encodes as a number, but cannot decode back to time.Time.
  594. //As there is no real support for extension tags in json, this must be skipped.
  595. doTestCodecTableOne(t, false, h, table[:numPrim], tableVerify[:numPrim])
  596. doTestCodecTableOne(t, false, h, table[idxMap:], tableVerify[idxMap:])
  597. default:
  598. doTestCodecTableOne(t, false, h, table, tableVerify)
  599. }
  600. // func TestMsgpackAll(t *testing.T) {
  601. // //skip []interface{} containing time.Time
  602. // doTestCodecTableOne(t, false, h, table[:numPrim], tableVerify[:numPrim])
  603. // doTestCodecTableOne(t, false, h, table[numPrim+1:], tableVerify[numPrim+1:])
  604. // func TestMsgpackNilStringMap(t *testing.T) {
  605. var oldMapType reflect.Type
  606. v := h.getBasicHandle()
  607. oldMapType, v.MapType = v.MapType, testMapStrIntfTyp
  608. // defer func() { v.MapType = oldMapType }()
  609. //skip time.Time, []interface{} containing time.Time, last map, and newStruc
  610. doTestCodecTableOne(t, true, h, table[:idxTime], tableTestNilVerify[:idxTime])
  611. doTestCodecTableOne(t, true, h, table[idxMap:idxMap+numMap-1], tableTestNilVerify[idxMap:idxMap+numMap-1])
  612. v.MapType = oldMapType
  613. // func TestMsgpackNilIntf(t *testing.T) {
  614. //do last map and newStruc
  615. idx2 := idxMap + numMap - 1
  616. doTestCodecTableOne(t, true, h, table[idx2:], tableTestNilVerify[idx2:])
  617. //TODO? What is this one?
  618. //doTestCodecTableOne(t, true, h, table[17:18], tableTestNilVerify[17:18])
  619. }
  620. func testCodecMiscOne(t *testing.T, h Handle) {
  621. testOnce.Do(testInitAll)
  622. b, err := testMarshalErr(32, h, t, "32")
  623. // Cannot do this nil one, because faster type assertion decoding will panic
  624. // var i *int32
  625. // if err = testUnmarshal(b, i, nil); err == nil {
  626. // logT(t, "------- Expecting error because we cannot unmarshal to int32 nil ptr")
  627. // failT(t)
  628. // }
  629. var i2 int32 = 0
  630. err = testUnmarshalErr(&i2, b, h, t, "int32-ptr")
  631. if i2 != int32(32) {
  632. logT(t, "------- didn't unmarshal to 32: Received: %d", i2)
  633. failT(t)
  634. }
  635. // func TestMsgpackDecodePtr(t *testing.T) {
  636. ts := newTestStrucFlex(testDepth, false, !testSkipIntf, false)
  637. b, err = testMarshalErr(ts, h, t, "pointer-to-struct")
  638. if len(b) < 40 {
  639. logT(t, "------- Size must be > 40. Size: %d", len(b))
  640. failT(t)
  641. }
  642. var b1 = b
  643. if len(b1) > 256 {
  644. b1 = b1[:256]
  645. }
  646. if h.isBinary() {
  647. logT(t, "------- b: size: %v, value: %v", len(b), b1)
  648. } else {
  649. logT(t, "------- b: size: %v, value: %s", len(b), b1)
  650. }
  651. ts2 := new(TestStrucFlex)
  652. err = testUnmarshalErr(ts2, b, h, t, "pointer-to-struct")
  653. if ts2.I64 != math.MaxInt64*2/3 {
  654. logT(t, "------- Unmarshal wrong. Expect I64 = 64. Got: %v", ts2.I64)
  655. failT(t)
  656. }
  657. // func TestMsgpackIntfDecode(t *testing.T) {
  658. m := map[string]int{"A": 2, "B": 3}
  659. p := []interface{}{m}
  660. bs, err := testMarshalErr(p, h, t, "p")
  661. m2 := map[string]int{}
  662. p2 := []interface{}{m2}
  663. err = testUnmarshalErr(&p2, bs, h, t, "&p2")
  664. if m2["A"] != 2 || m2["B"] != 3 {
  665. logT(t, "FAIL: m2 not as expected: expecting: %v, got: %v", m, m2)
  666. failT(t)
  667. }
  668. // log("m: %v, m2: %v, p: %v, p2: %v", m, m2, p, p2)
  669. checkEqualT(t, p, p2, "p=p2")
  670. checkEqualT(t, m, m2, "m=m2")
  671. if err = deepEqual(p, p2); err == nil {
  672. logT(t, "p and p2 match")
  673. } else {
  674. logT(t, "Not Equal: %v. p: %v, p2: %v", err, p, p2)
  675. failT(t)
  676. }
  677. if err = deepEqual(m, m2); err == nil {
  678. logT(t, "m and m2 match")
  679. } else {
  680. logT(t, "Not Equal: %v. m: %v, m2: %v", err, m, m2)
  681. failT(t)
  682. }
  683. // func TestMsgpackDecodeStructSubset(t *testing.T) {
  684. // test that we can decode a subset of the stream
  685. mm := map[string]interface{}{"A": 5, "B": 99, "C": 333}
  686. bs, err = testMarshalErr(mm, h, t, "mm")
  687. type ttt struct {
  688. A uint8
  689. C int32
  690. }
  691. var t2 ttt
  692. testUnmarshalErr(&t2, bs, h, t, "t2")
  693. t3 := ttt{5, 333}
  694. checkEqualT(t, t2, t3, "t2=t3")
  695. // println(">>>>>")
  696. // test simple arrays, non-addressable arrays, slices
  697. type tarr struct {
  698. A int64
  699. B [3]int64
  700. C []byte
  701. D [3]byte
  702. }
  703. var tarr0 = tarr{1, [3]int64{2, 3, 4}, []byte{4, 5, 6}, [3]byte{7, 8, 9}}
  704. // test both pointer and non-pointer (value)
  705. for _, tarr1 := range []interface{}{tarr0, &tarr0} {
  706. bs, err = testMarshalErr(tarr1, h, t, "tarr1")
  707. if err != nil {
  708. logT(t, "Error marshalling: %v", err)
  709. failT(t)
  710. }
  711. if _, ok := h.(*JsonHandle); ok {
  712. logT(t, "Marshal as: %s", bs)
  713. }
  714. var tarr2 tarr
  715. testUnmarshalErr(&tarr2, bs, h, t, "tarr2")
  716. checkEqualT(t, tarr0, tarr2, "tarr0=tarr2")
  717. }
  718. // test byte array, even if empty (msgpack only)
  719. if h == testMsgpackH {
  720. type ystruct struct {
  721. Anarray []byte
  722. }
  723. var ya = ystruct{}
  724. testUnmarshalErr(&ya, []byte{0x91, 0x90}, h, t, "ya")
  725. }
  726. }
  727. func testCodecEmbeddedPointer(t *testing.T, h Handle) {
  728. testOnce.Do(testInitAll)
  729. type Z int
  730. type A struct {
  731. AnInt int
  732. }
  733. type B struct {
  734. *Z
  735. *A
  736. MoreInt int
  737. }
  738. var z Z = 4
  739. x1 := &B{&z, &A{5}, 6}
  740. bs, err := testMarshalErr(x1, h, t, "x1")
  741. var x2 = new(B)
  742. err = testUnmarshalErr(x2, bs, h, t, "x2")
  743. err = checkEqualT(t, x1, x2, "x1=x2")
  744. _ = err
  745. }
  746. func testCodecUnderlyingType(t *testing.T, h Handle) {
  747. testOnce.Do(testInitAll)
  748. // Manual Test.
  749. // Run by hand, with accompanying print statements in fast-path.go
  750. // to ensure that the fast functions are called.
  751. type T1 map[string]string
  752. v := T1{"1": "1s", "2": "2s"}
  753. var bs []byte
  754. var err error
  755. NewEncoderBytes(&bs, h).MustEncode(v)
  756. if err != nil {
  757. logT(t, "Error during encode: %v", err)
  758. failT(t)
  759. }
  760. var v2 T1
  761. NewDecoderBytes(bs, h).MustDecode(&v2)
  762. if err != nil {
  763. logT(t, "Error during decode: %v", err)
  764. failT(t)
  765. }
  766. }
  767. func testCodecChan(t *testing.T, h Handle) {
  768. testOnce.Do(testInitAll)
  769. // - send a slice []*int64 (sl1) into an chan (ch1) with cap > len(s1)
  770. // - encode ch1 as a stream array
  771. // - decode a chan (ch2), with cap > len(s1) from the stream array
  772. // - receive from ch2 into slice sl2
  773. // - compare sl1 and sl2
  774. // - do this for codecs: json, cbor (covers all types)
  775. if true {
  776. sl1 := make([]*int64, 4)
  777. for i := range sl1 {
  778. var j int64 = int64(i)
  779. sl1[i] = &j
  780. }
  781. ch1 := make(chan *int64, 4)
  782. for _, j := range sl1 {
  783. ch1 <- j
  784. }
  785. var bs []byte
  786. NewEncoderBytes(&bs, h).MustEncode(ch1)
  787. ch2 := make(chan *int64, 8)
  788. NewDecoderBytes(bs, h).MustDecode(&ch2)
  789. close(ch2)
  790. var sl2 []*int64
  791. for j := range ch2 {
  792. sl2 = append(sl2, j)
  793. }
  794. if err := deepEqual(sl1, sl2); err != nil {
  795. logT(t, "FAIL: Not Match: %v; len: %v, %v", err, len(sl1), len(sl2))
  796. failT(t)
  797. }
  798. }
  799. if true {
  800. type testBytesT []byte
  801. sl1 := make([]testBytesT, 4)
  802. for i := range sl1 {
  803. var j = []byte(strings.Repeat(strconv.FormatInt(int64(i), 10), i))
  804. sl1[i] = j
  805. }
  806. ch1 := make(chan testBytesT, 4)
  807. for _, j := range sl1 {
  808. ch1 <- j
  809. }
  810. var bs []byte
  811. NewEncoderBytes(&bs, h).MustEncode(ch1)
  812. ch2 := make(chan testBytesT, 8)
  813. NewDecoderBytes(bs, h).MustDecode(&ch2)
  814. close(ch2)
  815. var sl2 []testBytesT
  816. for j := range ch2 {
  817. sl2 = append(sl2, j)
  818. }
  819. if err := deepEqual(sl1, sl2); err != nil {
  820. logT(t, "FAIL: Not Match: %v; len: %v, %v", err, len(sl1), len(sl2))
  821. failT(t)
  822. }
  823. }
  824. if true {
  825. type testBytesT byte
  826. sl1 := make([]testBytesT, 4)
  827. for i := range sl1 {
  828. var j = strconv.FormatInt(int64(i), 10)[0]
  829. sl1[i] = testBytesT(j)
  830. }
  831. ch1 := make(chan testBytesT, 4)
  832. for _, j := range sl1 {
  833. ch1 <- j
  834. }
  835. var bs []byte
  836. NewEncoderBytes(&bs, h).MustEncode(ch1)
  837. ch2 := make(chan testBytesT, 8)
  838. NewDecoderBytes(bs, h).MustDecode(&ch2)
  839. close(ch2)
  840. var sl2 []testBytesT
  841. for j := range ch2 {
  842. sl2 = append(sl2, j)
  843. }
  844. if err := deepEqual(sl1, sl2); err != nil {
  845. logT(t, "FAIL: Not Match: %v; len: %v, %v", err, len(sl1), len(sl2))
  846. failT(t)
  847. }
  848. }
  849. if true {
  850. sl1 := make([]byte, 4)
  851. for i := range sl1 {
  852. var j = strconv.FormatInt(int64(i), 10)[0]
  853. sl1[i] = byte(j)
  854. }
  855. ch1 := make(chan byte, 4)
  856. for _, j := range sl1 {
  857. ch1 <- j
  858. }
  859. var bs []byte
  860. NewEncoderBytes(&bs, h).MustEncode(ch1)
  861. ch2 := make(chan byte, 8)
  862. NewDecoderBytes(bs, h).MustDecode(&ch2)
  863. close(ch2)
  864. var sl2 []byte
  865. for j := range ch2 {
  866. sl2 = append(sl2, j)
  867. }
  868. if err := deepEqual(sl1, sl2); err != nil {
  869. logT(t, "FAIL: Not Match: %v; len: %v, %v", err, len(sl1), len(sl2))
  870. failT(t)
  871. }
  872. }
  873. }
  874. func testCodecRpcOne(t *testing.T, rr Rpc, h Handle, doRequest bool, exitSleepMs time.Duration,
  875. ) (port int) {
  876. testOnce.Do(testInitAll)
  877. if testSkipRPCTests {
  878. return
  879. }
  880. // rpc needs EOF, which is sent via a panic, and so must be recovered.
  881. if !recoverPanicToErr {
  882. logT(t, "EXPECTED. set recoverPanicToErr=true, since rpc needs EOF")
  883. failT(t)
  884. }
  885. srv := rpc.NewServer()
  886. srv.Register(testRpcInt)
  887. ln, err := net.Listen("tcp", "127.0.0.1:0")
  888. // log("listener: %v", ln.Addr())
  889. checkErrT(t, err)
  890. port = (ln.Addr().(*net.TCPAddr)).Port
  891. // var opts *DecoderOptions
  892. // opts := testDecOpts
  893. // opts.MapType = mapStrIntfTyp
  894. // opts.RawToString = false
  895. serverExitChan := make(chan bool, 1)
  896. var serverExitFlag uint64 = 0
  897. serverFn := func() {
  898. for {
  899. conn1, err1 := ln.Accept()
  900. // if err1 != nil {
  901. // //fmt.Printf("accept err1: %v\n", err1)
  902. // continue
  903. // }
  904. if atomic.LoadUint64(&serverExitFlag) == 1 {
  905. serverExitChan <- true
  906. conn1.Close()
  907. return // exit serverFn goroutine
  908. }
  909. if err1 == nil {
  910. var sc rpc.ServerCodec = rr.ServerCodec(conn1, h)
  911. srv.ServeCodec(sc)
  912. }
  913. }
  914. }
  915. clientFn := func(cc rpc.ClientCodec) {
  916. cl := rpc.NewClientWithCodec(cc)
  917. defer cl.Close()
  918. // defer func() { println("##### client closing"); cl.Close() }()
  919. var up, sq, mult int
  920. var rstr string
  921. // log("Calling client")
  922. checkErrT(t, cl.Call("TestRpcInt.Update", 5, &up))
  923. // log("Called TestRpcInt.Update")
  924. checkEqualT(t, testRpcInt.i, 5, "testRpcInt.i=5")
  925. checkEqualT(t, up, 5, "up=5")
  926. checkErrT(t, cl.Call("TestRpcInt.Square", 1, &sq))
  927. checkEqualT(t, sq, 25, "sq=25")
  928. checkErrT(t, cl.Call("TestRpcInt.Mult", 20, &mult))
  929. checkEqualT(t, mult, 100, "mult=100")
  930. checkErrT(t, cl.Call("TestRpcInt.EchoStruct", TestRpcABC{"Aa", "Bb", "Cc"}, &rstr))
  931. checkEqualT(t, rstr, fmt.Sprintf("%#v", TestRpcABC{"Aa", "Bb", "Cc"}), "rstr=")
  932. checkErrT(t, cl.Call("TestRpcInt.Echo123", []string{"A1", "B2", "C3"}, &rstr))
  933. checkEqualT(t, rstr, fmt.Sprintf("%#v", []string{"A1", "B2", "C3"}), "rstr=")
  934. }
  935. connFn := func() (bs net.Conn) {
  936. // log("calling f1")
  937. bs, err2 := net.Dial(ln.Addr().Network(), ln.Addr().String())
  938. checkErrT(t, err2)
  939. return
  940. }
  941. exitFn := func() {
  942. atomic.StoreUint64(&serverExitFlag, 1)
  943. bs := connFn()
  944. <-serverExitChan
  945. bs.Close()
  946. // serverExitChan <- true
  947. }
  948. go serverFn()
  949. runtime.Gosched()
  950. //time.Sleep(100 * time.Millisecond)
  951. if exitSleepMs == 0 {
  952. defer ln.Close()
  953. defer exitFn()
  954. }
  955. if doRequest {
  956. bs := connFn()
  957. cc := rr.ClientCodec(bs, h)
  958. clientFn(cc)
  959. }
  960. if exitSleepMs != 0 {
  961. go func() {
  962. defer ln.Close()
  963. time.Sleep(exitSleepMs)
  964. exitFn()
  965. }()
  966. }
  967. return
  968. }
  969. func doTestMapEncodeForCanonical(t *testing.T, name string, h Handle) {
  970. testOnce.Do(testInitAll)
  971. // println("doTestMapEncodeForCanonical")
  972. v1 := map[stringUint64T]interface{}{
  973. {"a", 1}: 1,
  974. {"b", 2}: "hello",
  975. {"c", 3}: map[string]interface{}{
  976. "c/a": 1,
  977. "c/b": "world",
  978. "c/c": []int{1, 2, 3, 4},
  979. "c/d": map[string]interface{}{
  980. "c/d/a": "fdisajfoidsajfopdjsaopfjdsapofda",
  981. "c/d/b": "fdsafjdposakfodpsakfopdsakfpodsakfpodksaopfkdsopafkdopsa",
  982. "c/d/c": "poir02 ir30qif4p03qir0pogjfpoaerfgjp ofke[padfk[ewapf kdp[afep[aw",
  983. "c/d/d": "fdsopafkd[sa f-32qor-=4qeof -afo-erfo r-eafo 4e- o r4-qwo ag",
  984. "c/d/e": "kfep[a sfkr0[paf[a foe-[wq ewpfao-q ro3-q ro-4qof4-qor 3-e orfkropzjbvoisdb",
  985. "c/d/f": "",
  986. },
  987. "c/e": map[int]string{
  988. 1: "1",
  989. 22: "22",
  990. 333: "333",
  991. 4444: "4444",
  992. 55555: "55555",
  993. },
  994. "c/f": map[string]int{
  995. "1": 1,
  996. "22": 22,
  997. "333": 333,
  998. "4444": 4444,
  999. "55555": 55555,
  1000. },
  1001. },
  1002. }
  1003. var v2 map[stringUint64T]interface{}
  1004. var b1, b2 []byte
  1005. // encode v1 into b1, decode b1 into v2, encode v2 into b2, compare b1 and b2
  1006. bh := h.getBasicHandle()
  1007. if !bh.Canonical {
  1008. bh.Canonical = true
  1009. defer func() { bh.Canonical = false }()
  1010. }
  1011. e1 := NewEncoderBytes(&b1, h)
  1012. e1.MustEncode(v1)
  1013. d1 := NewDecoderBytes(b1, h)
  1014. d1.MustDecode(&v2)
  1015. e2 := NewEncoderBytes(&b2, h)
  1016. e2.MustEncode(v2)
  1017. if !bytes.Equal(b1, b2) {
  1018. logT(t, "Unequal bytes: %v VS %v", b1, b2)
  1019. failT(t)
  1020. }
  1021. }
  1022. func doTestStdEncIntf(t *testing.T, name string, h Handle) {
  1023. testOnce.Do(testInitAll)
  1024. args := [][2]interface{}{
  1025. {&TestABC{"A", "BB", "CCC"}, new(TestABC)},
  1026. {&TestABC2{"AAA", "BB", "C"}, new(TestABC2)},
  1027. }
  1028. for _, a := range args {
  1029. var b []byte
  1030. e := NewEncoderBytes(&b, h)
  1031. e.MustEncode(a[0])
  1032. d := NewDecoderBytes(b, h)
  1033. d.MustDecode(a[1])
  1034. if err := deepEqual(a[0], a[1]); err == nil {
  1035. logT(t, "++++ Objects match")
  1036. } else {
  1037. logT(t, "---- FAIL: Objects do not match: y1: %v, err: %v", a[1], err)
  1038. failT(t)
  1039. }
  1040. }
  1041. }
  1042. func doTestEncCircularRef(t *testing.T, name string, h Handle) {
  1043. testOnce.Do(testInitAll)
  1044. type T1 struct {
  1045. S string
  1046. B bool
  1047. T interface{}
  1048. }
  1049. type T2 struct {
  1050. S string
  1051. T *T1
  1052. }
  1053. type T3 struct {
  1054. S string
  1055. T *T2
  1056. }
  1057. t1 := T1{"t1", true, nil}
  1058. t2 := T2{"t2", &t1}
  1059. t3 := T3{"t3", &t2}
  1060. t1.T = &t3
  1061. var bs []byte
  1062. var err error
  1063. bh := h.getBasicHandle()
  1064. if !bh.CheckCircularRef {
  1065. bh.CheckCircularRef = true
  1066. defer func() { bh.CheckCircularRef = false }()
  1067. }
  1068. err = NewEncoderBytes(&bs, h).Encode(&t3)
  1069. if err == nil {
  1070. logT(t, "expecting error due to circular reference. found none")
  1071. failT(t)
  1072. }
  1073. if x := err.Error(); strings.Contains(x, "circular") || strings.Contains(x, "cyclic") {
  1074. logT(t, "error detected as expected: %v", x)
  1075. } else {
  1076. logT(t, "FAIL: error detected was not as expected: %v", x)
  1077. failT(t)
  1078. }
  1079. }
  1080. // TestAnonCycleT{1,2,3} types are used to test anonymous cycles.
  1081. // They are top-level, so that they can have circular references.
  1082. type (
  1083. TestAnonCycleT1 struct {
  1084. S string
  1085. TestAnonCycleT2
  1086. }
  1087. TestAnonCycleT2 struct {
  1088. S2 string
  1089. TestAnonCycleT3
  1090. }
  1091. TestAnonCycleT3 struct {
  1092. *TestAnonCycleT1
  1093. }
  1094. )
  1095. func doTestAnonCycle(t *testing.T, name string, h Handle) {
  1096. testOnce.Do(testInitAll)
  1097. var x TestAnonCycleT1
  1098. x.S = "hello"
  1099. x.TestAnonCycleT2.S2 = "hello.2"
  1100. x.TestAnonCycleT2.TestAnonCycleT3.TestAnonCycleT1 = &x
  1101. // just check that you can get typeInfo for T1
  1102. rt := reflect.TypeOf((*TestAnonCycleT1)(nil)).Elem()
  1103. rtid := rt2id(rt)
  1104. pti := h.getBasicHandle().getTypeInfo(rtid, rt)
  1105. logT(t, "pti: %v", pti)
  1106. }
  1107. func doTestJsonLargeInteger(t *testing.T, v interface{}, ias uint8) {
  1108. testOnce.Do(testInitAll)
  1109. logT(t, "Running doTestJsonLargeInteger: v: %#v, ias: %c", v, ias)
  1110. oldIAS := testJsonH.IntegerAsString
  1111. defer func() { testJsonH.IntegerAsString = oldIAS }()
  1112. testJsonH.IntegerAsString = ias
  1113. var vu uint
  1114. var vi int
  1115. var vb bool
  1116. var b []byte
  1117. e := NewEncoderBytes(&b, testJsonH)
  1118. e.MustEncode(v)
  1119. e.MustEncode(true)
  1120. d := NewDecoderBytes(b, testJsonH)
  1121. // below, we validate that the json string or number was encoded,
  1122. // then decode, and validate that the correct value was decoded.
  1123. fnStrChk := func() {
  1124. // check that output started with ", and ended with "true
  1125. if !(b[0] == '"' && string(b[len(b)-5:]) == `"true`) {
  1126. logT(t, "Expecting a JSON string, got: %s", b)
  1127. failT(t)
  1128. }
  1129. }
  1130. switch ias {
  1131. case 'L':
  1132. switch v2 := v.(type) {
  1133. case int:
  1134. v2n := int64(v2) // done to work with 32-bit OS
  1135. if v2n > 1<<53 || (v2n < 0 && -v2n > 1<<53) {
  1136. fnStrChk()
  1137. }
  1138. case uint:
  1139. v2n := uint64(v2) // done to work with 32-bit OS
  1140. if v2n > 1<<53 {
  1141. fnStrChk()
  1142. }
  1143. }
  1144. case 'A':
  1145. fnStrChk()
  1146. default:
  1147. // check that output doesn't contain " at all
  1148. for _, i := range b {
  1149. if i == '"' {
  1150. logT(t, "Expecting a JSON Number without quotation: got: %s", b)
  1151. failT(t)
  1152. }
  1153. }
  1154. }
  1155. switch v2 := v.(type) {
  1156. case int:
  1157. d.MustDecode(&vi)
  1158. d.MustDecode(&vb)
  1159. // check that vb = true, and vi == v2
  1160. if !(vb && vi == v2) {
  1161. logT(t, "Expecting equal values from %s: got golden: %v, decoded: %v", b, v2, vi)
  1162. failT(t)
  1163. }
  1164. case uint:
  1165. d.MustDecode(&vu)
  1166. d.MustDecode(&vb)
  1167. // check that vb = true, and vi == v2
  1168. if !(vb && vu == v2) {
  1169. logT(t, "Expecting equal values from %s: got golden: %v, decoded: %v", b, v2, vu)
  1170. failT(t)
  1171. }
  1172. }
  1173. }
  1174. func doTestRawValue(t *testing.T, name string, h Handle) {
  1175. testOnce.Do(testInitAll)
  1176. bh := h.getBasicHandle()
  1177. if !bh.Raw {
  1178. bh.Raw = true
  1179. defer func() { bh.Raw = false }()
  1180. }
  1181. var i, i2 int
  1182. var v, v2 TestRawValue
  1183. var bs, bs2 []byte
  1184. i = 1234 //1234567890
  1185. v = TestRawValue{I: i}
  1186. e := NewEncoderBytes(&bs, h)
  1187. e.MustEncode(v.I)
  1188. logT(t, ">>> raw: %v\n", bs)
  1189. v.R = Raw(bs)
  1190. e.ResetBytes(&bs2)
  1191. e.MustEncode(v)
  1192. logT(t, ">>> bs2: %v\n", bs2)
  1193. d := NewDecoderBytes(bs2, h)
  1194. d.MustDecode(&v2)
  1195. d.ResetBytes(v2.R)
  1196. logT(t, ">>> v2.R: %v\n", ([]byte)(v2.R))
  1197. d.MustDecode(&i2)
  1198. logT(t, ">>> Encoded %v, decoded %v\n", i, i2)
  1199. // logT(t, "Encoded %v, decoded %v", i, i2)
  1200. if i != i2 {
  1201. logT(t, "Error: encoded %v, decoded %v", i, i2)
  1202. failT(t)
  1203. }
  1204. }
  1205. // Comprehensive testing that generates data encoded from python handle (cbor, msgpack),
  1206. // and validates that our code can read and write it out accordingly.
  1207. // We keep this unexported here, and put actual test in ext_dep_test.go.
  1208. // This way, it can be excluded by excluding file completely.
  1209. func doTestPythonGenStreams(t *testing.T, name string, h Handle) {
  1210. testOnce.Do(testInitAll)
  1211. logT(t, "TestPythonGenStreams-%v", name)
  1212. tmpdir, err := ioutil.TempDir("", "golang-"+name+"-test")
  1213. if err != nil {
  1214. logT(t, "-------- Unable to create temp directory\n")
  1215. failT(t)
  1216. }
  1217. defer os.RemoveAll(tmpdir)
  1218. logT(t, "tmpdir: %v", tmpdir)
  1219. cmd := exec.Command("python", "test.py", "testdata", tmpdir)
  1220. //cmd.Stdin = strings.NewReader("some input")
  1221. //cmd.Stdout = &out
  1222. var cmdout []byte
  1223. if cmdout, err = cmd.CombinedOutput(); err != nil {
  1224. logT(t, "-------- Error running test.py testdata. Err: %v", err)
  1225. logT(t, " %v", string(cmdout))
  1226. failT(t)
  1227. }
  1228. bh := h.getBasicHandle()
  1229. oldMapType := bh.MapType
  1230. for i, v := range tablePythonVerify {
  1231. // if v == uint64(0) && h == testMsgpackH {
  1232. // v = int64(0)
  1233. // }
  1234. bh.MapType = oldMapType
  1235. //load up the golden file based on number
  1236. //decode it
  1237. //compare to in-mem object
  1238. //encode it again
  1239. //compare to output stream
  1240. logT(t, "..............................................")
  1241. logT(t, " Testing: #%d: %T, %#v\n", i, v, v)
  1242. var bss []byte
  1243. bss, err = ioutil.ReadFile(filepath.Join(tmpdir, strconv.Itoa(i)+"."+name+".golden"))
  1244. if err != nil {
  1245. logT(t, "-------- Error reading golden file: %d. Err: %v", i, err)
  1246. failT(t)
  1247. continue
  1248. }
  1249. bh.MapType = testMapStrIntfTyp
  1250. var v1 interface{}
  1251. if err = testUnmarshal(&v1, bss, h); err != nil {
  1252. logT(t, "-------- Error decoding stream: %d: Err: %v", i, err)
  1253. failT(t)
  1254. continue
  1255. }
  1256. if v == skipVerifyVal {
  1257. continue
  1258. }
  1259. //no need to indirect, because we pass a nil ptr, so we already have the value
  1260. //if v1 != nil { v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface() }
  1261. if err = deepEqual(v, v1); err == nil {
  1262. logT(t, "++++++++ Objects match: %T, %v", v, v)
  1263. } else {
  1264. logT(t, "-------- FAIL: Objects do not match: %v. Source: %T. Decoded: %T", err, v, v1)
  1265. logT(t, "-------- GOLDEN: %#v", v)
  1266. // logT(t, "-------- DECODED: %#v <====> %#v", v1, reflect.Indirect(reflect.ValueOf(v1)).Interface())
  1267. logT(t, "-------- DECODED: %#v <====> %#v", v1, reflect.Indirect(reflect.ValueOf(v1)).Interface())
  1268. failT(t)
  1269. }
  1270. bsb, err := testMarshal(v1, h)
  1271. if err != nil {
  1272. logT(t, "Error encoding to stream: %d: Err: %v", i, err)
  1273. failT(t)
  1274. continue
  1275. }
  1276. if err = deepEqual(bsb, bss); err == nil {
  1277. logT(t, "++++++++ Bytes match")
  1278. } else {
  1279. logT(t, "???????? FAIL: Bytes do not match. %v.", err)
  1280. xs := "--------"
  1281. if reflect.ValueOf(v).Kind() == reflect.Map {
  1282. xs = " "
  1283. logT(t, "%s It's a map. Ok that they don't match (dependent on ordering).", xs)
  1284. } else {
  1285. logT(t, "%s It's not a map. They should match.", xs)
  1286. failT(t)
  1287. }
  1288. logT(t, "%s FROM_FILE: %4d] %v", xs, len(bss), bss)
  1289. logT(t, "%s ENCODED: %4d] %v", xs, len(bsb), bsb)
  1290. }
  1291. }
  1292. bh.MapType = oldMapType
  1293. }
  1294. // To test MsgpackSpecRpc, we test 3 scenarios:
  1295. // - Go Client to Go RPC Service (contained within TestMsgpackRpcSpec)
  1296. // - Go client to Python RPC Service (contained within doTestMsgpackRpcSpecGoClientToPythonSvc)
  1297. // - Python Client to Go RPC Service (contained within doTestMsgpackRpcSpecPythonClientToGoSvc)
  1298. //
  1299. // This allows us test the different calling conventions
  1300. // - Go Service requires only one argument
  1301. // - Python Service allows multiple arguments
  1302. func doTestMsgpackRpcSpecGoClientToPythonSvc(t *testing.T) {
  1303. if testSkipRPCTests {
  1304. return
  1305. }
  1306. testOnce.Do(testInitAll)
  1307. // openPorts are between 6700 and 6800
  1308. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  1309. openPort := strconv.FormatInt(6700+r.Int63n(99), 10)
  1310. // openPort := "6792"
  1311. cmd := exec.Command("python", "test.py", "rpc-server", openPort, "4")
  1312. checkErrT(t, cmd.Start())
  1313. bs, err2 := net.Dial("tcp", ":"+openPort)
  1314. for i := 0; i < 10 && err2 != nil; i++ {
  1315. time.Sleep(50 * time.Millisecond) // time for python rpc server to start
  1316. bs, err2 = net.Dial("tcp", ":"+openPort)
  1317. }
  1318. checkErrT(t, err2)
  1319. cc := MsgpackSpecRpc.ClientCodec(bs, testMsgpackH)
  1320. cl := rpc.NewClientWithCodec(cc)
  1321. defer cl.Close()
  1322. var rstr string
  1323. checkErrT(t, cl.Call("EchoStruct", TestRpcABC{"Aa", "Bb", "Cc"}, &rstr))
  1324. //checkEqualT(t, rstr, "{'A': 'Aa', 'B': 'Bb', 'C': 'Cc'}")
  1325. var mArgs MsgpackSpecRpcMultiArgs = []interface{}{"A1", "B2", "C3"}
  1326. checkErrT(t, cl.Call("Echo123", mArgs, &rstr))
  1327. checkEqualT(t, rstr, "1:A1 2:B2 3:C3", "rstr=")
  1328. cmd.Process.Kill()
  1329. }
  1330. func doTestMsgpackRpcSpecPythonClientToGoSvc(t *testing.T) {
  1331. if testSkipRPCTests {
  1332. return
  1333. }
  1334. testOnce.Do(testInitAll)
  1335. port := testCodecRpcOne(t, MsgpackSpecRpc, testMsgpackH, false, 1*time.Second)
  1336. //time.Sleep(1000 * time.Millisecond)
  1337. cmd := exec.Command("python", "test.py", "rpc-client-go-service", strconv.Itoa(port))
  1338. var cmdout []byte
  1339. var err error
  1340. if cmdout, err = cmd.CombinedOutput(); err != nil {
  1341. logT(t, "-------- Error running test.py rpc-client-go-service. Err: %v", err)
  1342. logT(t, " %v", string(cmdout))
  1343. failT(t)
  1344. }
  1345. checkEqualT(t, string(cmdout),
  1346. fmt.Sprintf("%#v\n%#v\n", []string{"A1", "B2", "C3"}, TestRpcABC{"Aa", "Bb", "Cc"}), "cmdout=")
  1347. }
  1348. func doTestSwallowAndZero(t *testing.T, h Handle) {
  1349. testOnce.Do(testInitAll)
  1350. v1 := newTestStrucFlex(testDepth, false, false, false)
  1351. var b1 []byte
  1352. e1 := NewEncoderBytes(&b1, h)
  1353. e1.MustEncode(v1)
  1354. d1 := NewDecoderBytes(b1, h)
  1355. d1.swallow()
  1356. if d1.r.numread() != len(b1) {
  1357. logT(t, "swallow didn't consume all encoded bytes: %v out of %v", d1.r.numread(), len(b1))
  1358. failT(t)
  1359. }
  1360. d1.setZero(v1)
  1361. testDeepEqualErr(v1, &TestStrucFlex{}, t, "filled-and-zeroed")
  1362. }
  1363. func doTestRawExt(t *testing.T, h Handle) {
  1364. testOnce.Do(testInitAll)
  1365. // return // TODO: need to fix this ...
  1366. var b []byte
  1367. var v interface{}
  1368. _, isJson := h.(*JsonHandle)
  1369. _, isCbor := h.(*CborHandle)
  1370. isValuer := isJson || isCbor
  1371. _ = isValuer
  1372. for _, r := range []RawExt{
  1373. {Tag: 99, Value: "9999", Data: []byte("9999")},
  1374. } {
  1375. e := NewEncoderBytes(&b, h)
  1376. e.MustEncode(&r)
  1377. d := NewDecoderBytes(b, h)
  1378. d.MustDecode(&v)
  1379. switch h.(type) {
  1380. case *JsonHandle:
  1381. testDeepEqualErr(r.Value, v, t, "rawext-json")
  1382. default:
  1383. r2 := r
  1384. if isValuer {
  1385. r2.Data = nil
  1386. } else {
  1387. r2.Value = nil
  1388. }
  1389. testDeepEqualErr(v, r2, t, "rawext-default")
  1390. }
  1391. }
  1392. }
  1393. func doTestMapStructKey(t *testing.T, h Handle) {
  1394. testOnce.Do(testInitAll)
  1395. var b []byte
  1396. var v interface{} // map[stringUint64T]wrapUint64Slice // interface{}
  1397. bh := h.getBasicHandle()
  1398. m := map[stringUint64T]wrapUint64Slice{
  1399. {"55555", 55555}: []wrapUint64{12345},
  1400. {"333", 333}: []wrapUint64{123},
  1401. }
  1402. oldCanonical := bh.Canonical
  1403. oldMapType := bh.MapType
  1404. defer func() {
  1405. bh.Canonical = oldCanonical
  1406. bh.MapType = oldMapType
  1407. }()
  1408. bh.MapType = reflect.TypeOf((*map[stringUint64T]wrapUint64Slice)(nil)).Elem()
  1409. for _, bv := range [2]bool{true, false} {
  1410. b, v = nil, nil
  1411. bh.Canonical = bv
  1412. e := NewEncoderBytes(&b, h)
  1413. e.MustEncode(m)
  1414. d := NewDecoderBytes(b, h)
  1415. d.MustDecode(&v)
  1416. testDeepEqualErr(v, m, t, "map-structkey")
  1417. }
  1418. }
  1419. func doTestDecodeNilMapValue(t *testing.T, handle Handle) {
  1420. type Struct struct {
  1421. Field map[uint16]map[uint32]struct{}
  1422. }
  1423. bh := handle.getBasicHandle()
  1424. oldMapType := bh.MapType
  1425. oldDeleteOnNilMapValue := bh.DeleteOnNilMapValue
  1426. defer func() {
  1427. bh.MapType = oldMapType
  1428. bh.DeleteOnNilMapValue = oldDeleteOnNilMapValue
  1429. }()
  1430. bh.MapType = reflect.TypeOf(map[interface{}]interface{}(nil))
  1431. bh.DeleteOnNilMapValue = false
  1432. _, isJsonHandle := handle.(*JsonHandle)
  1433. toEncode := Struct{Field: map[uint16]map[uint32]struct{}{
  1434. 1: nil,
  1435. }}
  1436. bs, err := testMarshal(toEncode, handle)
  1437. if err != nil {
  1438. logT(t, "Error encoding: %v, Err: %v", toEncode, err)
  1439. failT(t)
  1440. }
  1441. if isJsonHandle {
  1442. logT(t, "json encoded: %s\n", bs)
  1443. }
  1444. var decoded Struct
  1445. err = testUnmarshal(&decoded, bs, handle)
  1446. if err != nil {
  1447. logT(t, "Error decoding: %v", err)
  1448. failT(t)
  1449. }
  1450. if !reflect.DeepEqual(decoded, toEncode) {
  1451. logT(t, "Decoded value %#v != %#v", decoded, toEncode)
  1452. failT(t)
  1453. }
  1454. }
  1455. func testRandomFillRV(v reflect.Value) {
  1456. testOnce.Do(testInitAll)
  1457. fneg := func() int64 {
  1458. i := rand.Intn(1)
  1459. if i == 1 {
  1460. return 1
  1461. }
  1462. return -1
  1463. }
  1464. switch v.Kind() {
  1465. case reflect.Invalid:
  1466. case reflect.Ptr:
  1467. if v.IsNil() {
  1468. v.Set(reflect.New(v.Type().Elem()))
  1469. }
  1470. testRandomFillRV(v.Elem())
  1471. case reflect.Interface:
  1472. if v.IsNil() {
  1473. v.Set(reflect.ValueOf("nothing"))
  1474. } else {
  1475. testRandomFillRV(v.Elem())
  1476. }
  1477. case reflect.Struct:
  1478. for i, n := 0, v.NumField(); i < n; i++ {
  1479. testRandomFillRV(v.Field(i))
  1480. }
  1481. case reflect.Slice:
  1482. if v.IsNil() {
  1483. v.Set(reflect.MakeSlice(v.Type(), 4, 4))
  1484. }
  1485. fallthrough
  1486. case reflect.Array:
  1487. for i, n := 0, v.Len(); i < n; i++ {
  1488. testRandomFillRV(v.Index(i))
  1489. }
  1490. case reflect.Map:
  1491. if v.IsNil() {
  1492. v.Set(reflect.MakeMap(v.Type()))
  1493. }
  1494. if v.Len() == 0 {
  1495. kt, vt := v.Type().Key(), v.Type().Elem()
  1496. for i := 0; i < 4; i++ {
  1497. k0 := reflect.New(kt).Elem()
  1498. v0 := reflect.New(vt).Elem()
  1499. testRandomFillRV(k0)
  1500. testRandomFillRV(v0)
  1501. v.SetMapIndex(k0, v0)
  1502. }
  1503. } else {
  1504. for _, k := range v.MapKeys() {
  1505. testRandomFillRV(v.MapIndex(k))
  1506. }
  1507. }
  1508. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1509. v.SetInt(fneg() * rand.Int63n(127))
  1510. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  1511. v.SetUint(uint64(rand.Int63n(255)))
  1512. case reflect.Bool:
  1513. if fneg() == 1 {
  1514. v.SetBool(true)
  1515. } else {
  1516. v.SetBool(false)
  1517. }
  1518. case reflect.Float32, reflect.Float64:
  1519. v.SetFloat(float64(fneg()) * float64(rand.Float32()))
  1520. case reflect.String:
  1521. v.SetString(strings.Repeat(strconv.FormatInt(rand.Int63n(99), 10), rand.Intn(8)))
  1522. default:
  1523. panic(fmt.Errorf("testRandomFillRV: unsupported type: %v", v.Kind()))
  1524. }
  1525. }
  1526. func testMammoth(t *testing.T, name string, h Handle) {
  1527. testOnce.Do(testInitAll)
  1528. var m, m2 TestMammoth
  1529. testRandomFillRV(reflect.ValueOf(&m).Elem())
  1530. b, _ := testMarshalErr(&m, h, t, "mammoth-"+name)
  1531. testUnmarshalErr(&m2, b, h, t, "mammoth-"+name)
  1532. testDeepEqualErr(&m, &m2, t, "mammoth-"+name)
  1533. }
  1534. // -----------------
  1535. func TestBincCodecsTable(t *testing.T) {
  1536. testCodecTableOne(t, testBincH)
  1537. }
  1538. func TestBincCodecsMisc(t *testing.T) {
  1539. testCodecMiscOne(t, testBincH)
  1540. }
  1541. func TestBincCodecsEmbeddedPointer(t *testing.T) {
  1542. testCodecEmbeddedPointer(t, testBincH)
  1543. }
  1544. func TestBincStdEncIntf(t *testing.T) {
  1545. doTestStdEncIntf(t, "binc", testBincH)
  1546. }
  1547. func TestBincMammoth(t *testing.T) {
  1548. testMammoth(t, "binc", testBincH)
  1549. }
  1550. func TestSimpleCodecsTable(t *testing.T) {
  1551. testCodecTableOne(t, testSimpleH)
  1552. }
  1553. func TestSimpleCodecsMisc(t *testing.T) {
  1554. testCodecMiscOne(t, testSimpleH)
  1555. }
  1556. func TestSimpleCodecsEmbeddedPointer(t *testing.T) {
  1557. testCodecEmbeddedPointer(t, testSimpleH)
  1558. }
  1559. func TestSimpleStdEncIntf(t *testing.T) {
  1560. doTestStdEncIntf(t, "simple", testSimpleH)
  1561. }
  1562. func TestSimpleMammoth(t *testing.T) {
  1563. testMammoth(t, "simple", testSimpleH)
  1564. }
  1565. func TestMsgpackCodecsTable(t *testing.T) {
  1566. testCodecTableOne(t, testMsgpackH)
  1567. }
  1568. func TestMsgpackCodecsMisc(t *testing.T) {
  1569. testCodecMiscOne(t, testMsgpackH)
  1570. }
  1571. func TestMsgpackCodecsEmbeddedPointer(t *testing.T) {
  1572. testCodecEmbeddedPointer(t, testMsgpackH)
  1573. }
  1574. func TestMsgpackStdEncIntf(t *testing.T) {
  1575. doTestStdEncIntf(t, "msgpack", testMsgpackH)
  1576. }
  1577. func TestMsgpackMammoth(t *testing.T) {
  1578. testMammoth(t, "msgpack", testMsgpackH)
  1579. }
  1580. func TestCborCodecsTable(t *testing.T) {
  1581. testCodecTableOne(t, testCborH)
  1582. }
  1583. func TestCborCodecsMisc(t *testing.T) {
  1584. testCodecMiscOne(t, testCborH)
  1585. }
  1586. func TestCborCodecsEmbeddedPointer(t *testing.T) {
  1587. testCodecEmbeddedPointer(t, testCborH)
  1588. }
  1589. func TestCborMapEncodeForCanonical(t *testing.T) {
  1590. doTestMapEncodeForCanonical(t, "cbor", testCborH)
  1591. }
  1592. func TestCborCodecChan(t *testing.T) {
  1593. testCodecChan(t, testCborH)
  1594. }
  1595. func TestCborStdEncIntf(t *testing.T) {
  1596. doTestStdEncIntf(t, "cbor", testCborH)
  1597. }
  1598. func TestCborMammoth(t *testing.T) {
  1599. testMammoth(t, "cbor", testCborH)
  1600. }
  1601. func TestJsonCodecsTable(t *testing.T) {
  1602. testCodecTableOne(t, testJsonH)
  1603. }
  1604. func TestJsonCodecsMisc(t *testing.T) {
  1605. testCodecMiscOne(t, testJsonH)
  1606. }
  1607. func TestJsonCodecsEmbeddedPointer(t *testing.T) {
  1608. testCodecEmbeddedPointer(t, testJsonH)
  1609. }
  1610. func TestJsonCodecChan(t *testing.T) {
  1611. testCodecChan(t, testJsonH)
  1612. }
  1613. func TestJsonStdEncIntf(t *testing.T) {
  1614. doTestStdEncIntf(t, "json", testJsonH)
  1615. }
  1616. func TestJsonMammoth(t *testing.T) {
  1617. testMammoth(t, "json", testJsonH)
  1618. }
  1619. // ----- Raw ---------
  1620. func TestJsonRaw(t *testing.T) {
  1621. doTestRawValue(t, "json", testJsonH)
  1622. }
  1623. func TestBincRaw(t *testing.T) {
  1624. doTestRawValue(t, "binc", testBincH)
  1625. }
  1626. func TestMsgpackRaw(t *testing.T) {
  1627. doTestRawValue(t, "msgpack", testMsgpackH)
  1628. }
  1629. func TestSimpleRaw(t *testing.T) {
  1630. doTestRawValue(t, "simple", testSimpleH)
  1631. }
  1632. func TestCborRaw(t *testing.T) {
  1633. doTestRawValue(t, "cbor", testCborH)
  1634. }
  1635. // ----- ALL (framework based) -----
  1636. func TestAllEncCircularRef(t *testing.T) {
  1637. doTestEncCircularRef(t, "cbor", testCborH)
  1638. }
  1639. func TestAllAnonCycle(t *testing.T) {
  1640. doTestAnonCycle(t, "cbor", testCborH)
  1641. }
  1642. // ----- RPC -----
  1643. func TestBincRpcGo(t *testing.T) {
  1644. testCodecRpcOne(t, GoRpc, testBincH, true, 0)
  1645. }
  1646. func TestSimpleRpcGo(t *testing.T) {
  1647. testCodecRpcOne(t, GoRpc, testSimpleH, true, 0)
  1648. }
  1649. func TestMsgpackRpcGo(t *testing.T) {
  1650. testCodecRpcOne(t, GoRpc, testMsgpackH, true, 0)
  1651. }
  1652. func TestCborRpcGo(t *testing.T) {
  1653. testCodecRpcOne(t, GoRpc, testCborH, true, 0)
  1654. }
  1655. func TestJsonRpcGo(t *testing.T) {
  1656. testCodecRpcOne(t, GoRpc, testJsonH, true, 0)
  1657. }
  1658. func TestMsgpackRpcSpec(t *testing.T) {
  1659. testCodecRpcOne(t, MsgpackSpecRpc, testMsgpackH, true, 0)
  1660. }
  1661. func TestBincUnderlyingType(t *testing.T) {
  1662. testCodecUnderlyingType(t, testBincH)
  1663. }
  1664. func TestJsonSwallowAndZero(t *testing.T) {
  1665. doTestSwallowAndZero(t, testJsonH)
  1666. }
  1667. func TestCborSwallowAndZero(t *testing.T) {
  1668. doTestSwallowAndZero(t, testCborH)
  1669. }
  1670. func TestMsgpackSwallowAndZero(t *testing.T) {
  1671. doTestSwallowAndZero(t, testMsgpackH)
  1672. }
  1673. func TestBincSwallowAndZero(t *testing.T) {
  1674. doTestSwallowAndZero(t, testBincH)
  1675. }
  1676. func TestSimpleSwallowAndZero(t *testing.T) {
  1677. doTestSwallowAndZero(t, testSimpleH)
  1678. }
  1679. func TestJsonRawExt(t *testing.T) {
  1680. doTestRawExt(t, testJsonH)
  1681. }
  1682. func TestCborRawExt(t *testing.T) {
  1683. doTestRawExt(t, testCborH)
  1684. }
  1685. func TestMsgpackRawExt(t *testing.T) {
  1686. doTestRawExt(t, testMsgpackH)
  1687. }
  1688. func TestBincRawExt(t *testing.T) {
  1689. doTestRawExt(t, testBincH)
  1690. }
  1691. func TestSimpleRawExt(t *testing.T) {
  1692. doTestRawExt(t, testSimpleH)
  1693. }
  1694. func TestJsonMapStructKey(t *testing.T) {
  1695. doTestMapStructKey(t, testJsonH)
  1696. }
  1697. func TestCborMapStructKey(t *testing.T) {
  1698. doTestMapStructKey(t, testCborH)
  1699. }
  1700. func TestMsgpackMapStructKey(t *testing.T) {
  1701. doTestMapStructKey(t, testMsgpackH)
  1702. }
  1703. func TestBincMapStructKey(t *testing.T) {
  1704. doTestMapStructKey(t, testBincH)
  1705. }
  1706. func TestSimpleMapStructKey(t *testing.T) {
  1707. doTestMapStructKey(t, testSimpleH)
  1708. }
  1709. func TestJsonDecodeNilMapValue(t *testing.T) {
  1710. doTestDecodeNilMapValue(t, testJsonH)
  1711. }
  1712. func TestCborDecodeNilMapValue(t *testing.T) {
  1713. doTestDecodeNilMapValue(t, testCborH)
  1714. }
  1715. func TestMsgpackDecodeNilMapValue(t *testing.T) {
  1716. doTestDecodeNilMapValue(t, testMsgpackH)
  1717. }
  1718. func TestBincDecodeNilMapValue(t *testing.T) {
  1719. doTestDecodeNilMapValue(t, testBincH)
  1720. }
  1721. func TestSimpleDecodeNilMapValue(t *testing.T) {
  1722. doTestDecodeNilMapValue(t, testSimpleH)
  1723. }
  1724. func TestJsonLargeInteger(t *testing.T) {
  1725. for _, i := range []uint8{'L', 'A', 0} {
  1726. for _, j := range []interface{}{
  1727. int64(1 << 60),
  1728. -int64(1 << 60),
  1729. 0,
  1730. 1 << 20,
  1731. -(1 << 20),
  1732. uint64(1 << 60),
  1733. uint(0),
  1734. uint(1 << 20),
  1735. } {
  1736. doTestJsonLargeInteger(t, j, i)
  1737. }
  1738. }
  1739. }
  1740. func TestJsonDecodeNonStringScalarInStringContext(t *testing.T) {
  1741. var b = `{"s.true": "true", "b.true": true, "s.false": "false", "b.false": false, "s.10": "10", "i.10": 10, "i.-10": -10}`
  1742. var golden = map[string]string{"s.true": "true", "b.true": "true", "s.false": "false", "b.false": "false", "s.10": "10", "i.10": "10", "i.-10": "-10"}
  1743. var m map[string]string
  1744. d := NewDecoderBytes([]byte(b), testJsonH)
  1745. d.MustDecode(&m)
  1746. if err := deepEqual(golden, m); err == nil {
  1747. logT(t, "++++ match: decoded: %#v", m)
  1748. } else {
  1749. logT(t, "---- mismatch: %v ==> golden: %#v, decoded: %#v", err, golden, m)
  1750. failT(t)
  1751. }
  1752. }
  1753. func TestJsonEncodeIndent(t *testing.T) {
  1754. v := TestSimplish{
  1755. Ii: -794,
  1756. Ss: `A Man is
  1757. after the new line
  1758. after new line and tab
  1759. `,
  1760. }
  1761. v2 := v
  1762. v.Mm = make(map[string]*TestSimplish)
  1763. for i := 0; i < len(v.Ar); i++ {
  1764. v3 := v2
  1765. v3.Ii += (i * 4)
  1766. v3.Ss = fmt.Sprintf("%d - %s", v3.Ii, v3.Ss)
  1767. if i%2 == 0 {
  1768. v.Ar[i] = &v3
  1769. }
  1770. // v3 = v2
  1771. v.Sl = append(v.Sl, &v3)
  1772. v.Mm[strconv.FormatInt(int64(i), 10)] = &v3
  1773. }
  1774. oldcan := testJsonH.Canonical
  1775. oldIndent := testJsonH.Indent
  1776. oldS2A := testJsonH.StructToArray
  1777. defer func() {
  1778. testJsonH.Canonical = oldcan
  1779. testJsonH.Indent = oldIndent
  1780. testJsonH.StructToArray = oldS2A
  1781. }()
  1782. testJsonH.Canonical = true
  1783. testJsonH.Indent = -1
  1784. testJsonH.StructToArray = false
  1785. var bs []byte
  1786. NewEncoderBytes(&bs, testJsonH).MustEncode(&v)
  1787. txt1Tab := string(bs)
  1788. bs = nil
  1789. testJsonH.Indent = 120
  1790. NewEncoderBytes(&bs, testJsonH).MustEncode(&v)
  1791. txtSpaces := string(bs)
  1792. // fmt.Printf("\n-----------\n%s\n------------\n%s\n-------------\n", txt1Tab, txtSpaces)
  1793. goldenResultTab := `{
  1794. "Ar": [
  1795. {
  1796. "Ar": [
  1797. null,
  1798. null
  1799. ],
  1800. "Ii": -794,
  1801. "Mm": null,
  1802. "Sl": null,
  1803. "Ss": "-794 - A Man is\nafter the new line\n\tafter new line and tab\n"
  1804. },
  1805. null
  1806. ],
  1807. "Ii": -794,
  1808. "Mm": {
  1809. "0": {
  1810. "Ar": [
  1811. null,
  1812. null
  1813. ],
  1814. "Ii": -794,
  1815. "Mm": null,
  1816. "Sl": null,
  1817. "Ss": "-794 - A Man is\nafter the new line\n\tafter new line and tab\n"
  1818. },
  1819. "1": {
  1820. "Ar": [
  1821. null,
  1822. null
  1823. ],
  1824. "Ii": -790,
  1825. "Mm": null,
  1826. "Sl": null,
  1827. "Ss": "-790 - A Man is\nafter the new line\n\tafter new line and tab\n"
  1828. }
  1829. },
  1830. "Sl": [
  1831. {
  1832. "Ar": [
  1833. null,
  1834. null
  1835. ],
  1836. "Ii": -794,
  1837. "Mm": null,
  1838. "Sl": null,
  1839. "Ss": "-794 - A Man is\nafter the new line\n\tafter new line and tab\n"
  1840. },
  1841. {
  1842. "Ar": [
  1843. null,
  1844. null
  1845. ],
  1846. "Ii": -790,
  1847. "Mm": null,
  1848. "Sl": null,
  1849. "Ss": "-790 - A Man is\nafter the new line\n\tafter new line and tab\n"
  1850. }
  1851. ],
  1852. "Ss": "A Man is\nafter the new line\n\tafter new line and tab\n"
  1853. }`
  1854. if txt1Tab != goldenResultTab {
  1855. logT(t, "decoded indented with tabs != expected: \nexpected: %s\nencoded: %s", goldenResultTab, txt1Tab)
  1856. failT(t)
  1857. }
  1858. if txtSpaces != strings.Replace(goldenResultTab, "\t", strings.Repeat(" ", 120), -1) {
  1859. logT(t, "decoded indented with spaces != expected: \nexpected: %s\nencoded: %s", goldenResultTab, txtSpaces)
  1860. failT(t)
  1861. }
  1862. }
  1863. // TODO:
  1864. // Add Tests for:
  1865. // - decoding empty list/map in stream into a nil slice/map
  1866. // - binary(M|Unm)arsher support for time.Time (e.g. cbor encoding)
  1867. // - text(M|Unm)arshaler support for time.Time (e.g. json encoding)
  1868. // - non fast-path scenarios e.g. map[string]uint16, []customStruct.
  1869. // Expand cbor to include indefinite length stuff for this non-fast-path types.
  1870. // This may not be necessary, since we have the manual tests (fastpathEnabled=false) to test/validate with.
  1871. // - CodecSelfer
  1872. // Ensure it is called when (en|de)coding interface{} or reflect.Value (2 different codepaths).
  1873. // - interfaces: textMarshaler, binaryMarshaler, codecSelfer
  1874. // - struct tags:
  1875. // on anonymous fields, _struct (all fields), etc
  1876. // - codecgen of struct containing channels.
  1877. //
  1878. // Add negative tests for failure conditions:
  1879. // - bad input with large array length prefix