1. Why file-based tests break "by themselves"
When you first write a CLI, it is very tempting to do this: "I will read tasks.txt from the current folder, because it sits next to the project anyway." On your machine, that will even work, and you will feel like a winner. And then the tests will run in CI, where there is nothing "next to" them, the current directory is different, the permissions are different, and someone has already created a file with that name anyway (or not).
The problem here is not Go and not tests. The problem is that the file system is external environment, and external environment is unpredictable. Our job as test authors is to make the environment predictable: create our own sandbox and work only inside it. Then the same test will run identically on your laptop, on the CI server, and on a colleague's machine running tests on Windows, Linux, and in a "special mood".
We have already discussed that changes to the "correct output" can break tests if the tests are tied to too specific a format. The same observation applies to the environment: the more a test depends on the "world around it", the easier it is to break without changing the business logic.
t.TempDir() — a personal sandbox on disk
testing.T can give you a temporary directory: dir := t.TempDir(). This is a small gift from the standard library that saves you from the eternal pain of "created a folder — forgot to delete it". The folder is created uniquely, and after the test Go cleans everything up for you. In other words, you get a real disk (actual os.ReadFile, os.WriteFile), but without trash in the project.
It is important to understand the philosophy: t.TempDir() is not "another way to create a folder". It is a way to tell the test runner: "this is my temporary zone; please do not leave traces here." If you are testing a CLI that reads and writes files, this is usually the simplest and most reliable option: you test the real behavior of the code, including file errors, encodings, line endings, and the other joys of life.
And here is a small style nuance: when you factor reading/writing into helpers, do not forget to call t.Helper() so that, when the test fails, the line points to the helper call site rather than the internals. This behavior is specifically supported in testing.
2. Continuing todo-cli: add the -file flag
To test file scenarios properly, we need to be able to tell the application: "use this file I prepared for you." The simplest path is the -file flag. Then in real life you can write todo list -file tasks.txt, and in a test — todo list -file <tempDir>/tasks.txt.
Below are small code fragments that come together into one application: the cli package remains the entry point for tests, and the todo package does the file work.
Task model and "string" serialization
Let's make a super-simple format: id|text. It is not the "perfect format for all time", but for learning and tests it is great: readable by eye and easy to parse.
package todo
import (
"fmt"
"strings"
)
type Task struct {
ID int
Text string
}
func (t Task) String() string {
// String example: "1|buy milk"
return fmt.Sprintf("%d|%s", t.ID, strings.ReplaceAll(t.Text, "\n", " "))
}
Note that we remove \n from the task text in advance. This is not "paranoia", but a way to keep the file format predictable.
Saving and loading tasks
Minimal version: read the whole file, parse line by line, write the whole thing back. For a learning project, that is enough.
package todo
import (
"os"
"strings"
)
func Save(path string, tasks []Task) error {
var b strings.Builder
for _, t := range tasks {
b.WriteString(t.String())
b.WriteString("\n")
}
return os.WriteFile(path, []byte(b.String()), 0o644)
}
package todo
import (
"os"
)
func Load(path string) ([]Task, error) {
b, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return Parse(string(b))
}
And we will factor parsing out separately so that it can be tested independently.
package todo
import (
"strconv"
"strings"
)
func Parse(data string) ([]Task, error) {
data = strings.TrimSpace(data)
if data == "" {
return nil, nil
}
lines := strings.Split(data, "\n")
out := make([]Task, 0, len(lines))
for _, line := range lines {
parts := strings.SplitN(line, "|", 2)
id, err := strconv.Atoi(parts[0])
if err != nil {
return nil, err
}
out = append(out, Task{ID: id, Text: parts[1]})
}
return out, nil
}
The add command: reads a file, adds a task, saves it
package cli
import (
"flag"
"fmt"
"io"
"strings"
"example.com/todo/todo"
)
func runAdd(args []string, out, errOut io.Writer) int {
fs := flag.NewFlagSet("add", flag.ContinueOnError)
fs.SetOutput(errOut)
path := fs.String("file", "tasks.txt", "path to tasks file")
if err := fs.Parse(args); err != nil {
return exitUsage
}
if fs.NArg() == 0 {
fmt.Fprintln(errOut, "missing task text")
return exitUsage
}
text := strings.Join(fs.Args(), " ")
tasks, _ := todo.Load(*path) // simplify: we will deal with "file does not exist" later
tasks = append(tasks, todo.Task{ID: len(tasks) + 1, Text: text})
if err := todo.Save(*path, tasks); err != nil {
fmt.Fprintln(errOut, "save:", err)
return exitFail
}
fmt.Fprintln(out, "ok")
return exitOK
}
Yes, there is a simplification here: we ignore the Load error. Ideally, we should distinguish "file does not exist" from a "real error", but that is not today's lecture goal: today we are learning how to isolate FS in tests, not how to design the perfect storage layer.
4. Testing the CLI + files through t.TempDir()
Now for the most important part: how to test this so that the test is independent of your machine. The idea is simple: create a temporary directory, build the path to a file inside it, run Run(...) (or runAdd/runList — however you have it organized), check the exit code and the output. Then read the file separately and make sure it was actually created and contains the expected data.
Testing a command with a real file
package cli
import (
"bytes"
"os"
"path/filepath"
"strings"
"testing"
)
func TestAdd_CreatesFileInTempDir(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "tasks.txt")
var out bytes.Buffer
var errOut bytes.Buffer
code := Run([]string{"add", "-file", path, "buy", "milk"}, strings.NewReader(""), &out, &errOut)
if code != exitOK {
t.Fatalf("code=%d, stderr=%q", code, errOut.String())
}
if out.String() != "ok\n" {
t.Fatalf("stdout=%q", out.String())
}
b, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read file: %v", err)
}
if string(b) != "1|buy milk\n" {
t.Fatalf("file=%q", string(b))
}
}
The important thing here is that the test does not create any files in the project. You can run it 100 times — the repository stays clean.
Why we read the file separately instead of trusting ok\n
From a UX perspective, ok is just a message to the user. From a functionality perspective, what matters is that the application really wrote the data where it promised to. That is why, in file-based tests, it is useful to verify not only stdout/stderr but also the FS "trace": did the file appear, and what is its content.
In spirit, this check is similar to the idea that "stdout is checked by the test runner" in example tests: there too, the important thing is the contract of "what was actually printed", not what we thought we printed.
5. A few scenarios: "add twice → IDs grow"
If you add tasks several times, it is important to check that the file is read correctly and new entries are appended in a "logically correct" way. Even if physically you rewrite the file completely, the result must still be correct.
package cli
import (
"bytes"
"path/filepath"
"strings"
"testing"
)
func TestAdd_Twice(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "tasks.txt")
var out1, err1 bytes.Buffer
_ = Run([]string{"add", "-file", path, "a"}, strings.NewReader(""), &out1, &err1)
var out2, err2 bytes.Buffer
_ = Run([]string{"add", "-file", path, "b"}, strings.NewReader(""), &out2, &err2)
var out bytes.Buffer
var errOut bytes.Buffer
code := Run([]string{"list", "-file", path}, strings.NewReader(""), &out, &errOut)
if code != exitOK {
t.Fatalf("code=%d, stderr=%q", code, errOut.String())
}
if out.String() != "1. a\n2. b\n" {
t.Fatalf("stdout=%q", out.String())
}
}
Here we do something important: we test the program "like a user" but still without launching a process. That is exactly the point of our command-level CLI architecture.
6. Useful nuances: fstest.MapFS, io/fs, and paths
Sometimes you do not need a "real disk". For example, if you want to test a parser or data loading, and speed/isolation matter more to you than checking the real os.WriteFile. In such moments, it is useful to use io/fs and testing/fstest.
The main idea: instead of the function "going into os by itself", it accepts fs.FS and reads the file through fs.ReadFile. Then, in the test, you give it fstest.MapFS — "files in memory". This is not magic, just ordinary dependency substitution, only at the file-system level.
Loading from fs.FS
package todo
import (
"io/fs"
)
func LoadFS(fsys fs.FS, name string) ([]Task, error) {
b, err := fs.ReadFile(fsys, name)
if err != nil {
return nil, err
}
return Parse(string(b))
}
Unit test without disk via fstest.MapFS
package todo
import (
"testing"
"testing/fstest"
)
func TestLoadFS_MapFS(t *testing.T) {
fsys := fstest.MapFS{
"tasks.txt": {Data: []byte("1|buy milk\n2|learn go\n")},
}
tasks, err := LoadFS(fsys, "tasks.txt")
if err != nil {
t.Fatalf("err: %v", err)
}
if len(tasks) != 2 || tasks[1].Text != "learn go" {
t.Fatalf("tasks=%v", tasks)
}
}
Here you are testing the "pure logic" of reading and parsing without creating temporary directories. This is convenient when you want the test to be as fast as possible and not depend on file-system specifics.
Important nuance about paths: filepath and "paths inside FS" are different worlds
When you work with a real disk, use filepath.Join because it respects the rules of the current OS (separators, path specifics). When you work with fs.FS (and especially with fstest.MapFS), file names are usually written in a "virtual FS" style: with / and without absolute paths.
The easiest way not to get confused is to keep the rule: "in TempDir I build an OS path with filepath, and in MapFS I use short relative names (tasks.txt, data/input.txt)". If you try to feed C:\...\tasks.txt into fs.ReadFile, it will almost certainly end strangely, and the test will look like a detective story with the last page missing.
How to choose: t.TempDir() or fstest.MapFS
At this point, it is usually tempting to produce a list of 20 items, but we are peaceful people, so let's simply summarize the idea in a table:
| Test task | Better fit | Why |
|---|---|---|
| Check that the CLI really creates/modifies a file | |
This is a "real disk"; you are testing behavior as in production |
| Check parsing/reading data as logic | |
Fast, isolated, no I/O and no temporary folders |
| Check permissions, "file does not exist", strange OS errors | |
Only a real FS gives realistic errors |
| Check a pure function LoadFS/Parse | |
You need logic, not environment |
7. Typical mistakes
Mistake #1: the test writes files into the repository (next to go.mod) and "forgets to clean up".
This looks harmless until you hit a strange test failure because the file was left over from the previous run. The test should create its own world and destroy it itself. t.TempDir() solves this almost completely: files live in the sandbox and disappear automatically.
Mistake #2: the test depends on the current directory (os.Getwd()/ "well, I run it from the project root").
As soon as the test is run from the IDE, from CI, or from another package, the "current directory" may be different. It is better to design the CLI so that the file path is passed explicitly (with the -file flag) and, in the test, is always built through filepath.Join(t.TempDir(), ...).
Mistake #3: stdout/stderr are checked, but file content is not.
The message ok can be printed even when the write did not happen (especially if you got the handling of err wrong). If the command promises to write data, the test must also verify the file result. Otherwise, you are not testing behavior, but self-soothing.
Mistake #4: test helpers call t.Fatalf, but are not marked with t.Helper().
As a result, when the test fails, you see the line inside the helper rather than the place where it was called, and you start "looking for the problem in the wrong place". Marking helpers with t.Helper() is a small habit that makes debugging much nicer.
Mistake #5: trying to use OS paths inside fstest.MapFS.
fstest.MapFS is not your disk, and it is not required to understand absolute paths. In MapFS, use relative names and /-style paths inside the virtual FS. For the real disk, use filepath.Join and t.TempDir().
GO TO FULL VERSION