我如何编写写入标准输入的Go测试? [英] How can I write a Go test that writes to stdin?
问题描述
包主
导入(
bufio
fmt
io
os
)
func main(){
reader:= bufio.NewReader(os.Stdin)
for {
fmt.Print(>)
字节,_,err:= reader.ReadLine()
if err == io.EOF {
os.Exit(0)
}
fmt.Println(string(bytes))
}
}
我想编写一个测试用例,写入stdin,然后将输出与输入进行比较。例如:
包主
导入(
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()
输入:=abc\\\
subproc.Start()
io.WriteString(stdin,input)
读取器:= bufio.NewReader(stdout)
字节,_,_:= reader.ReadLine()
输出:=字符串(字节)
如果输入!=输出{
t.Errorf(Wanted:%v,Got:%v,input,output)
}
subproc.Wait()
}
运行 go test -v
给了我以下信息:
=== RUN TestInput
--- FAIL:TestInput(3.32s)
echo_test.go:25:Wanted:abc
,得到:--- FAIL:TestInput(3.32s)
FAIL
exit statu s 1
我在这里显然做了一些不正确的事情。我应该如何去测试这种类型的代码?
这是一个写stdin并从stdout读取的例子。请注意,它不起作用,因为输出中首先包含>。
func TestInput(t * testing.T){
subproc := exec.Command(yourCmd)
输入:=abc\\\
subproc.Stdin = strings.NewReader(输入)
输出,_:= subproc.Output( )
if input!= string(output){
t.Errorf(Wanted:%v,Got:%v,input,string(output))
}
subproc.Wait()
}
Say that I have a simple application that reads lines from stdin and simply echoes it back to stdout. For example:
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))
}
}
I would like to write a test case that writes to stdin and then compares the output to the input. For example:
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()
}
Running go test -v
gives me the following:
=== RUN TestInput
--- FAIL: TestInput (3.32s)
echo_test.go:25: Wanted: abc
, Got: --- FAIL: TestInput (3.32s)
FAIL
exit status 1
I'm obviously doing something incorrect here. How should I go about testing this type of code?
Here is an example that writes to stdin and reads from stdout. Note that it does not work because the output contains "> " at first. Still, you can modify it to suit your needs.
func TestInput(t *testing.T) {
subproc := exec.Command("yourCmd")
input := "abc\n"
subproc.Stdin = strings.NewReader(input)
output, _ := subproc.Output()
if input != string(output) {
t.Errorf("Wanted: %v, Got: %v", input, string(output))
}
subproc.Wait()
}
这篇关于我如何编写写入标准输入的Go测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!