Created
June 19, 2022 12:44
-
-
Save sewera/9c4af488b9d92c500f6ef004dff1aa20 to your computer and use it in GitHub Desktop.
Go (Golang) - fs.FS implementation with a correct root directory, using default os.Open implementation, as opposed to os.DirFS("/"), which can produce unwanted behavior on some systems
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// issue in context: https://github.com/golang/go/issues/44279#issuecomment-1159714960 | |
type OsFilesystem struct{} | |
func (f *OsFilesystem) Open(name string) (fs.File, error) { | |
return os.Open(name) | |
} | |
// *OsFilesystem implements fs.FS | |
var _ fs.FS = new(OsFilesystem) | |
func TestOsFilesystem(t *testing.T) { | |
// given | |
openFile := func(fsys fs.FS, path string) error { | |
_, err := fsys.Open(path) | |
return err | |
} | |
fsys := new(OsFilesystem) | |
t.Run("exists", func(t *testing.T) { | |
// given | |
path := "/tmp/existent.file" | |
// when | |
err := openFile(fsys, path) | |
// then | |
assert.NoError(t, err) | |
}) | |
t.Run("does not exist", func(t *testing.T) { | |
// given | |
path := "/tmp/nonexistent.file" | |
// when | |
err := openFile(fsys, path) | |
// then | |
assert.Error(t, err) | |
assert.True(t, errors.Is(err, fs.ErrNotExist)) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment