Memory file for testing

How to create files in memory for unit testing in Go?

In Python, I test reading from a file or writing to a file with or . For example, to test a file analyzer, I would io.BytesIO io.StringIO

def test_parse_function():
    infile = io.StringIO('''\
line1
line2
line3
''')
    parsed_contents = parse_function(infile)
    expected_contents = ['line1', 'line2', 'line3']  # or whatever is appropriate
    assert parsed_contents == expected_contents

Similarly, to output the file, I would have something like the following:

def test_write_function():
    outfile = io.StringIO()
    write_function(outfile, ['line1', 'line2', 'line3'])
    outfile.seek(0)
    output = outfile.read()
    expected_output = '''\
line1
line2
line3
'''
    assert output == expected_output
+7
source share
3 answers

You can use Buffer .

, io.Reader io.Writer (Buffer ) IO. , / ( , , ...) , , , . .


:

:

// mypkg project mypkg.go
package mypkg

import (
    "bufio"
    "io"
    "strings"
)

func MyFunction(in io.Reader, out io.Writer) {
    rd := bufio.NewReader(in)
    str, _ := rd.ReadString('\n')
    io.WriteString(out, strings.TrimSuffix(str, "\n")+" was input\n")
}

:

package main

import (
    "mypkg"
    "os"
)

func main() {
    mypkg.MyFunction(os.Stdin, os.Stdout)
}

:

// mypkg project mypkg_test.go
package mypkg

import (
    "bytes"
    "testing"
)

func TestMyFunction(t *testing.T) {
    ibuf := bytes.NewBufferString("hello\n")
    obuf := bytes.NewBufferString("")
    MyFunction(ibuf, obuf)
    if obuf.String() != "hello was input\n" {
        t.Fail()
    }
}
+13

"" Go ", spf13/afero , .

Afero :

mock .

, , .
, , , Windows ..
MemMapFs .

  • , -
  • .
  • . 'rm -rf /'
  • .
  • .

(MemMapFs).
.

+3

If you need io.ReadSeekerand do not need write access, use : bytes.Reader

import "bytes"

data := []byte("success")
readSeeker := bytes.NewReader(data)

This is useful for things like . http.ServeContent()

+1
source

Source: https://habr.com/ru/post/1659245/


All Articles