wand/exec_test.go

121 lines
2.3 KiB
Go
Raw Normal View History

2025-08-18 14:24:31 +02:00
package wand
import (
"bytes"
"fmt"
2025-08-26 03:21:35 +02:00
"io"
2025-08-18 14:24:31 +02:00
"strings"
"testing"
)
2025-08-26 03:21:35 +02:00
type testCase struct {
2025-09-06 02:46:28 +02:00
impl any
stdin string
conf string
mergeConfTyped []Config
mergeConf []string
env string
command string
contains bool
2025-08-26 03:21:35 +02:00
}
func testExec(test testCase, err string, expect ...string) func(*testing.T) {
2025-08-18 14:24:31 +02:00
return func(t *testing.T) {
var exitCode int
exit := func(code int) { exitCode = code }
2025-08-26 03:21:35 +02:00
2025-09-06 02:46:28 +02:00
var stdin io.Reader
if test.stdin == "" {
stdin = bytes.NewBuffer(nil)
} else {
stdin = bytes.NewBufferString(test.stdin)
2025-08-26 03:21:35 +02:00
}
2025-08-18 14:24:31 +02:00
stdout := bytes.NewBuffer(nil)
stderr := bytes.NewBuffer(nil)
2025-08-26 03:21:35 +02:00
cmd := wrap(test.impl)
e := strings.Split(test.env, ";")
a := strings.Split(test.command, " ")
2025-09-06 02:46:28 +02:00
zeroOrOne := func(b ...bool) bool {
var one bool
for _, bi := range b {
if bi && one {
return false
}
if bi {
one = true
}
}
return true
}
if !zeroOrOne(test.conf != "", len(test.mergeConf) > 0, len(test.mergeConfTyped) > 0) {
2025-09-05 03:19:00 +02:00
t.Fatal("test error: conflicting test config")
2025-09-06 02:46:28 +02:00
}
var conf Config
if test.conf != "" {
2025-09-05 03:19:00 +02:00
conf = Config{test: test.conf}
} else if len(test.mergeConf) > 0 {
var c []Config
for _, cs := range test.mergeConf {
c = append(c, Config{test: cs})
}
conf = MergeConfig(c...)
2025-09-06 02:46:28 +02:00
} else if len(test.mergeConfTyped) > 0 {
conf = MergeConfig(test.mergeConfTyped...)
2025-09-05 03:19:00 +02:00
}
2025-09-06 02:46:28 +02:00
exec(stdin, stdout, stderr, exit, cmd, conf, e, a)
2025-08-18 14:24:31 +02:00
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))
}
2025-08-26 03:21:35 +02:00
output := stdout.String()
2025-08-26 14:12:18 +02:00
if output[len(output)-1] != '\n' {
2025-08-26 03:21:35 +02:00
output = output + "\n"
}
2025-09-05 03:19:00 +02:00
checkOutput := func() bool {
return output == strings.Join(expstr, "\n")+"\n"
}
if test.contains {
checkOutput = func() bool {
for _, e := range expstr {
if !strings.Contains(output, e) {
return false
}
}
return true
}
}
if !checkOutput() {
t.Fatal("unexpected output:", output)
2025-08-18 14:24:31 +02:00
}
}
}