Thursday, 15 August 2013

testing - How to test a function's output (stdout/stderr) in Go unit tests -



testing - How to test a function's output (stdout/stderr) in Go unit tests -

i have simple function want test:

func (t *thing) print(min_verbosity int, message string) { if t.verbosity >= minv { fmt.print(message) } }

but how can test function sends standard output? test::output want in perl. know write own boilerplate same in go (as described here):

orig = os.stdout r,w,_ = os.pipe() thing.print("some message") var buf bytes.buffer io.copy(&buf, r) w.close() os.stdout = orig if(buf.string() != "some message") { t.error("failure!") }

but that's lot of work every single test. i'm hoping there's more standard way, or perhaps abstraction library handle this.

you can 1 of 2 things. first utilize examples.

the bundle runs , verifies illustration code. illustration functions may include final line comment begins "output:" , compared standard output of function when tests run. (the comparing ignores leading , trailing space.) these examples of example:

func examplehello() { fmt.println("hello") // output: hello }

the sec (and more appropriate, imo) utilize false functions io. in code do:

var myprint = fmt.print func (t *thing) print(min_verbosity int, message string) { if t.verbosity >= minv { myprint(message) // n.b. } }

and in tests:

func init() { myprint = fakeprint // fakeprint records it's supposed print. } func test...

another alternative utilize fmt.fprintf io.writer os.stdout in production code, may bytes.buffer in tests.

testing go stdout

No comments:

Post a Comment