stdinから行を読み込んで単純にstdoutに返す単純なアプリケーションがあるとします。例:stdinに書き込むGoテストを書くにはどうすればよいですか?
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("> ")
bytes, _, err := reader.ReadLine()
if err == io.EOF {
os.Exit(0)
}
fmt.Println(string(bytes))
}
}
stdinに書き込んだ出力を入力と比較するテストケースを作成したいとします。例えば:私は明らかにここに間違った何かをやっている
=== RUN TestInput
--- FAIL: TestInput (3.32s)
echo_test.go:25: Wanted: abc
, Got: --- FAIL: TestInput (3.32s)
FAIL
exit status 1
:
package main
import (
"bufio"
"io"
"os"
"os/exec"
"testing"
)
func TestInput(t *testing.T) {
subproc := exec.Command(os.Args[0])
stdin, _ := subproc.StdinPipe()
stdout, _ := subproc.StdoutPipe()
defer stdin.Close()
input := "abc\n"
subproc.Start()
io.WriteString(stdin, input)
reader := bufio.NewReader(stdout)
bytes, _, _ := reader.ReadLine()
output := string(bytes)
if input != output {
t.Errorf("Wanted: %v, Got: %v", input, output)
}
subproc.Wait()
}
がgo test -v
を実行すると、次の私に与えます。このタイプのコードをテストするにはどうすればよいですか?代わりにstdin
とstdout
とmain
ですべてを行うことの
出力から ">"を削除し、TestInput関数を使用しました。 --- FAILを === RUN TestInput :私はこのような何かを見て約100繰り返し失敗のシリーズを取得TestInput(5.17s) \t echo_test.go:36:募集:ABC \t \t、ガット: --- FAIL:TestInput(5.15s) \t \t \t echo_test.go:36:募集:ABC \t \t \t \t、ガット:--- FAIL:TestInput(5.13s) \t \t \t \t \t echo_test.go :36:募集:abc ...など。 –
">"を削除するとうまく動作します。実行するための適切なコマンドを提供しましたか? –
コマンドをos.Args [0]に変更しました。 –