lundi 3 juin 2019

Reading stdout from an exec'd process from within a golang test

I have a main.go that I would like to read its standard output from when I exec it inside one of my tests. In my app_test.go I have:

func TestShutdown(t *testing.T) {
timer := time.NewTimer(4 * time.Second)
cmd := exec.Command("go", "run", "cmd/testing/main.go")
stdout, err := cmd.StdoutPipe()
if err != nil {
    log.Fatal(err)
}
err = cmd.Start()
if err != nil {
    t.Logf("Error starting the go file: %s", err)
}
<-timer.C

buf := new(bytes.Buffer)
buf.ReadFrom(stdout)
s := buf.String()
t.Logf("out: %s", s)

}

My main.go simply is:

package main

import (
    "fmt"
)

func main() {
    fmt.Println("hello world")
}

When I run the test it only prints: out: and not the expected hello world. I have attempted to read using cmd.Stdout as well cmd.Output() with the same result. Do I need to use exec.Wait()? I cannot figure out why the standard output is not being picked up in my test. Perhaps in tests you cannot read from standard out?

Aucun commentaire:

Enregistrer un commentaire