Golang afero: Difference between revisions

From wikinotes
Line 54: Line 54:
}
}
</syntaxhighlight>
</syntaxhighlight>
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")
<syntaxhighlight lang="go">
// utils exposed in different imports
import "afero/ioutil"
ioutil.ReadFile(appfs, "/var/tmp/foo.txt")
</syntaxhighlight>
There are no assertions, when testing use the API to check the presence/contents of the file.<br>
There are however some additional utils that are helpful, both in testing and production code (ex. <code>appfs.DirExists()</code>).
</blockquote><!-- Basics -->
</blockquote><!-- Basics -->
</blockquote><!-- Usage -->
</blockquote><!-- Usage -->

Revision as of 18:27, 22 July 2022

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)
    })
}