How to write tests against user input in Go

How can I test user input from fmt.Scan / Scanf / Scanln?

For example, how can I verify that the function input will take "4 5 \ n" and "1 2 3 4 \ n" from STDIN and returns n == 5 and array == [1, 2, 3, 4].

package main import ( "fmt" ) // input gets an array from the user. func input() (m int, array []int) { fmt.Print("Enter the size of the array, n, and the difference, m: ") var n int _, err := fmt.Scanf("%d %d", &n, &m) if err != nil { panic(err) } fmt.Print("Enter the array as a space seperated string: ") array = make([]int, n) for i := 0; i < n; i++ { _, _ = fmt.Scan(&array[i]) } return m, array } func main() { m, array := input() fmt.Println(m, array) } 
+6
source share
2 answers

Here is a very rough draft illustrating the principle.

program.go

 package main import ( "fmt" "os" ) // input gets an array from the user. func input(in *os.File) (m int, array []int) { if in == nil { in = os.Stdin } fmt.Print("Enter the size of the array, n, and the difference, m: ") var n int _, err := fmt.Fscanf(in, "%d %d", &n, &m) if err != nil { panic(err) } fmt.Print("Enter the array as a space seperated string: ") array = make([]int, n) for i := 0; i < n; i++ { _, _ = fmt.Fscan(in, &array[i]) } return m, array } func main() { m, array := input(nil) fmt.Println(m, array) } 

program_test.go

 package main import ( "fmt" "io" "io/ioutil" "os" "testing" ) func TestInput(t *testing.T) { var ( n, m int array []int ) in, err := ioutil.TempFile("", "") if err != nil { t.Fatal(err) } defer in.Close() _, err = io.WriteString(in, "4 5\n"+"1 2 3 4\n") if err != nil { t.Fatal(err) } _, err = in.Seek(0, os.SEEK_SET) if err != nil { t.Fatal(err) } n, array = input(in) if n != 5 || fmt.Sprintf("%v", array) != fmt.Sprintf("%v", []int{1, 2, 3, 4}) { t.Error("unexpected results:", n, m, array) } } 

Output:

 $ go test ok command-line-arguments 0.010s 
+10
source

You can not. At least not so easy that it was worth the effort.

-5
source

Source: https://habr.com/ru/post/948649/


All Articles