shared_test.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. "fmt"
  43. "io"
  44. "io/ioutil"
  45. "log"
  46. "sync"
  47. "testing"
  48. )
  49. import . "github.com/ugorji/go/codec"
  50. type testHED struct {
  51. H Handle
  52. E *Encoder
  53. D *Decoder
  54. }
  55. type ioReaderWrapper struct {
  56. r io.Reader
  57. }
  58. func (x ioReaderWrapper) Read(p []byte) (n int, err error) {
  59. return x.r.Read(p)
  60. }
  61. type ioWriterWrapper struct {
  62. w io.Writer
  63. }
  64. func (x ioWriterWrapper) Write(p []byte) (n int, err error) {
  65. return x.w.Write(p)
  66. }
  67. var (
  68. // testNoopH = NoopHandle(8)
  69. testMsgpackH = &MsgpackHandle{}
  70. testBincH = &BincHandle{}
  71. testSimpleH = &SimpleHandle{}
  72. testCborH = &CborHandle{}
  73. testJsonH = &JsonHandle{}
  74. testHandles []Handle
  75. testPreInitFns []func()
  76. testPostInitFns []func()
  77. testOnce sync.Once
  78. testHEDs []testHED
  79. )
  80. // flag variables used by tests (and bench)
  81. var (
  82. testVerbose bool
  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. )
  94. // variables that are not flags, but which can configure the handles
  95. var (
  96. testEncodeOptions EncodeOptions
  97. testDecodeOptions DecodeOptions
  98. )
  99. // flag variables used by bench
  100. var (
  101. benchDoInitBench bool
  102. benchVerify bool
  103. benchUnscientificRes bool = false
  104. benchMapStringKeyOnly bool
  105. //depth of 0 maps to ~400bytes json-encoded string, 1 maps to ~1400 bytes, etc
  106. //For depth>1, we likely trigger stack growth for encoders, making benchmarking unreliable.
  107. benchDepth int
  108. benchInitDebug bool
  109. )
  110. func init() {
  111. log.SetOutput(ioutil.Discard) // don't allow things log to standard out/err
  112. testHEDs = make([]testHED, 0, 32)
  113. testHandles = append(testHandles,
  114. // testNoopH,
  115. testMsgpackH, testBincH, testSimpleH, testCborH, testJsonH)
  116. // JSON should do HTMLCharsAsIs by default
  117. testJsonH.HTMLCharsAsIs = true
  118. // set ExplicitRelease on each handle
  119. testMsgpackH.ExplicitRelease = true
  120. testBincH.ExplicitRelease = true
  121. testSimpleH.ExplicitRelease = true
  122. testCborH.ExplicitRelease = true
  123. testJsonH.ExplicitRelease = true
  124. testInitFlags()
  125. benchInitFlags()
  126. }
  127. func testInitFlags() {
  128. // delete(testDecOpts.ExtFuncs, timeTyp)
  129. flag.BoolVar(&testVerbose, "tv", false, "Text Extra Verbose Logging if -v if set")
  130. flag.IntVar(&testDepth, "tsd", 0, "Test Struc Depth")
  131. flag.BoolVar(&testInitDebug, "tg", false, "Test Init Debug")
  132. flag.IntVar(&testUseIoEncDec, "ti", -1, "Use IO Reader/Writer for Marshal/Unmarshal ie >= 0")
  133. flag.BoolVar(&testUseIoWrapper, "tiw", false, "Wrap the IO Reader/Writer with a base pass-through reader/writer")
  134. flag.BoolVar(&testSkipIntf, "tf", false, "Skip Interfaces")
  135. flag.BoolVar(&testUseReset, "tr", false, "Use Reset")
  136. flag.IntVar(&testNumRepeatString, "trs", 8, "Create string variables by repeating a string N times")
  137. flag.BoolVar(&testUseMust, "tm", true, "Use Must(En|De)code")
  138. flag.IntVar(&testMaxInitLen, "tx", 0, "Max Init Len")
  139. }
  140. func benchInitFlags() {
  141. flag.BoolVar(&benchMapStringKeyOnly, "bs", false, "Bench use maps with string keys only")
  142. flag.BoolVar(&benchInitDebug, "bg", false, "Bench Debug")
  143. flag.IntVar(&benchDepth, "bd", 1, "Bench Depth")
  144. flag.BoolVar(&benchDoInitBench, "bi", false, "Run Bench Init")
  145. flag.BoolVar(&benchVerify, "bv", false, "Verify Decoded Value during Benchmark")
  146. flag.BoolVar(&benchUnscientificRes, "bu", false, "Show Unscientific Results during Benchmark")
  147. }
  148. func testHEDGet(h Handle) *testHED {
  149. for i := range testHEDs {
  150. v := &testHEDs[i]
  151. if v.H == h {
  152. return v
  153. }
  154. }
  155. testHEDs = append(testHEDs, testHED{h, NewEncoder(nil, h), NewDecoder(nil, h)})
  156. return &testHEDs[len(testHEDs)-1]
  157. }
  158. func testReinit() {
  159. testOnce = sync.Once{}
  160. testHEDs = nil
  161. }
  162. func testInitAll() {
  163. // only parse it once.
  164. if !flag.Parsed() {
  165. flag.Parse()
  166. }
  167. for _, f := range testPreInitFns {
  168. f()
  169. }
  170. for _, f := range testPostInitFns {
  171. f()
  172. }
  173. }
  174. func sTestCodecEncode(ts interface{}, bsIn []byte, fn func([]byte) *bytes.Buffer,
  175. h Handle, bh *BasicHandle) (bs []byte, err error) {
  176. // bs = make([]byte, 0, approxSize)
  177. var e *Encoder
  178. var buf *bytes.Buffer
  179. if testUseReset {
  180. e = testHEDGet(h).E
  181. } else {
  182. e = NewEncoder(nil, h)
  183. }
  184. var oldWriteBufferSize int
  185. if testUseIoEncDec >= 0 {
  186. buf = fn(bsIn)
  187. // set the encode options for using a buffer
  188. oldWriteBufferSize = bh.WriterBufferSize
  189. bh.WriterBufferSize = testUseIoEncDec
  190. if testUseIoWrapper {
  191. e.Reset(ioWriterWrapper{buf})
  192. } else {
  193. e.Reset(buf)
  194. }
  195. } else {
  196. bs = bsIn
  197. e.ResetBytes(&bs)
  198. }
  199. if testUseMust {
  200. e.MustEncode(ts)
  201. } else {
  202. err = e.Encode(ts)
  203. }
  204. if testUseIoEncDec >= 0 {
  205. bs = buf.Bytes()
  206. bh.WriterBufferSize = oldWriteBufferSize
  207. }
  208. if !testUseReset {
  209. e.Release()
  210. }
  211. return
  212. }
  213. func sTestCodecDecode(bs []byte, ts interface{}, h Handle, bh *BasicHandle) (err error) {
  214. var d *Decoder
  215. // var buf *bytes.Reader
  216. if testUseReset {
  217. d = testHEDGet(h).D
  218. } else {
  219. d = NewDecoder(nil, h)
  220. }
  221. var oldReadBufferSize int
  222. if testUseIoEncDec >= 0 {
  223. buf := bytes.NewReader(bs)
  224. oldReadBufferSize = bh.ReaderBufferSize
  225. bh.ReaderBufferSize = testUseIoEncDec
  226. if testUseIoWrapper {
  227. d.Reset(ioReaderWrapper{buf})
  228. } else {
  229. d.Reset(buf)
  230. }
  231. } else {
  232. d.ResetBytes(bs)
  233. }
  234. if testUseMust {
  235. d.MustDecode(ts)
  236. } else {
  237. err = d.Decode(ts)
  238. }
  239. if testUseIoEncDec >= 0 {
  240. bh.ReaderBufferSize = oldReadBufferSize
  241. }
  242. if !testUseReset {
  243. d.Release()
  244. }
  245. return
  246. }
  247. // --- functions below are used by both benchmarks and tests
  248. // log message only when testVerbose = true (ie go test ... -- -tv).
  249. //
  250. // These are for intormational messages that do not necessarily
  251. // help with diagnosing a failure, or which are too large.
  252. func logTv(x interface{}, format string, args ...interface{}) {
  253. if testVerbose {
  254. logT(x, format, args...)
  255. }
  256. }
  257. // logT logs messages when running as go test -v
  258. //
  259. // Use it for diagnostics messages that help diagnost failure,
  260. // and when the output is not too long ie shorter than like 100 characters.
  261. //
  262. // In general, any logT followed by failT should call this.
  263. func logT(x interface{}, format string, args ...interface{}) {
  264. if x == nil {
  265. if len(format) == 0 || format[len(format)-1] != '\n' {
  266. format = format + "\n"
  267. }
  268. fmt.Printf(format, args...)
  269. return
  270. }
  271. switch t := x.(type) {
  272. case *testing.T:
  273. // TODO: use conditional build files containing logT and failT
  274. // t.Helper() // only available from go 1.9
  275. t.Logf(format, args...)
  276. case *testing.B:
  277. // t.Helper() // only available from go 1.9
  278. t.Logf(format, args...)
  279. }
  280. }
  281. func failT(x interface{}, args ...interface{}) {
  282. // switch t := x.(type) {
  283. // case *testing.T:
  284. // t.Helper() // only available from go 1.9
  285. // case *testing.B:
  286. // t.Helper()
  287. // }
  288. if len(args) > 0 {
  289. if format, ok := args[0].(string); ok {
  290. logT(x, format, args[1:]...)
  291. } else if len(args) == 1 {
  292. logT(x, "%v", args[0])
  293. } else {
  294. logT(x, "%v", args)
  295. }
  296. }
  297. if t, ok := x.(interface{ FailNow() }); ok {
  298. t.FailNow()
  299. }
  300. }
  301. // --- functions below are used only by benchmarks alone
  302. func fnBenchmarkByteBuf(bsIn []byte) (buf *bytes.Buffer) {
  303. // var buf bytes.Buffer
  304. // buf.Grow(approxSize)
  305. buf = bytes.NewBuffer(bsIn)
  306. buf.Truncate(0)
  307. return
  308. }
  309. // func benchFnCodecEncode(ts interface{}, bsIn []byte, h Handle) (bs []byte, err error) {
  310. // return testCodecEncode(ts, bsIn, fnBenchmarkByteBuf, h)
  311. // }
  312. // func benchFnCodecDecode(bs []byte, ts interface{}, h Handle) (err error) {
  313. // return testCodecDecode(bs, ts, h)
  314. // }