Checking a function line by line, "does it count right?", "does it skip blanks?", misses the mistakes that matter to a reader of the output: a missing line ending, an extra blank line, the summary in the wrong place. A transcript check catches all of those at once. It feeds known input to a function and compares the complete output with the exact text you expect, line endings included.
That only works when the function doesn't talk to os.Stdin and os.Stdout itself. With a reader and a writer passed in, a check supplies a strings.Reader and captures the output in a strings.Builder.
Predict and run
What output does echoLine write to the builder?
package main
import (
"bufio"
"fmt"
"io"
"strings"
)
func echoLine(r io.Reader, w io.Writer) error {
scanner := bufio.NewScanner(r)
if scanner.Scan() {
_, err := fmt.Fprintln(w, "Task:", scanner.Text())
if err != nil {
return err
}
}
return scanner.Err()
}
func main() {
var out strings.Builder
if err := echoLine(strings.NewReader("Read"), &out); err != nil {
panic(err)
}
fmt.Printf("%q\n", out.String())
}Check your prediction
"Task: Read\n"Remove the input entirely and compare the transcript.
Many transcripts in one table
One transcript proves one case. A table of them, input on one side and the exact expected output on the other, proves several, and adding a case is one line. When a case fails, print both strings with %q, so a missing \n or a stray space is visible:
package main
import (
"bufio"
"fmt"
"io"
"strings"
)
func tally(r io.Reader, w io.Writer) error {
scanner := bufio.NewScanner(r)
count := 0
for scanner.Scan() {
title := strings.TrimSpace(scanner.Text())
if title == "" {
continue
}
count++
if _, err := fmt.Fprintln(w, "Task:", title); err != nil {
return err
}
}
if err := scanner.Err(); err != nil {
return err
}
_, err := fmt.Fprintln(w, "Tasks:", count)
return err
}
func main() {
cases := []struct {
name, input, want string
}{
{"two titles", "Read\nDraft\n", "Task: Read\nTask: Draft\nTasks: 2\n"},
{"blank line", "Read\n\n \n", "Task: Read\nTasks: 1\n"},
{"empty", "", "Tasks: 0\n"},
}
for _, c := range cases {
var out strings.Builder
if err := tally(strings.NewReader(c.input), &out); err != nil {
panic(c.name + ": " + err.Error())
}
if got := out.String(); got != c.want {
panic(fmt.Sprintf("%s: got %q, want %q", c.name, got, c.want))
}
}
fmt.Println(len(cases), "transcripts passed")
}3 transcripts passedChange count++ to count += 2 and run it. The program stops with panic: two titles: got "Task: Read\nTask: Draft\nTasks: 4\n", want "Task: Read\nTask: Draft\nTasks: 2\n", naming the case and showing both transcripts. Restore the line.
Practice
Your turn
The starter has shout, which writes each nonblank line in capitals followed by !, and then Done. Write a table of three transcript cases for it, then run them all: two lines with a blank line between them, a single line with spaces around it, and empty input. Work out each expected transcript by hand from the description, not by running shout first. When all three pass, print:
3 transcripts passedpackage main
import (
"bufio"
"fmt"
"io"
"strings"
)
func shout(r io.Reader, w io.Writer) error {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
if _, err := fmt.Fprintln(w, strings.ToUpper(line)+"!"); err != nil {
return err
}
}
if err := scanner.Err(); err != nil {
return err
}
_, err := fmt.Fprintln(w, "Done")
return err
}
func main() {
// Write the table and the loop here.
}Hint 1: the idea
Each row holds a name, an input and the full expected output as one string, with a \n after every line shout writes, including Done. The loop runs shout with a fresh reader and builder per row and compares the whole string.
Hint 2: a first step
Write the empty-input row first: its expected transcript is just "Done\n". Get that one passing, then add the other two rows.
Worked solution
package main
import (
"bufio"
"fmt"
"io"
"strings"
)
func shout(r io.Reader, w io.Writer) error {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
if _, err := fmt.Fprintln(w, strings.ToUpper(line)+"!"); err != nil {
return err
}
}
if err := scanner.Err(); err != nil {
return err
}
_, err := fmt.Fprintln(w, "Done")
return err
}
func main() {
cases := []struct {
name, input, want string
}{
{"blank between", "read\n\ndraft", "READ!\nDRAFT!\nDone\n"},
{"spaces", " call sam \n", "CALL SAM!\nDone\n"},
{"empty", "", "Done\n"},
}
for _, c := range cases {
var out strings.Builder
if err := shout(strings.NewReader(c.input), &out); err != nil {
panic(c.name + ": " + err.Error())
}
if got := out.String(); got != c.want {
panic(fmt.Sprintf("%s: got %q, want %q", c.name, got, c.want))
}
}
fmt.Println(len(cases), "transcripts passed")
}3 transcripts passedWriting the expected text from the description, before running the code, is what makes this a check: a transcript copied from the program's own output would agree with any bug it had. The spaces case proves the trimming happens before the ! is added, otherwise you would see CALL SAM !.
Going further: the same check as a Go test (optional)
The browser runs one main package, so this course's checks are programs that panic on a mismatch. On your own computer, Go has a built-in way to write the same checks: the testing package and the go test command. The Day 7 download uses it, so it's worth seeing once now. This section needs Go installed locally; the last Day 7 lesson of the beginner course shows how to set it up.
- Make an empty folder, open a terminal in it, and run
go mod init practice. That creates ago.modfile. - Save
tallyand a smallmaininmain.go, withpackage mainat the top. Themaincan just calltally(os.Stdin, os.Stdout). - Save this as
tally_test.goin the same folder. Any file whose name ends in_test.gois only compiled bygo test, never bygo run.
package main
import (
"strings"
"testing"
)
func TestTally(t *testing.T) {
cases := []struct {
name, input, want string
}{
{"two titles", "Read\nDraft\n", "Task: Read\nTask: Draft\nTasks: 2\n"},
{"blank line", "Read\n\n \n", "Task: Read\nTasks: 1\n"},
{"empty", "", "Tasks: 0\n"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
var out strings.Builder
if err := tally(strings.NewReader(c.input), &out); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got := out.String(); got != c.want {
t.Errorf("got %q, want %q", got, c.want)
}
})
}
}- Run
go test. It printsPASSand then a line starting withok.
Compare it with the table above. A test is a function whose name starts with Test and that takes a *testing.T. t.Run gives each row its own named subtest. Instead of panic, t.Errorf reports a failure and carries on with the other rows, so one run shows every broken case. t.Fatalf reports and stops the current subtest, for errors that make the rest of the check meaningless.
Two more commands are worth trying. go test -v lists every subtest with PASS or FAIL. go test -run TestTally/empty runs only the matching subtest, which is handy while you fix one case. Then break tally with count += 2 again: go test prints a --- FAIL line for each failing row, with the got and want transcripts, and ends with FAIL.
Completion is saved in this browser only. It does not measure mastery.