I'm connecting a pipe to my stdout in golang as follows for the purpose of testing (I stripped out the error handling codes):
stdout := os.Stdout
defer func() {
os.Stdout = stdout
}()
r, w, _ = os.Pipe()
os.Stdout = w
var buf bytes.Buffer
fmt.Print(testOut)
w.Close()
io.Copy(&buf, r)
assert.Equal(t, testOut, buf.String())
I want to basically do something similar with stdin as well. Something like this:
stdin := os.Stdin
defer func() {
os.Stdin = stdin
}()
r, w, _ = os.Pipe()
os.Stdin = r
var in string
w.WriteString(testIn)
// w.Close()
fmt.Scan(&in)
assert.Equal(t, testIn, in)
But, I cannot get this working. If I don't close w, fmt.Scan(&in) never returns. If I close w, I get file already closed error.
Any I idea how to get this working?