如何模拟/抽象文件系统?

时间:2013-05-24 19:28:16

标签: filesystems mocking go

我希望能够将我的应用程序发布的每个写入/读取记录到底层操作系统,并且(如果可能的话)将FS完全替换为仅存储在内存中的FS。

有可能吗?怎么样?也许有一个现成的解决方案?

4 个答案:

答案 0 :(得分:30)

直接来自Andrew Gerrand的10 things you (probably) don't know about Go

var fs fileSystem = osFS{}

type fileSystem interface {
    Open(name string) (file, error)
    Stat(name string) (os.FileInfo, error)
}

type file interface {
    io.Closer
    io.Reader
    io.ReaderAt
    io.Seeker
    Stat() (os.FileInfo, error)
}

// osFS implements fileSystem using the local disk.
type osFS struct{}

func (osFS) Open(name string) (file, error)        { return os.Open(name) }
func (osFS) Stat(name string) (os.FileInfo, error) { return os.Stat(name) }

要使其正常工作,您需要编写代码以获取fileSystem参数(可能将其嵌入其他类型,或者让nil表示默认文件系统)。

答案 1 :(得分:13)

对于那些希望在测试过程中解决模拟文件系统问题的人,请查看@ spf13的Afero库https://github.com/spf13/afero。它完成了所接受的答案所做的一切,但有更好的文档和示例。

答案 2 :(得分:1)

您可以使用 testing/fstest 包:

package main
import "testing/fstest"

func main() {
   m := fstest.MapFS{
      "hello.txt": {
         Data: []byte("hello, world"),
      },
   }
   b, e := m.ReadFile("hello.txt")
   if e != nil {
      panic(e)
   }
   println(string(b) == "hello, world")
}

https://golang.org/pkg/testing/fstest

答案 3 :(得分:0)

只是因为在谷歌搜索这个问题时这个问题突然出现了:

我不知道记录读取和写入,但对于仅驻留在内存中的文件系统,我发现blang/vfs。我没有在生产中使用它,它说它的alpha和接口可能会改变。需要您自担风险使用它。

我想你可以实现它来记录读写。