Golang afero: Difference between revisions

From wikinotes
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
Afero defines and implements an interface to access the filesystem.<br>
Afero defines and implements an interface to access the filesystem.<br>
You can then pass in an abstraction of real os calls, or a stub stub interface you can make assertions against.
You can then pass in an abstraction of real os calls, or a stub stub interface you can make assertions against.<br>
It is maintained by the go developers.


= Documentation =
= Documentation =
Line 55: Line 56:
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Basics -->
</blockquote><!-- Basics -->
== Common Tasks ==
<blockquote>
<syntaxhighlight lang="go">
Fs := afero.NewOsFs()
Os := afero.Afero{Fs: Fs}
path, err := Os.TempDir(os.TempDir(), "my-prefix-")
exists, err := Os.Exists("/var/tmp/foo")
</syntaxhighlight>
</blockquote><!-- Common Tasks -->
</blockquote><!-- Usage -->
</blockquote><!-- Usage -->

Latest revision as of 19:43, 30 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.
It is maintained by the go developers.

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

Common Tasks

Fs := afero.NewOsFs()
Os := afero.Afero{Fs: Fs}

path, err := Os.TempDir(os.TempDir(), "my-prefix-")
exists, err := Os.Exists("/var/tmp/foo")