[英]How to mock/abstract filesystem in go?
I would like to be able to log every write/read that my go app issues to the underlying OS, and also (if it's possible) completely replace FS with one that resides only in memory.我希望能够记录我的 go 应用程序向底层操作系统发出的每次写入/读取,并且(如果可能)将 FS 完全替换为仅驻留在内存中的 FS。
Is it possible?是否有可能? How?
如何? Maybe there is a ready-to-Go solution?
也许有现成的解决方案?
This is straight from Andrew Gerrand's 10 things you (probably) don't know about Go :这直接来自 Andrew Gerrand 的关于 Go 的你(可能)不知道的10 件事:
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) }
For this to work, you will need to write your code to take a fileSystem
argument (maybe embed it in some other type, or let nil
denote the default filesystem).为此,您需要编写代码以获取
fileSystem
参数(可能将其嵌入其他类型,或者让nil
表示默认文件系统)。
For those looking to solve the problem of mocking out your filesystem during testing, checkout @spf13's Afero library, https://github.com/spf13/afero .对于那些希望在测试期间解决模拟文件系统问题的人,请查看 @spf13 的 Afero 库, https://github.com/spf13/afero 。 It does everything that the accepted answer does, but with better documentation and examples.
它完成了公认答案所做的一切,但提供了更好的文档和示例。
You can use the testing/fstest
package:您可以使用
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 https://golang.org/pkg/testing/fstest
Just because this question pops up pretty high when googling for this matter:仅仅因为在谷歌搜索这个问题时这个问题弹出的频率很高:
I don't know about logging reads and writes, but for a filesystem residing only in memory, I've found blang/vfs .我不知道记录读取和写入,但是对于仅驻留在内存中的文件系统,我发现了blang/vfs 。 I haven't used in production, and it says it's alpha and interfaces are likely to change.
我没有在生产中使用过,它说它是 alpha 并且接口可能会改变。 Use it at your own risk.
需要您自担风险使用它。
I suppose you could implement it to log reads and writes.我想你可以实现它来记录读取和写入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.