testfs

package module
v0.4.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 24, 2021 License: MIT Imports: 6 Imported by: 0

README

testfs

A simple fs.FS which is contained in a test (using testing.TB's TempDir()) and with a few helper methods.

PS: This lib only works on Go 1.16+.

Example

func TestSomething(t *testing.T) {
	tmpfs := testfs.New(t)
	testfile := "foo/bar/foobar"
	_ = tmpfs.MkdirAll(filepath.Dir(testfile), 0o764)
	_ = tmpfs.WriteFile(testfile, []byte("example"), 0o644)

	// you can now use tmpfs as a fs.FS...
	// fs.WalkDir(tmpfs, ".", func(path string, d fs.DirEntry, err error) error { return nil })

	// and read files of course:
	bts, _ := fs.ReadFile(tmpfs, testfile)
	fmt.Println(string(bts))
}

Why

The idea is to able to test code that use a fs.FS, without having to, for example, commit a bunch of files inside testdata and without using in-memory implementation that might not do the same thing as a real FS.

This is a real FS, it only limits itself to a temporary directory and cleans after itself once the test is done. You also get a couple of helper methods to create the structure you need.

Other options

If you don't mind testing against an in-memory implementation, the native fstest.MemFS is a good option.

Documentation

Overview

Package testfs provides a simple fs.FS which is contained in a test (using testing.TB's TempDir) and with a few helper methods.

The temporary FS is auto-cleaned once the test and all its children finish.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrOutsideFS = fmt.Errorf("path is outside test fs root folder")

ErrOutsideFS happens when the user tries to handle files outside of the FS's root path.

Functions

This section is empty.

Types

type FS added in v0.3.0

type FS struct {
	FS fs.FS
	// contains filtered or unexported fields
}

FS is a fs.FS made for testing only.

func New added in v0.2.0

func New(tb testing.TB) FS

New creates a new FS using the tb.TempDir as root.

Example
tmpfs := New(&testing.T{})
_ = tmpfs.MkdirAll("foo/bar", 0o764)
_ = tmpfs.WriteFile("foo/bar/foobar", []byte("example"), 0o644)
bts, _ := fs.ReadFile(tmpfs, "foo/bar/foobar")
fmt.Println(string(bts))
Output:

example

func (FS) MkdirAll added in v0.3.0

func (t FS) MkdirAll(path string, perm os.FileMode) error

MkdirAll creates the dir and all the necessary parents into FS.

func (FS) Open added in v0.4.3

func (t FS) Open(name string) (fs.File, error)

Open opens the named file.

func (FS) Path added in v0.4.0

func (t FS) Path() string

Path returns the FS root path.

func (FS) WriteFile added in v0.3.0

func (t FS) WriteFile(name string, data []byte, perm os.FileMode) error

WriteFile writes a file to FS.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL