I am trying to do functional testing of a cli app similar to this way.
As the command asks a few input on command prompt, I am putting them in a file and setting it as os.Stdin.
cmd := exec.Command(path.Join(dir, binaryName), "myArg")
tmpfile := setStdin("TheMasterPassword
SecondAnswer
12121212
")
cmd.Stdin = tmpfile
output, err := cmd.CombinedOutput()
The setStdin
just creates a tmpFile, write the string in file and returns the *os.File
.
Now, I am expecting TheMasterPassword
to be first input, and it's working. But for the second input always getting Critical Error: EOF
.
The function I am using for asking and getting user input this :
func Ask(question string, minLen int) string {
reader := bufio.NewReader(os.Stdin)
for {
fmt.Printf("%s: ", question)
response, err := reader.ReadString('
')
ExitIfError(err)
if len(response) >= minLen {
return strings.TrimSpace(response)
} else {
fmt.Printf("Provide at least %d character.
", minLen)
}
}
}
Can you please help me to find out what's going wrong? Thanks a lot!
Adding setStdin
as requested
func setStdin(userInput string) *os.File {
tmpfile, err := ioutil.TempFile("", "test_stdin_")
util.ExitIfError(err)
_, err = tmpfile.Write([]byte(userInput))
util.ExitIfError(err)
_, err = tmpfile.Seek(0, 0)
util.ExitIfError(err)
return tmpfile
}