Why fmt.Scan doesn't wait input while using in testing?

2,293 views
Skip to first unread message

Googol Lee

unread,
Feb 17, 2012, 11:07:34 PM2/17/12
to golang-nuts
I try to use fmt.Scan to get user input when running testing. Code
like below:

package sample

import (
"testing"
"fmt"
)

func TestSomething(t *testing.T) {
var input string
fmt.Scan(&input)
fmt.Println(input)
}

But fmt.Scan doesn't work. It return empty string immediately after
call. Is there a way to get user input when running testing?

Thanks.

Dustin

unread,
Feb 17, 2012, 11:12:53 PM2/17/12
to golan...@googlegroups.com

On Friday, February 17, 2012 8:07:34 PM UTC-8, Googol Lee wrote:
func TestSomething(t *testing.T) {
  var input string
  fmt.Scan(&input)
  fmt.Println(input)
}

But fmt.Scan doesn't work. It return empty string immediately after
call. Is there a way to get user input when running testing?

  Tests run with /dev/null on console.  You should really check the results of those calls.  :)

Evan Shaw

unread,
Feb 17, 2012, 11:16:48 PM2/17/12
to Googol Lee, golang-nuts
fmt.Scan reads from os.Stdin, which is set to /dev/null when testing.
Tests should be automated and self-contained anyway, so you don't want
to read from stdin.

Either use an external file, a bytes.Buffer, or a strings.Reader and
call scan.Fscan if you want to scan something.

- Evan

Kyle Lemons

unread,
Feb 20, 2012, 4:58:11 AM2/20/12
to Evan Shaw, Googol Lee, golang-nuts
You should also check error returns when scanning.

Googol Lee

unread,
Feb 20, 2012, 5:43:37 AM2/20/12
to golang-nuts
Got it. Thanks :)

ashinmi...@gmail.com

unread,
Mar 28, 2020, 1:29:42 AM3/28/20
to golang-nuts
Hello Evan, where is this `set to /dev/null` operating in the source code of golang? I tried to explore it, but I didn't find it

在 2012年2月18日星期六 UTC+8下午12:16:48,Evan Shaw写道:

Ian Lance Taylor

unread,
Mar 28, 2020, 1:58:24 AM3/28/20
to ashinmi...@gmail.com, golang-nuts
On Fri, Mar 27, 2020 at 10:29 PM <ashinmi...@gmail.com> wrote:
>
> Hello Evan, where is this `set to /dev/null` operating in the source code of golang? I tried to explore it, but I didn't find it

You are replying to a message from 2012. Many things have changed since then.

Ian


> 在 2012年2月18日星期六 UTC+8下午12:16:48,Evan Shaw写道:
>>
>> fmt.Scan reads from os.Stdin, which is set to /dev/null when testing.
>> Tests should be automated and self-contained anyway, so you don't want
>> to read from stdin.
>>
>> Either use an external file, a bytes.Buffer, or a strings.Reader and
>> call scan.Fscan if you want to scan something.
>>
>> - Evan
>
> --
> You received this message because you are subscribed to the Google Groups "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/fbd04f6d-4c78-4b61-a37b-3c3a10171e36%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages