dongnachuang6635 2019-01-28 16:50
浏览 68

模拟bufio.Scanner输入

I've had a lot of success defining interfaces and substituting mocks during testing, but I've hit a problem with mocking bufio.Scanner input:

file := &mockFile{
    ReadFunc: func(p []byte) (int, error) {
        reader := bufio.NewReader(bytes.NewReader([]byte(consulPropertiesFile)))
        return reader.Read(p)
    },
    CloseFunc: func() error {
        return nil
    },
}

fs := &mockFileSystem{
    OpenFunc: func(name string) (File, error) {
        return file, nil
    },
}

properties, err := readConsulPropertiesFile(fs)

While this seems to work, once the scanner has gotten to the end of my string, it just seems to return to the beginning, and reads too much (it seems to read more than a line this time around). It's like I need to manually return an EOF error at the appropriate time in my ReadFunc, but I'm not sure how to figure out when I should do that...

Scanner code (lifted from here):

f, err := file.Open("/run/secrets/consul-web4.properties")
if err != nil {
    return nil, err
}
defer f.Close()

properties := map[string]string{}

scanner := bufio.NewScanner(f)
for scanner.Scan() {
    line := scanner.Text()
    if equal := strings.Index(line, "="); equal >= 0 {
        if key := strings.TrimSpace(line[:equal]); len(key) > 0 {
            value := ""
            if len(line) > equal {
                value = strings.TrimSpace(line[equal+1:])
            }
            properties[key] = value
        }
    }
}

I've yet to refactor the above...

I've tried the following variations on my test string:

const input = `key=value
key=value
key=value
`
const input = "key=value
key=value
key=value
"

And I've tried bufio.Reader & io.Reader implementations.

Any help / insight appreciated!

  • 写回答

1条回答 默认 最新

  • dou70260 2019-01-28 18:01
    关注

    Thanks to @Adrian:

    I realised on my way home it was probably due to instantiating a new reader every time the method is called. Moving the reader instantiation out of my ReadFunc worked perfectly!

    And thanks to @Thundercat for the strings.NewReader() tip, updated code:

    reader := ioutil.NopCloser(strings.NewReader(consulPropertiesFile))
    
    file := &mockFile{
        ReadFunc: func(p []byte) (int, error) {
            return reader.Read(p)
        },
        CloseFunc: func() error {
            return nil
        },
    }
    

    For anyone who comes across this post looking for information on how to mock file system etc:

    An interface for opening and stat'ing files, plus concrete implementation using os package:

    // FileSystem - interface to the filesystem
    type FileSystem interface {
        Open(name string) (File, error)
        Stat(name string) (os.FileInfo, error)
    }
    
    // OsFS - filesystem backed by default os package
    type OsFS struct {
    }
    
    // Open - open a file
    func (o *OsFS) Open(name string) (File, error) {
        return os.Open(name)
    }
    
    // Stat - get file status
    func (o *OsFS) Stat(name string) (os.FileInfo, error) {
        return os.Stat(name)
    }
    

    File interface mentioned above:

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

    Mock the file you want your filesystem to return (implement the methods that will be used by your code):

    type mockFile struct {
        CloseFunc  func() error
        ReadFunc   func(p []byte) (int, error)
        ReadAtFunc func(p []byte, off int64) (int, error)
        SeekFunc   func(offset int64, whence int) (int64, error)
        StatFunc   func() (os.FileInfo, error)
    }
    
    func (m *mockFile) Close() error {
        return m.CloseFunc()
    }
    
    func (m *mockFile) Read(p []byte) (int, error) {
        return m.ReadFunc(p)
    }
    
    func (m *mockFile) ReadAt(p []byte, off int64) (int, error) {
        return m.ReadAtFunc(p, off)
    }
    
    func (m *mockFile) Seek(offset int64, whence int) (int64, error) {
        return m.SeekFunc(offset, whence)
    }
    
    func (m *mockFile) Stat() (os.FileInfo, error) {
        return m.StatFunc()
    }
    
    ---
    
    reader := ioutil.NopCloser(strings.NewReader("some string, replace with bytes etc"))
    
    file := &mockFile{
        ReadFunc: func(p []byte) (int, error) {
            return reader.Read(p)
        },
        CloseFunc: func() error {
            return nil
        },
    }
    

    And return your mockFile via mockFileSystem:

    fs := &mockFileSystem{
        OpenFunc: func(name string) (File, error) {
            return file, nil
        },
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值