Code that handles failures is the code least often run. Disks rarely fill and connections rarely drop while you are testing, so the error paths can be wrong for months before anyone notices. The intermediate course used a writer that always fails. Today you will make failures happen at a chosen moment, and then turn the idea around: break the code on purpose, to find out whether the checks notice.
Because io.Writer and io.Reader are small interfaces, a test can supply its own implementation that fails exactly when you want, with no files or network involved.
Predict and run
failAfter accepts a fixed number of writes, then fails. writeLines stops at the first error. What reaches the destination, and what error comes back?
package main
import (
"errors"
"fmt"
"io"
"strings"
)
var errFull = errors.New("disk full")
type failAfter struct {
writes int
out strings.Builder
}
func (f *failAfter) Write(p []byte) (int, error) {
if f.writes == 0 {
return 0, errFull
}
f.writes--
return f.out.Write(p)
}
func writeLines(w io.Writer, lines []string) error {
for i, line := range lines {
if _, err := fmt.Fprintln(w, line); err != nil {
return fmt.Errorf("line %d: %w", i+1, err)
}
}
return nil
}
func main() {
w := &failAfter{writes: 2}
err := writeLines(w, []string{"Stocked tent: 5", "Reserved A1", "Cancelled A1"})
fmt.Printf("%q\n", w.out.String())
fmt.Println(err, errors.Is(err, errFull))
}Check your prediction
"Stocked tent: 5\nReserved A1\n"
line 3: disk full trueThe first two lines arrived, the third failed, and the error says which line it was while still matching errFull. Set writes to 0, then to 3, and predict each result. With 3 the function succeeds, which checks that a writer that is merely close to failing does not trigger the error path.
Failures that arrive late
A bufio.Writer changes when a failure appears. Its writes go into memory, so Fprintln succeeds and the destination's error only surfaces at Flush, or when the buffer fills. That is why the project's run reports the error from a deferred Flush, as on Day 2. A failing reader is just as easy to build. testing/iotest provides ready-made ones locally, and this one returns some data and then an error.
package main
import (
"bufio"
"errors"
"fmt"
"io"
"strings"
)
var errDropped = errors.New("connection dropped")
type failingReader struct {
data io.Reader
}
func (r *failingReader) Read(p []byte) (int, error) {
n, err := r.data.Read(p)
if err == io.EOF {
return n, errDropped
}
return n, err
}
func main() {
scanner := bufio.NewScanner(&failingReader{data: strings.NewReader("stock tent 5\norder A1 tent:2\n")})
count := 0
for scanner.Scan() {
count++
}
fmt.Println(count, scanner.Err())
}2 connection droppedBoth complete lines were read before the failure, and scanner.Err() reports it instead of treating it as the end of the input. Code that forgets to check scanner.Err() would quietly accept a truncated input as if it were whole, which is why every reading loop in this course checks it.
Mutation testing
Injected failures test the code. Mutations test the checks. A mutation is a small, plausible mistake made on purpose: change > to >=, delete one line, skip one check. Then run the checks. If they still pass, they cannot tell the correct code from the broken one, and a real slip of the same kind would ship. The course's tooling runs nine mutations against the project, and both go test and the browser check must fail for every one. Among them:
- replace the staged copy with the real map, so a failed order reserves its first lines
- stop sorting order lines, so a reordered retry looks like a conflict
- skip the capacity check when cancelling
- remove the final
ctx.Err()check in the worker pool - ignore the error from the deferred
Flush
On Day 7 you will run the project's checks and break one of these yourself.
A check that never failed has not been tested
After writing a check, break the code it protects once and watch it fail. It takes a minute and it is the only evidence that the check can see what it claims to protect.
Practice
Your turn
Write copyLines(r io.Reader, w io.Writer) (int, error), which copies non-blank lines from r to w and returns how many it wrote. Return read errors wrapped with read: and write errors wrapped with write:. Check it with a normal reader and a strings.Builder, with a writer that fails on the second write, and with the failing reader from the lesson.
The output should be:
3 <nil>
1 write: disk full
3 read: connection droppedpackage main
func main() {
// Write copyLines and the failing reader and writer, then check three cases.
}Hint 1: the idea
There are two error paths, and each needs its own injected failure to prove it works. The successful case proves the count is right.
Hint 2: a first step
Scan with a bufio.Scanner, skip lines that are blank after strings.TrimSpace, and write with fmt.Fprintln. After the loop, wrap scanner.Err() if it is not nil.
Worked solution
package main
import (
"bufio"
"errors"
"fmt"
"io"
"strings"
)
var (
errFull = errors.New("disk full")
errDropped = errors.New("connection dropped")
)
type failAfter struct {
writes int
}
func (f *failAfter) Write(p []byte) (int, error) {
if f.writes == 0 {
return 0, errFull
}
f.writes--
return len(p), nil
}
type failingReader struct {
data io.Reader
}
func (r *failingReader) Read(p []byte) (int, error) {
n, err := r.data.Read(p)
if err == io.EOF {
return n, errDropped
}
return n, err
}
func copyLines(r io.Reader, w io.Writer) (int, error) {
scanner := bufio.NewScanner(r)
written := 0
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
if _, err := fmt.Fprintln(w, line); err != nil {
return written, fmt.Errorf("write: %w", err)
}
written++
}
if err := scanner.Err(); err != nil {
return written, fmt.Errorf("read: %w", err)
}
return written, nil
}
func main() {
input := "tent\n\ndrill\nlamp\n"
var out strings.Builder
fmt.Println(copyLines(strings.NewReader(input), &out))
fmt.Println(copyLines(strings.NewReader(input), &failAfter{writes: 1}))
fmt.Println(copyLines(&failingReader{data: strings.NewReader(input)}, &out))
}3 <nil>
1 write: disk full
3 read: connection droppedEach failure came through its own path with its own prefix, and the counts show how far each run got. The third case wrote all three lines before the read failed, which is the situation where a caller most needs the error: the output looks complete but the input was not.
Completion is saved in this browser only. It does not measure mastery.