0

I am writing a program that reads input from a file, parses the text in that file, and then prints out text to stdout. I have the expected output in a text file. How would I go about using the testing package to compare my program's output to the expected output saved in a text file?

Let's say my code is the following:

package main
import (
    "fmt"
    "log"
    "os"
    "bufio"
    "strings"
)

func main() {
    if len(os.Args) > 1 {
        file, err := os.Open(os.Args[1])
        if err != nil {
            log.Fatal(err)
        }
        defer file.Close()

        scanner := bufio.NewScanner(file)
        for scanner.Scan() {
            fmt.Println(strings.ToUpper(scanner.Text()))
        }
    } else {
        fmt.Println("Need input file as argument")
        os.Exit(1)
    }
}

This is simply taking each line of the input text file, capitalizing all letters, and then printing each line.

In my input file, I have:

hello, wOrlD!
foo
BAR

And in my expected output file, I have:

HELLO, WORLD!
FOO
BAR

What is the best way to use the testing package to compare my output to the expected output file?

Thanks!

Spitfire
  • 11
  • 3
  • If you have only 3 rows of test text - you can stick with basic Examples. Look at: https://golang.org/pkg/testing/#pkg-examples If you really need to compare by file content - I would try to exploite https://golang.org/src/testing/example.go. – Alex Yu Apr 02 '17 at 18:13
  • @Flimzy I've read through that question trying to gleam useful information, and it doesn't seem to fit my question. An idea that I have is that I could write a function that accepts any input file as a function parameter (maybe, just an idea) and test against a file containing expected output. Maybe what I'm looking for is that testing function that takes an input file as a parameter, then passes the output of that function to a buffer, and then finally compares that buffer's contents to the expected output file. – Spitfire Apr 02 '17 at 19:35
  • 1
    I'm not sure what the problem is. It should be easy to write a test function and capture its output (as described in the linked question/answers). Then you can compare it to whatever you want, however you want. What specific questions remain? – Jonathan Hall Apr 02 '17 at 20:17
  • you need to use testing package. https://golang.org/pkg/testing/ 1) Create a file in package main. 2) Create a function func TestOutPut(*testing.T) 3) write logic 4) run with go test myfile_test.go – reticentroot Apr 02 '17 at 20:40
  • Yep I think I'm grasping my head around the duplicate mentioned and how I can use it. I'll close/delete this question since it doesn't provide any new information. – Spitfire Apr 03 '17 at 00:08

0 Answers0