undocker/internal/cmdrootfs/cmdrootfs_test.go

94 lines
2.1 KiB
Go
Raw Normal View History

2021-05-24 00:11:58 +03:00
package cmdrootfs
2021-05-24 00:11:58 +03:00
import (
"bytes"
"io"
2021-05-24 00:11:58 +03:00
"io/ioutil"
2021-05-24 00:11:58 +03:00
"path/filepath"
"testing"
goflags "github.com/jessevdk/go-flags"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
2021-05-24 00:11:58 +03:00
func TestExecute(t *testing.T) {
2021-05-24 00:11:58 +03:00
var _foo = []byte("foo foo")
2021-05-24 00:11:58 +03:00
tests := []struct {
name string
2021-05-24 00:11:58 +03:00
fixture func(*testing.T, string)
2021-05-24 00:11:58 +03:00
infile string
outfile string
wantErr string
}{
{
2021-05-24 00:11:58 +03:00
name: "ok passthrough via stdout",
infile: "t10-in.txt",
fixture: func(t *testing.T, dir string) {
fname := filepath.Join(dir, "t10-in.txt")
require.NoError(t, ioutil.WriteFile(fname, _foo, 0644))
},
2021-05-24 00:11:58 +03:00
outfile: "-",
},
{
2021-05-24 00:11:58 +03:00
name: "ok passthrough via file",
infile: "t20-in.txt",
fixture: func(t *testing.T, dir string) {
fname := filepath.Join(dir, "t20-in.txt")
require.NoError(t, ioutil.WriteFile(fname, _foo, 0644))
},
outfile: "t20-out.txt",
2021-05-24 00:11:58 +03:00
},
{
name: "infile does not exist",
2021-05-24 00:11:58 +03:00
infile: "t3-does-not-exist.txt",
wantErr: "^open .*t3-does-not-exist.txt: no such file or directory$",
2021-05-24 00:11:58 +03:00
},
{
name: "outpath dir not writable",
2021-05-24 00:11:58 +03:00
outfile: filepath.Join("t4", "does", "not", "exist"),
wantErr: "^create: open .*/t4/does/not/exist: no such file or directory",
2021-05-24 00:11:58 +03:00
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
2021-05-24 00:11:58 +03:00
dir := t.TempDir()
2021-05-24 00:11:58 +03:00
var stdout bytes.Buffer
2021-05-24 00:11:58 +03:00
c := &Command{Stdout: &stdout}
2021-05-24 00:11:58 +03:00
if tt.fixture != nil {
tt.fixture(t, dir)
}
if tt.outfile != "-" {
tt.outfile = filepath.Join(dir, tt.outfile)
}
inf := filepath.Join(dir, tt.infile)
c.PositionalArgs.Infile = goflags.Filename(inf)
2021-05-24 00:11:58 +03:00
c.PositionalArgs.Outfile = tt.outfile
2021-05-24 00:11:58 +03:00
c.flattener = flattenPassthrough
2021-05-24 00:11:58 +03:00
err := c.Execute(nil)
if tt.wantErr != "" {
2021-05-24 00:11:58 +03:00
require.Error(t, err)
assert.Regexp(t, tt.wantErr, err.Error())
2021-05-24 00:11:58 +03:00
return
}
2021-05-24 00:11:58 +03:00
var out []byte
2021-05-24 00:11:58 +03:00
require.NoError(t, err)
2021-05-24 00:11:58 +03:00
if tt.outfile == "-" {
out = stdout.Bytes()
} else {
out, err = ioutil.ReadFile(tt.outfile)
require.NoError(t, err)
}
assert.Equal(t, []byte("foo foo"), out)
2021-05-24 00:11:58 +03:00
})
}
2021-05-24 00:11:58 +03:00
}
2021-05-24 00:11:58 +03:00
2021-05-24 00:11:58 +03:00
func flattenPassthrough(r io.ReadSeeker, w io.Writer) error {
_, err := io.Copy(w, r)
2021-05-24 00:11:58 +03:00
return err
}