Golang afero

From wikinotes
Revision as of 18:26, 22 July 2022 by Will (talk | contribs) (→‎Basics)

Afero defines and implements an interface to access the filesystem.
You can then pass in an abstraction of real os calls, or a stub stub interface you can make assertions against.

Documentation

api docs https://pkg.go.dev/github.com/spf13/afero
github https://github.com/spf13/afero

Usage

Basics

// internal/fs/fs.go
import "github.com/spf13/afero"

Fs = Fs: afero.NewOsFs() // real 'os' calls
// foo.go
package foo
import (
    "example.com/x/mypkg/internal/fs"
    "github.com/spf13/afero"
)

func DoThing() {
    Os = afero.Afero{Fs: Fs}
    // os.* exposed on Fs
    Fs.Create("/var/tmp/foo.txt")

    // io, ioutil exposed in Afero{}
    Os.ReadFile("/var/tmp/foo.txt")
}
// foo_test.go
package foo

func TestDoThing(t *testing.T) {
    var fs.Fs = afero.NewMemMapFs()
    t.Run("Does Thing", func(t *testing.T) {
        err := foo.DoThing()
        assert.Nil(t, err)
    })
}

appfs := afero.NewOsFs() appfs := afero.NewMemMapFs() // memory backed fake filesystem // there are several additional options, like sftp, CopyOnWriteFs, ...

// creates on disk, or in memory (depending on appfs val) appfs.Create("/var/tmp/foo.txt")

// utils exposed in different imports
import "afero/ioutil"
ioutil.ReadFile(appfs, "/var/tmp/foo.txt")

There are no assertions, when testing use the API to check the presence/contents of the file.
There are however some additional utils that are helpful, both in testing and production code (ex. appfs.DirExists()).