The framework in the testing package prints its output to os.Stdout. A caller might want to redirect this elsewhere, or alter it - e.g. to write to a file as well which another system might parse. This can be achieved by replacing os.Stdout, but this is overly difficult since it's a File (#13473 suggests this is known to be undesirable but can't change before v2), requiring e.g. os.Pipe and associated management + overhead. However, testing only needs an io.Writer rather than the full os.File type.
I propose that we add a new function to the testing package allowing a caller to set the stream that is output to, along the lines of:
// OutputStream sets the stream to which testing output is written.
// It must be called before any tests, benchmarks or fuzz suites are run, and should not be called while they are running.
// If not called, the default is os.Stdout
func OutputStream(w io.Writer) {
outputStream = w
}
var outputStream = os.Stdout
I might be being a little defensive about not exposing the variable directly, but it feels like the function is a clearer documentation point and helps future-proof the interface a bit.
The text was updated successfully, but these errors were encountered:
I think that's a slightly different thing. go test guarantees that the subprocess gets os.Stdout pointing to the original terminal. If that subprocess chooses to do something different for output (say in a TestMain), that's up to it - today it can open a File and reassign os.Stdout to that if it wants to. This would just provide a (much) nicer interface for tests wanting to opt into that behaviour.
ianlancetaylor
changed the title
proposal: testing: Add function to set output writer
proposal: testing: add function to set output writer
Apr 5, 2023
The framework in the
testing
package prints its output toos.Stdout
. A caller might want to redirect this elsewhere, or alter it - e.g. to write to a file as well which another system might parse. This can be achieved by replacingos.Stdout
, but this is overly difficult since it's aFile
(#13473 suggests this is known to be undesirable but can't change before v2), requiring e.g.os.Pipe
and associated management + overhead. However,testing
only needs anio.Writer
rather than the fullos.File
type.I propose that we add a new function to the
testing
package allowing a caller to set the stream that is output to, along the lines of:I might be being a little defensive about not exposing the variable directly, but it feels like the function is a clearer documentation point and helps future-proof the interface a bit.
The text was updated successfully, but these errors were encountered: