简体   繁体   中英

Golang - Testing with filesystem and reaching 100%

I'm trying to test one of my package to reach 100%. However, I can't find how I can do this without being "against the system" (functions pointers, etc.).

I tried to do something similar to this, but I can't reach 100% because of "real" functions :

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

(From https://talks.golang.org/2012/10things.slide#8 )

Does someone would have a suggestion ? :) Thanks !

I attempted to do same thing, just to try it. I achieved it by referencing all system file calls as interfaces and having method accept an interface. Then if no interface was provided the system method was used. I am brand new to Go, so I'm not sure if it violates best practices or not.

import "io/ioutil"


type ReadFile func (string) ([]byte, error)


type FileLoader interface {
    LoadPath(path string) []byte
}

// Initializes a LocalFileSystemLoader with default ioutil.ReadFile
// as the method to read file.  Optionally allows caller to provide
// their own ReadFile for testing.
func NewLocalFileSystemLoader(rffn ReadFile) *localFileSystemLoader{
    var rf ReadFile = ioutil.ReadFile

    if rffn != nil {
        rf = rffn
    }
    return &localFileSystemLoader{
        ReadFileFn: rf}
}

type localFileSystemLoader struct {
    ReadFileFn ReadFile
}

func (lfsl *localFileSystemLoader) LoadPath(path string) []byte {
    dat, err := lfsl.ReadFileFn(path)
    if err != nil {
        panic(err)
    }

    return dat
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM