Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions fs/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,19 @@ func (d *Dir) Remove() {
func (d *Dir) Join(parts ...string) string {
return filepath.Join(append([]string{d.Path()}, parts...)...)
}

// DirFromPath returns a Dir for a path that already exists. No directory is created.
// Unlike NewDir the directory will not be removed automatically when the test exits,
// it is the callers responsibly to remove the directory.
// DirFromPath can be used with Apply to modify an existing directory.
//
// If the path does not already exist, use NewDir instead.
func DirFromPath(t assert.TestingT, path string, ops ...PathOp) *Dir {
if ht, ok := t.(helperT); ok {
ht.Helper()
}

dir := &Dir{path: path}
assert.NilError(t, applyPathOps(dir, ops))
return dir
}
24 changes: 24 additions & 0 deletions fs/file_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package fs_test

import (
"errors"
"io/ioutil"
"os"
"path/filepath"
"testing"

"gotest.tools/v3/assert"
Expand Down Expand Up @@ -92,3 +95,24 @@ func TestNewDir_IntegrationWithCleanup(t *testing.T) {
assert.ErrorType(t, err, os.IsNotExist)
})
}

func TestDirFromPath(t *testing.T) {
tmpdir, err := ioutil.TempDir("", t.Name())
assert.NilError(t, err)
t.Cleanup(func() {
os.RemoveAll(tmpdir)
})

dir := fs.DirFromPath(t, tmpdir, fs.WithFile("newfile", ""))

_, err = os.Stat(dir.Join("newfile"))
assert.NilError(t, err)

assert.Equal(t, dir.Path(), tmpdir)
assert.Equal(t, dir.Join("newfile"), filepath.Join(tmpdir, "newfile"))

dir.Remove()

_, err = os.Stat(tmpdir)
assert.Assert(t, errors.Is(err, os.ErrNotExist))
}