codec_test.go 62 KB

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