dougongyou7364 2015-08-08 12:17
浏览 44
已采纳

Readline在Go测试案例中失败

I'm experimenting getting keyboard input in a test case, basically I followed this example,

https://www.socketloop.com/tutorials/golang-read-input-from-console-line

and in my unit test case, it always result in error of "EOF" without giving me a chance to type in from keyboard.

Is there any special in Go unit test environment? Or I should look into another better option?

My code looks like,

func (o *Player) consoleReadLn() (line string) {
    consoleReader := bufio.NewReader(os.Stdin)
    line, err := consoleReader.ReadString('
')
    if err != nil {
        panic(err.Error())   // it just panic: EOF
    }
    return
}
  • 写回答

1条回答 默认 最新

  • doushoubu5360 2015-08-08 14:57
    关注

    Firstly, your code should be corrected to:

    import "testing/iotest"
    
    func (o *Player) consoleReadLn() string {
        consoleReader := bufio.NewReader(os.Stdin)
        s := "" 
        for {
            s1, err := consoleReader.ReadString('
    ')
            if err == io.EOF {
                break
            }
            if err != nil && err != iotest.ErrTimeout {
                panic("GetLines: " + err.Error())
            }
            s += s1
        }
        return s
    }
    

    Because you expect using as delimiter of a line of string, so it will return the data with EOF which is in Unix OS, see godoc bufio#Reader.ReadString:

    ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter. If ReadString encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadString returns err != nil if and only if the returned data does not end in delim. For simple uses, a Scanner may be more convenient.

    However, I suggest reading this answer Read from initial stdin in GO?

    Secondly, it is hard to test STDIN in unit test context like go test. I found this mail saying:

    the new go test runs tests with standard input connected to /dev/null.

    So I think it is hard to test os.Stdin via go test directly, for example, the following code confirmed it doesn't read /dev/stdin at all when running command echo this is stdin | go test ./:

    import "io/ioutil"
    import "testing"
    import "fmt"
    
    func TestSTDIN(t *testing.T) {
        bytes, err := ioutil.ReadAll(os.Stdin)
    
        if err != nil {
            t.Fatal(err)
        }
    
        fmt.Println(string(bytes))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。