wand/exec_test.go
2025-08-26 14:12:18 +02:00

66 lines
1.3 KiB
Go

package wand
import (
"bytes"
"fmt"
"io"
"strings"
"testing"
)
type testCase struct {
impl any
stdin string
conf string
env string
command string
}
func testExec(test testCase, err string, expect ...string) func(*testing.T) {
return func(t *testing.T) {
var exitCode int
exit := func(code int) { exitCode = code }
var stdinr io.Reader
if test.stdin != "" {
stdinr = bytes.NewBuffer([]byte(test.stdin))
}
stdout := bytes.NewBuffer(nil)
stderr := bytes.NewBuffer(nil)
cmd := wrap(test.impl)
e := strings.Split(test.env, ";")
a := strings.Split(test.command, " ")
exec(stdinr, stdout, stderr, exit, cmd, Config{test: test.conf}, e, a)
if exitCode != 0 && err == "" {
t.Fatal("non-zero exit code:", stderr.String())
}
if err != "" && exitCode == 0 {
t.Fatal("failed to fail")
}
if err != "" && !strings.Contains(stderr.String(), err) {
t.Fatal("expected error not received:", stderr.String())
}
if exitCode != 0 {
return
}
var expstr []string
for _, e := range expect {
expstr = append(expstr, fmt.Sprint(e))
}
output := stdout.String()
if output[len(output)-1] != '\n' {
output = output + "\n"
}
if output != strings.Join(expstr, "\n")+"\n" {
t.Fatal("unexpected output:", stdout.String())
}
}
}