How to cleanly test files in Go
While working on a small project of mine, I found it difficult to test any function that had to do with files.
I wasn’t quite sure how to test things like file creation without accidentally leaving files left around. In order to find out how to do this properly, I went to go look how Afero, a file system library for Go, tests itself. I found something really clever that I eventually extracted out into its own library for regular usage.
Afero does two things to guarantee that it’s not causing any leftover files when you run go test
.
- It’s going to use temporary files stored in the normal cache location. (
var/folders
on macOS). - It’s going to keep track of these temporary files in an array and have a function we can call to delete them when we’re done.
This makes it easy to test files without ever having to worry about cleaning up after yourself. I liked this functionality a lot, so I built it into a little library (along with a few other things) called Filet.
In Filet, we store all the files in a package level variable so you don’t have to think about them. Then we provide TmpFile
and TmpDir
functions for creating new files and directories. Finally, we have a CleanUp
function that will delete all the temporary files you’ve accumulated.
In practice it looks like this:
func TestFoo(t *testing.T) {
defer filet.CleanUp(t) // Creates a temporary file with string "some content"
file := filet.TmpFile(t, "", "some content") // ... Do something with `file`
}
And… That’s it! Now you can safely create mock files and directories without having to worry about anything other than your tests.
If you find this useful, go get github.com/Flaque/filet
!