如何模拟/抽象文件系统? [英] How to mock/abstract filesystem in go?

查看:156
本文介绍了如何模拟/抽象文件系统?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

解决方案

这是直接从安德鲁Gerrand的



<$ p $ b $ open(name string)(file,error)
stat(name string){code> var fs fileSystem = osfs {}
$ b $ type b fileSystem interface { )(os.FileInfo,error)
}

类型文件接口{
io.Closer
io.Reader
io.ReaderAt
io.Seeker
Stat()(os.FileInfo,error)
}

// osFS使用本地磁盘实现fileSystem。
类型osFS结构{b
$ b func(osfs)打开(name string)(file,error){return os.Open(name)}
func(osFS)Stat name字符串)(os.FileInfo,error){return os.Stat(name)}

要工作,你需要编写代码来获取一个 fileSystem 参数(也许嵌入到其他类型中,或者让 nil 表示默认的文件系统)。


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.

Is it possible? How? Maybe there is an ready-to-Go solution?

解决方案

This is straight from Andrew Gerrand's 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) }

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).

这篇关于如何模拟/抽象文件系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆