I recently started working on a project where I was doing a lot of low level file manipulation. This of course made any of the code paths that used functions where I manipulated these files hard to test. After some brief searching on the web, I came across afero:
This go library easily allowed me to separate out the places where I made calls to the filesystem so I could later replace it with an in memory file system while testing. This would ensure that I wouldn’t have to have permissions set up on an OS filesystem in order to do my testing. Furthermore, I wouldn’t have to worry about leaving my files behind.
Setup
I deviated slightly from the documentation on how to set up my filesystem. The documentation on GitHub shows an initialization like so:
However, I went with the following as it allowed me to use both the functions
normally found in the os
pacakge as well as those in the ioutil
package.
This allowed me to do things like stat
files:
And read whole files to be parsed later as yaml:
Testing
Now, when it came time for testing, all I had to do in my tests was setup an in memory filesystem and test my functions were behaving as expected: