shared_test.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. // This file sets up the variables used, including testInitFns.
  5. // Each file should add initialization that should be performed
  6. // after flags are parsed.
  7. //
  8. // init is a multi-step process:
  9. // - setup vars (handled by init functions in each file)
  10. // - parse flags
  11. // - setup derived vars (handled by pre-init registered functions - registered in init function)
  12. // - post init (handled by post-init registered functions - registered in init function)
  13. // This way, no one has to manage carefully control the initialization
  14. // using file names, etc.
  15. //
  16. // Tests which require external dependencies need the -tag=x parameter.
  17. // They should be run as:
  18. // go test -tags=x -run=. <other parameters ...>
  19. // Benchmarks should also take this parameter, to include the sereal, xdr, etc.
  20. // To run against codecgen, etc, make sure you pass extra parameters.
  21. // Example usage:
  22. // go test "-tags=x codecgen" -bench=. <other parameters ...>
  23. //
  24. // To fully test everything:
  25. // go test -tags=x -benchtime=100ms -tv -bg -bi -brw -bu -v -run=. -bench=.
  26. // Handling flags
  27. // codec_test.go will define a set of global flags for testing, including:
  28. // - Use Reset
  29. // - Use IO reader/writer (vs direct bytes)
  30. // - Set Canonical
  31. // - Set InternStrings
  32. // - Use Symbols
  33. //
  34. // This way, we can test them all by running same set of tests with a different
  35. // set of flags.
  36. //
  37. // Following this, all the benchmarks will utilize flags set by codec_test.go
  38. // and will not redefine these "global" flags.
  39. import (
  40. "bytes"
  41. "flag"
  42. "fmt"
  43. "io"
  44. "sync"
  45. "testing"
  46. )
  47. // DO NOT REMOVE - replacement line for go-codec-bench import declaration tag //
  48. type testHED struct {
  49. H Handle
  50. E *Encoder
  51. D *Decoder
  52. }
  53. type ioReaderWrapper struct {
  54. r io.Reader
  55. }
  56. func (x ioReaderWrapper) Read(p []byte) (n int, err error) {
  57. return x.r.Read(p)
  58. }
  59. type ioWriterWrapper struct {
  60. w io.Writer
  61. }
  62. func (x ioWriterWrapper) Write(p []byte) (n int, err error) {
  63. return x.w.Write(p)
  64. }
  65. var (
  66. // testNoopH = NoopHandle(8)
  67. testMsgpackH = &MsgpackHandle{}
  68. testBincH = &BincHandle{}
  69. testSimpleH = &SimpleHandle{}
  70. testCborH = &CborHandle{}
  71. testJsonH = &JsonHandle{}
  72. testHandles []Handle
  73. testPreInitFns []func()
  74. testPostInitFns []func()
  75. testOnce sync.Once
  76. testHEDs []testHED
  77. )
  78. // flag variables used by tests (and bench)
  79. var (
  80. testDepth int
  81. testVerbose bool
  82. testInitDebug bool
  83. testStructToArray bool
  84. testCanonical bool
  85. testUseReset bool
  86. testSkipIntf bool
  87. testInternStr bool
  88. testUseMust bool
  89. testCheckCircRef bool
  90. testUseIoEncDec int
  91. testUseIoWrapper bool
  92. testMaxInitLen int
  93. testNumRepeatString int
  94. testRpcBufsize int
  95. )
  96. // variables that are not flags, but which can configure the handles
  97. var (
  98. testEncodeOptions EncodeOptions
  99. testDecodeOptions DecodeOptions
  100. )
  101. // flag variables used by bench
  102. var (
  103. benchDoInitBench bool
  104. benchVerify bool
  105. benchUnscientificRes bool = false
  106. benchMapStringKeyOnly bool
  107. //depth of 0 maps to ~400bytes json-encoded string, 1 maps to ~1400 bytes, etc
  108. //For depth>1, we likely trigger stack growth for encoders, making benchmarking unreliable.
  109. benchDepth int
  110. benchInitDebug bool
  111. )
  112. func init() {
  113. testHEDs = make([]testHED, 0, 32)
  114. testHandles = append(testHandles,
  115. // testNoopH,
  116. testMsgpackH, testBincH, testSimpleH,
  117. testCborH, testJsonH)
  118. testInitFlags()
  119. benchInitFlags()
  120. }
  121. func testInitFlags() {
  122. // delete(testDecOpts.ExtFuncs, timeTyp)
  123. flag.IntVar(&testDepth, "tsd", 0, "Test Struc Depth")
  124. flag.BoolVar(&testVerbose, "tv", false, "Test Verbose")
  125. flag.BoolVar(&testInitDebug, "tg", false, "Test Init Debug")
  126. flag.IntVar(&testUseIoEncDec, "ti", -1, "Use IO Reader/Writer for Marshal/Unmarshal ie >= 0")
  127. flag.BoolVar(&testUseIoWrapper, "tiw", false, "Wrap the IO Reader/Writer with a base pass-through reader/writer")
  128. flag.BoolVar(&testStructToArray, "ts", false, "Set StructToArray option")
  129. flag.BoolVar(&testCanonical, "tc", false, "Set Canonical option")
  130. flag.BoolVar(&testInternStr, "te", false, "Set InternStr option")
  131. flag.BoolVar(&testSkipIntf, "tf", false, "Skip Interfaces")
  132. flag.BoolVar(&testUseReset, "tr", false, "Use Reset")
  133. flag.IntVar(&testNumRepeatString, "trs", 8, "Create string variables by repeating a string N times")
  134. flag.IntVar(&testMaxInitLen, "tx", 0, "Max Init Len")
  135. flag.BoolVar(&testUseMust, "tm", true, "Use Must(En|De)code")
  136. flag.BoolVar(&testCheckCircRef, "tl", false, "Use Check Circular Ref")
  137. }
  138. func benchInitFlags() {
  139. flag.BoolVar(&benchMapStringKeyOnly, "bs", false, "Bench use maps with string keys only")
  140. flag.BoolVar(&benchInitDebug, "bg", false, "Bench Debug")
  141. flag.IntVar(&benchDepth, "bd", 1, "Bench Depth")
  142. flag.BoolVar(&benchDoInitBench, "bi", false, "Run Bench Init")
  143. flag.BoolVar(&benchVerify, "bv", false, "Verify Decoded Value during Benchmark")
  144. flag.BoolVar(&benchUnscientificRes, "bu", false, "Show Unscientific Results during Benchmark")
  145. }
  146. func testHEDGet(h Handle) *testHED {
  147. for i := range testHEDs {
  148. v := &testHEDs[i]
  149. if v.H == h {
  150. return v
  151. }
  152. }
  153. testHEDs = append(testHEDs, testHED{h, NewEncoder(nil, h), NewDecoder(nil, h)})
  154. return &testHEDs[len(testHEDs)-1]
  155. }
  156. func testReinit() {
  157. testOnce = sync.Once{}
  158. testHEDs = nil
  159. }
  160. func testInitAll() {
  161. // only parse it once.
  162. if !flag.Parsed() {
  163. flag.Parse()
  164. }
  165. for _, f := range testPreInitFns {
  166. f()
  167. }
  168. for _, f := range testPostInitFns {
  169. f()
  170. }
  171. }
  172. func sTestCodecEncode(ts interface{}, bsIn []byte, fn func([]byte) *bytes.Buffer,
  173. h Handle, bh *BasicHandle) (bs []byte, err error) {
  174. // bs = make([]byte, 0, approxSize)
  175. var e *Encoder
  176. var buf *bytes.Buffer
  177. if testUseReset {
  178. e = testHEDGet(h).E
  179. } else {
  180. e = NewEncoder(nil, h)
  181. }
  182. var oldWriteBufferSize int
  183. if testUseIoEncDec >= 0 {
  184. buf = fn(bsIn)
  185. // set the encode options for using a buffer
  186. oldWriteBufferSize = bh.WriterBufferSize
  187. bh.WriterBufferSize = testUseIoEncDec
  188. if testUseIoWrapper {
  189. e.Reset(ioWriterWrapper{buf})
  190. } else {
  191. e.Reset(buf)
  192. }
  193. } else {
  194. bs = bsIn
  195. e.ResetBytes(&bs)
  196. }
  197. if testUseMust {
  198. e.MustEncode(ts)
  199. } else {
  200. err = e.Encode(ts)
  201. }
  202. if testUseIoEncDec >= 0 {
  203. bs = buf.Bytes()
  204. bh.WriterBufferSize = oldWriteBufferSize
  205. }
  206. return
  207. }
  208. func sTestCodecDecode(bs []byte, ts interface{}, h Handle, bh *BasicHandle) (err error) {
  209. var d *Decoder
  210. // var buf *bytes.Reader
  211. if testUseReset {
  212. d = testHEDGet(h).D
  213. } else {
  214. d = NewDecoder(nil, h)
  215. }
  216. var oldReadBufferSize int
  217. if testUseIoEncDec >= 0 {
  218. buf := bytes.NewReader(bs)
  219. oldReadBufferSize = bh.ReaderBufferSize
  220. bh.ReaderBufferSize = testUseIoEncDec
  221. if testUseIoWrapper {
  222. d.Reset(ioReaderWrapper{buf})
  223. } else {
  224. d.Reset(buf)
  225. }
  226. } else {
  227. d.ResetBytes(bs)
  228. }
  229. if testUseMust {
  230. d.MustDecode(ts)
  231. } else {
  232. err = d.Decode(ts)
  233. }
  234. if testUseIoEncDec >= 0 {
  235. bh.ReaderBufferSize = oldReadBufferSize
  236. }
  237. return
  238. }
  239. // --- functions below are used by both benchmarks and tests
  240. func logT(x interface{}, format string, args ...interface{}) {
  241. if t, ok := x.(*testing.T); ok && t != nil {
  242. t.Logf(format, args...)
  243. } else if b, ok := x.(*testing.B); ok && b != nil {
  244. b.Logf(format, args...)
  245. } else if testVerbose {
  246. if len(format) == 0 || format[len(format)-1] != '\n' {
  247. format = format + "\n"
  248. }
  249. fmt.Printf(format, args...)
  250. }
  251. }
  252. // --- functions below are used only by benchmarks alone
  253. func fnBenchmarkByteBuf(bsIn []byte) (buf *bytes.Buffer) {
  254. // var buf bytes.Buffer
  255. // buf.Grow(approxSize)
  256. buf = bytes.NewBuffer(bsIn)
  257. buf.Truncate(0)
  258. return
  259. }
  260. // func benchFnCodecEncode(ts interface{}, bsIn []byte, h Handle) (bs []byte, err error) {
  261. // return testCodecEncode(ts, bsIn, fnBenchmarkByteBuf, h)
  262. // }
  263. // func benchFnCodecDecode(bs []byte, ts interface{}, h Handle) (err error) {
  264. // return testCodecDecode(bs, ts, h)
  265. // }