user3486527
user3486527

Reputation: 125

Go Command Line Input Testing

is there a better way that might be recommend for testing input, than below? Should the test use fmt.Println("6 6 4") to better simulate the input from command line?

main.go:

package main

import (
    "fmt"
    "math"
)

func input_calc(n, m, a float64) uint64 {

    fmt.Scanln(&n, &m, &a)

    a_in_n_ceil := uint64(math.Ceil(n / a))

    a_in_m_ceil := uint64(math.Ceil(m / a))

    a_in_n_and_m := a_in_n_ceil * a_in_m_ceil

    return a_in_n_and_m

}

func main() {

    fmt.Println(input_calc(0, 0, 0))

}

main_test.go:

package main

import "testing"

func TestMain(t *testing.T) {

    answer := input_calc(6, 6, 4)
    if answer != 4 {
        t.Log("error should be 4, but got", answer)
        t.Fail()
    }
}

Upvotes: 3

Views: 808

Answers (1)

rocka2q
rocka2q

Reputation: 2804

To test input, use the io.Reader interface. For your example,

main.go

package main  

import (
    "fmt"
    "io"
    "math"
    "os"
)

func input_calc(rdr io.Reader) (uint64, error) {
    var n, m, a float64
    _, err := fmt.Fscanln(rdr, &n, &m, &a)
    if err != nil {
        return 0, err
    }

    a_in_n_ceil := uint64(math.Ceil(n / a))
    a_in_m_ceil := uint64(math.Ceil(m / a))
    a_in_n_and_m := a_in_n_ceil * a_in_m_ceil

    return a_in_n_and_m, nil
}

func main() {
    rdr := os.Stdin
    answer, err := input_calc(rdr)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(answer)
}

main_test.go

package main

import (
    "strings"
    "testing"
)

func TestInputCalc(t *testing.T) {
    input := "6 6 4\n"
    rdr := strings.NewReader(input)
    answer, err := input_calc(rdr)
    if err != nil {
        t.Error(err)
    }
    if answer != 4 {
        t.Error("error should be 4, but got", answer)
    }
}

The statements

input := "6 6 4\n"

and

input := fmt.Sprintln(6, 6, 4)

are equivalent.

Upvotes: 3

Related Questions