shared_test.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. // Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved.
  2. // Use of this source code is governed by a MIT license found in the LICENSE file.
  3. package codec
  4. // 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. "io"
  43. "io/ioutil"
  44. "log"
  45. "sync"
  46. )
  47. // __DO_NOT_REMOVE__NEEDED_FOR_REPLACING__IMPORT_PATH__FOR_CODEC_BENCH__
  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. testVerbose bool
  81. //depth of 0 maps to ~400bytes json-encoded string, 1 maps to ~1400 bytes, etc
  82. //For depth>1, we likely trigger stack growth for encoders, making benchmarking unreliable.
  83. testDepth int
  84. testMaxInitLen int
  85. testInitDebug bool
  86. testUseReset bool
  87. testSkipIntf bool
  88. testUseMust bool
  89. testUseIoEncDec int
  90. testUseIoWrapper bool
  91. testNumRepeatString int
  92. testRpcBufsize int
  93. testMapStringKeyOnly bool
  94. )
  95. // variables that are not flags, but which can configure the handles
  96. var (
  97. testEncodeOptions EncodeOptions
  98. testDecodeOptions DecodeOptions
  99. )
  100. func init() {
  101. log.SetOutput(ioutil.Discard) // don't allow things log to standard out/err
  102. testHEDs = make([]testHED, 0, 32)
  103. testHandles = append(testHandles,
  104. // testNoopH,
  105. testMsgpackH, testBincH, testSimpleH, testCborH, testJsonH)
  106. // JSON should do HTMLCharsAsIs by default
  107. testJsonH.HTMLCharsAsIs = true
  108. // set ExplicitRelease on each handle
  109. testMsgpackH.ExplicitRelease = true
  110. testBincH.ExplicitRelease = true
  111. testSimpleH.ExplicitRelease = true
  112. testCborH.ExplicitRelease = true
  113. testJsonH.ExplicitRelease = true
  114. testInitFlags()
  115. benchInitFlags()
  116. }
  117. func testInitFlags() {
  118. // delete(testDecOpts.ExtFuncs, timeTyp)
  119. flag.BoolVar(&testVerbose, "tv", false, "Text Extra Verbose Logging if -v if set")
  120. flag.BoolVar(&testInitDebug, "tg", false, "Test Init Debug")
  121. flag.IntVar(&testUseIoEncDec, "ti", -1, "Use IO Reader/Writer for Marshal/Unmarshal ie >= 0")
  122. flag.BoolVar(&testUseIoWrapper, "tiw", false, "Wrap the IO Reader/Writer with a base pass-through reader/writer")
  123. flag.BoolVar(&testSkipIntf, "tf", false, "Skip Interfaces")
  124. flag.BoolVar(&testUseReset, "tr", false, "Use Reset")
  125. flag.IntVar(&testNumRepeatString, "trs", 8, "Create string variables by repeating a string N times")
  126. flag.BoolVar(&testUseMust, "tm", true, "Use Must(En|De)code")
  127. flag.IntVar(&testMaxInitLen, "tx", 0, "Max Init Len")
  128. flag.IntVar(&testDepth, "tsd", 0, "Test Struc Depth")
  129. flag.BoolVar(&testMapStringKeyOnly, "tsk", false, "use maps with string keys only")
  130. }
  131. func benchInitFlags() {
  132. // flags reproduced here for compatibility (duplicate some in testInitFlags)
  133. flag.BoolVar(&testMapStringKeyOnly, "bs", false, "use maps with string keys only")
  134. flag.IntVar(&testDepth, "bd", 1, "Bench Depth")
  135. }
  136. func testHEDGet(h Handle) *testHED {
  137. for i := range testHEDs {
  138. v := &testHEDs[i]
  139. if v.H == h {
  140. return v
  141. }
  142. }
  143. testHEDs = append(testHEDs, testHED{h, NewEncoder(nil, h), NewDecoder(nil, h)})
  144. return &testHEDs[len(testHEDs)-1]
  145. }
  146. func testReinit() {
  147. testOnce = sync.Once{}
  148. testHEDs = nil
  149. }
  150. func testInitAll() {
  151. // only parse it once.
  152. if !flag.Parsed() {
  153. flag.Parse()
  154. }
  155. for _, f := range testPreInitFns {
  156. f()
  157. }
  158. for _, f := range testPostInitFns {
  159. f()
  160. }
  161. }
  162. func sTestCodecEncode(ts interface{}, bsIn []byte, fn func([]byte) *bytes.Buffer,
  163. h Handle, bh *BasicHandle) (bs []byte, err error) {
  164. // bs = make([]byte, 0, approxSize)
  165. var e *Encoder
  166. var buf *bytes.Buffer
  167. if testUseReset {
  168. e = testHEDGet(h).E
  169. } else {
  170. e = NewEncoder(nil, h)
  171. }
  172. var oldWriteBufferSize int
  173. if testUseIoEncDec >= 0 {
  174. buf = fn(bsIn)
  175. // set the encode options for using a buffer
  176. oldWriteBufferSize = bh.WriterBufferSize
  177. bh.WriterBufferSize = testUseIoEncDec
  178. if testUseIoWrapper {
  179. e.Reset(ioWriterWrapper{buf})
  180. } else {
  181. e.Reset(buf)
  182. }
  183. } else {
  184. bs = bsIn
  185. e.ResetBytes(&bs)
  186. }
  187. if testUseMust {
  188. e.MustEncode(ts)
  189. } else {
  190. err = e.Encode(ts)
  191. }
  192. if testUseIoEncDec >= 0 {
  193. bs = buf.Bytes()
  194. bh.WriterBufferSize = oldWriteBufferSize
  195. }
  196. if !testUseReset {
  197. e.Release()
  198. }
  199. return
  200. }
  201. func sTestCodecDecode(bs []byte, ts interface{}, h Handle, bh *BasicHandle) (err error) {
  202. var d *Decoder
  203. // var buf *bytes.Reader
  204. if testUseReset {
  205. d = testHEDGet(h).D
  206. } else {
  207. d = NewDecoder(nil, h)
  208. }
  209. var oldReadBufferSize int
  210. if testUseIoEncDec >= 0 {
  211. buf := bytes.NewReader(bs)
  212. oldReadBufferSize = bh.ReaderBufferSize
  213. bh.ReaderBufferSize = testUseIoEncDec
  214. if testUseIoWrapper {
  215. d.Reset(ioReaderWrapper{buf})
  216. } else {
  217. d.Reset(buf)
  218. }
  219. } else {
  220. d.ResetBytes(bs)
  221. }
  222. if testUseMust {
  223. d.MustDecode(ts)
  224. } else {
  225. err = d.Decode(ts)
  226. }
  227. if testUseIoEncDec >= 0 {
  228. bh.ReaderBufferSize = oldReadBufferSize
  229. }
  230. if !testUseReset {
  231. d.Release()
  232. }
  233. return
  234. }
  235. // // --- functions below are used by both benchmarks and tests
  236. // // log message only when testVerbose = true (ie go test ... -- -tv).
  237. // //
  238. // // These are for intormational messages that do not necessarily
  239. // // help with diagnosing a failure, or which are too large.
  240. // func logTv(x interface{}, format string, args ...interface{}) {
  241. // if !testVerbose {
  242. // return
  243. // }
  244. // if t, ok := x.(testing.TB); ok { // only available from go 1.9
  245. // t.Helper()
  246. // }
  247. // logT(x, format, args...)
  248. // }
  249. // // logT logs messages when running as go test -v
  250. // //
  251. // // Use it for diagnostics messages that help diagnost failure,
  252. // // and when the output is not too long ie shorter than like 100 characters.
  253. // //
  254. // // In general, any logT followed by failT should call this.
  255. // func logT(x interface{}, format string, args ...interface{}) {
  256. // if x == nil {
  257. // if len(format) == 0 || format[len(format)-1] != '\n' {
  258. // format = format + "\n"
  259. // }
  260. // fmt.Printf(format, args...)
  261. // return
  262. // }
  263. // if t, ok := x.(testing.TB); ok { // only available from go 1.9
  264. // t.Helper()
  265. // t.Logf(format, args...)
  266. // }
  267. // }
  268. // func failTv(x testing.TB, args ...interface{}) {
  269. // x.Helper()
  270. // if testVerbose {
  271. // failTMsg(x, args...)
  272. // }
  273. // x.FailNow()
  274. // }
  275. // func failT(x testing.TB, args ...interface{}) {
  276. // x.Helper()
  277. // failTMsg(x, args...)
  278. // x.FailNow()
  279. // }
  280. // func failTMsg(x testing.TB, args ...interface{}) {
  281. // x.Helper()
  282. // if len(args) > 0 {
  283. // if format, ok := args[0].(string); ok {
  284. // logT(x, format, args[1:]...)
  285. // } else if len(args) == 1 {
  286. // logT(x, "%v", args[0])
  287. // } else {
  288. // logT(x, "%v", args)
  289. // }
  290. // }
  291. // }
  292. // --- functions below are used only by benchmarks alone
  293. func fnBenchmarkByteBuf(bsIn []byte) (buf *bytes.Buffer) {
  294. // var buf bytes.Buffer
  295. // buf.Grow(approxSize)
  296. buf = bytes.NewBuffer(bsIn)
  297. buf.Truncate(0)
  298. return
  299. }
  300. // func benchFnCodecEncode(ts interface{}, bsIn []byte, h Handle) (bs []byte, err error) {
  301. // return testCodecEncode(ts, bsIn, fnBenchmarkByteBuf, h)
  302. // }
  303. // func benchFnCodecDecode(bs []byte, ts interface{}, h Handle) (err error) {
  304. // return testCodecDecode(bs, ts, h)
  305. // }