Capstone 2: tests and a fake store

The tests follow the three layers of the capstone. The model is a table of titles and expected errors. The file store runs against a temporary directory, so two tests never share a file. The command layer runs against a fake store and a buffer, so the output is asserted as a string and no disk is touched. The whole suite takes milliseconds.

The fake store

The fake is a map, a counter and the five methods of the interface. It has one extra field, fail, which a test can set to make every write fail; that is the cheapest way to cover an error path without a broken disk. Forty lines of test code replace the real store for every command test.

type fakeStore struct { tasks map[int]Task next int fail error } func newFakeStore() *fakeStore { return &fakeStore{tasks: map[int]Task{}, next: 1} } func (f *fakeStore) All() ([]Task, error) { if f.fail != nil { return nil, f.fail } out := make([]Task, 0, len(f.tasks)) for _, task := range f.tasks { out = append(out, task) } sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID }) return out, nil } func (f *fakeStore) Get(id int) (Task, error) { task, ok := f.tasks[id] if !ok { return Task{}, ErrNotFound } return task, nil } func (f *fakeStore) Put(task Task) error { if f.fail != nil { return f.fail } f.tasks[task.ID] = task return nil } func (f *fakeStore) Delete(id int) error { if _, ok := f.tasks[id]; !ok { return ErrNotFound } delete(f.tasks, id) return nil } func (f *fakeStore) NextID() (int, error) { id := f.next f.next++ return id, nil }

All sorts the tasks by id, which is what the real store returns and what the list test expects. A fake that returns map order makes a test flaky once in a hundred runs, and the fix is to make the fake behave like the interface promises rather than to sort in the test.

Model tests

The model test is a table with a subtest per rule: trimming, a normal title, an empty one and the placeholder. The placeholder case does not compare a sentinel because there is none; it asserts that an error exists. The due date is checked only when the input had one.

func TestNew(t *testing.T) { due := time.Date(2026, 11, 20, 15, 30, 0, 0, time.UTC) tests := []struct { name string title string due time.Time want string err error }{ {"trims the title", " buy milk ", due, "buy milk", nil}, {"keeps a normal title", "write lesson", time.Time{}, "write lesson", nil}, {"rejects an empty title", " ", time.Time{}, "", ErrEmptyTitle}, {"rejects the placeholder", "TODO", time.Time{}, "", nil}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { task, err := New(1, tt.title, tt.due) if tt.err != nil { if !errors.Is(err, tt.err) { t.Fatalf("got %v, want %v", err, tt.err) } return } if tt.title == "TODO" { if err == nil { t.Fatal("expected an error for TODO") } return } if err != nil { t.Fatalf("unexpected error: %v", err) } if task.Title != tt.want { t.Errorf("title = %q, want %q", task.Title, tt.want) } if !tt.due.IsZero() && task.Due == nil { t.Error("due date was dropped") } }) } }

A table with a t.Run per case gives one line per rule in the output and a failure that names the rule. The test does not repeat the production logic: it checks the four outcomes a caller can see.

File store tests

The file test covers the first run (empty), the id, a put and a get, the due date through the file, a delete, the sentinel after the delete, and one thing the fake cannot show: that no temporary file is left behind. The corrupt test writes a single brace and asserts the error.

package tasks import ( "errors" "os" "path/filepath" "testing" "time" ) func TestFileStore(t *testing.T) { path := filepath.Join(t.TempDir(), "tasks.json") store := NewFileStore(path) all, err := store.All() if err != nil || len(all) != 0 { t.Fatalf("empty store: %v, %d tasks", err, len(all)) } id, err := store.NextID() if err != nil || id != 1 { t.Fatalf("next id = %d, %v", id, err) } task, err := New(id, "buy milk", time.Date(2026, 11, 20, 0, 0, 0, 0, time.UTC)) if err != nil { t.Fatal(err) } if err := store.Put(task); err != nil { t.Fatal(err) } got, err := store.Get(1) if err != nil || got.Title != "buy milk" { t.Fatalf("Get = %+v, %v", got, err) } if got.Due == nil || got.Due.Format("2006-01-02") != "2026-11-20" { t.Fatalf("due = %v", got.Due) } if err := store.Delete(1); err != nil { t.Fatal(err) } if _, err := store.Get(1); !errors.Is(err, ErrNotFound) { t.Fatalf("Get after delete = %v", err) } entries, err := os.ReadDir(filepath.Dir(path)) if err != nil { t.Fatal(err) } for _, entry := range entries { if entry.Name() != "tasks.json" { t.Errorf("leftover file %s", entry.Name()) } } } func TestFileStoreCorrupt(t *testing.T) { path := filepath.Join(t.TempDir(), "tasks.json") if err := os.WriteFile(path, []byte("{"), 0o644); err != nil { t.Fatal(err) } store := NewFileStore(path) if _, err := store.All(); err == nil { t.Fatal("expected an error for a corrupt file") } }

t.TempDir is removed by the test framework, so a failed run leaves nothing for the next one. The directory check after the delete is the test for the atomic write: a save that forgot to remove its temporary file leaves .tasks-*.json next to tasks.json and this loop fails.

The run

go test -v ./tasks runs every test in the package and prints each name, including the subtests of the model table. The package line reports the total time; a cached result appears as (cached) unless -count=1 is given.

go test -count=1 -v ./tasks

=== RUN TestCommands
--- PASS: TestCommands (0.00s)
=== RUN TestCommandsList
--- PASS: TestCommandsList (0.00s)
=== RUN TestNew
=== RUN TestNew/trims_the_title
=== RUN TestNew/keeps_a_normal_title
=== RUN TestNew/rejects_an_empty_title
=== RUN TestNew/rejects_the_placeholder
--- PASS: TestNew (0.00s)
--- PASS: TestNew/trims_the_title (0.00s)
--- PASS: TestNew/keeps_a_normal_title (0.00s)
--- PASS: TestNew/rejects_an_empty_title (0.00s)
--- PASS: TestNew/rejects_the_placeholder (0.00s)
=== RUN TestToggleAndString
--- PASS: TestToggleAndString (0.00s)
=== RUN TestFileStore
--- PASS: TestFileStore (0.00s)
=== RUN TestFileStoreCorrupt
--- PASS: TestFileStoreCorrupt (0.00s)
PASS
ok example.com/tasks/tasks 0.008s

Six tests and four subtests, all passing, in eight milliseconds. The suite does not start the command: the command is the thin layer from lesson 123, and the layer below it is what the tests hold down.

What the fake buys

A test with the real store is a test of two things at once. The fake separates them: the command tests check the command, the file tests check the file, and a failure points at one of them. The fake also runs in any order and in parallel, because it has no file to share. The cost is that the fake can drift from the interface; a compile error catches a missing method, and one integration test with the real store catches a behaviour difference.

The next lesson adds the JSON output the scripts wanted, and the one after that measures the store.

Exercises

  1. Set the fake's fail field and add a test for the error path of Add. Which status would the command exit with?
  2. Run the storage test with a relative path instead of t.TempDir and run it twice. What does the second run see, and why is the temporary directory the fix?
  3. Add a subtest for a title of eighty-one characters once the model has such a rule. Which table grows, and what does the subtest name?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does the fake store implement?

    Answer

    The Store interface

    Five methods and a map.

  2. Why does the fake sort in All?

    Answer

    The real store returns id order and the interface promises it

    A fake should match the contract.

  3. What is the fake's fail field for?

    Answer

    Covering an error path without a broken disk

    It is the cheapest error injection.

  4. What does t.TempDir give?

    Answer

    A directory removed by the test framework

    Two tests never share it.

  5. What does the storage test check about the atomic write?

    Answer

    No temporary file is left behind

    The directory has one entry.

  6. How is the command layer tested?

    Answer

    With the fake store and a bytes.Buffer

    The output is a string.

  7. What does a subtest give the table?

    Answer

    One named line per case and a targeted failure

    t.Run names the case.

  8. Can the fake drift from the real store?

    Answer

    Yes, which is why one integration test uses the real one

    The interface catches signatures, not behaviour.

  9. Why -count=1 in the run?

    Answer

    It skips the test result cache

    A cached result prints (cached).

  10. What does the suite not test?

    Answer

    The process exit codes of the binary

    That is a job for a script or an exec test.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev