codec_test.go 56 KB

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