io/fs adapters?

182 views
Skip to first unread message

aind...@gmail.com

unread,
Mar 27, 2021, 11:09:12 PM3/27/21
to golang-nuts
For testing library functions that accept fs.FS, I've been creating mock FS implementations. However, I'm surprised by the amount of code I've had to write for something like an FS with a single file in it. See below:

type singleFileFS struct {
    f stringFile
}

func (r singleFileFS) Open(name string) (fs.File, error)     { return nil, nil }
func (r singleFileFS) Stat(name string) (fs.FileInfo, error) { return r, nil }
func (r singleFileFS) Name() string                          { return "." }
func (r singleFileFS) Size() int64                           { return -1 }
func (r singleFileFS) Mode() (m fs.FileMode)                 { return }
func (r singleFileFS) ModTime() (t time.Time)                { return }
func (r singleFileFS) IsDir() bool                           { return true }
func (r singleFileFS) Sys() interface{}                      { return nil }
func (r singleFileFS) ReadDir(string) ([]fs.DirEntry, error) { return []fs.DirEntry{r.f}, nil }
func (r singleFileFS) ReadFile(name string) ([]byte, error)  { return r.f.body, nil }

type stringFile struct {
    name string
    body []byte
}

func (s stringFile) Stat() (fs.FileInfo, error)   { return s, nil }
func (s stringFile) Name() string                 { return s.name }
func (s stringFile) Size() int64                  { return int64(len(s.body)) }
func (s stringFile) Mode() (m fs.FileMode)        { return }
func (s stringFile) Type() (m fs.FileMode)        { return }
func (s stringFile) ModTime() (t time.Time)       { return }
func (s stringFile) IsDir() (false bool)          { return }
func (s stringFile) Sys() (i interface{})         { return }
func (s stringFile) Read([]byte) (i int, e error) { return }
func (s stringFile) Close() (err error)           { return }
func (s stringFile) Info() (fs.FileInfo, error)   { return s, nil }

Does anyone have any tips for creating a smaller version of this kind of adapter? Or are there any FS adapter libraries that can help with this sort of thing?

Thanks,
Akhil

Sean Liao

unread,
Mar 28, 2021, 4:06:21 AM3/28/21
to golang-nuts

Manlio Perillo

unread,
Mar 28, 2021, 6:31:24 AM3/28/21
to golang-nuts
For a project I wrote a simplified MapFS, where only the file data needs to be specified, as a string:


Manlio

aind...@gmail.com

unread,
Mar 28, 2021, 11:46:58 AM3/28/21
to golang-nuts
Thank you! I completely missed the memo on fstest :)
Reply all
Reply to author
Forward
0 new messages