Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

like image 761
canni Avatar asked May 24 '13 19:05

canni


People also ask

What is stub in Golang?

stub is replacement for some dependency in your code that will be used during test execution. It is typically built for one particular test and unlikely can be reused for another because it has hardcoded expectations and assumptions. mock takes stubs to next level.

What is mock in unit test?

unittest.mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. unittest.mock provides a core Mock class removing the need to create a host of stubs throughout your test suite.


1 Answers

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

like image 119
Fred Foo Avatar answered Sep 20 '22 04:09

Fred Foo