1 // SPDX-License-Identifier: GPL-3.0-or-later
2 // Copyright (C) 2021-2024 Simon Ruderich
14 "github.com/google/go-cmp/cmp"
15 "github.com/google/go-cmp/cmp/cmpopts"
17 "ruderich.org/simon/safcm"
18 "ruderich.org/simon/safcm/remote/log"
19 "ruderich.org/simon/safcm/remote/run"
22 // testRunner implements run.Runner to test commands without actually running
24 type testRunner struct {
32 func (r *testRunner) Run(cmd *exec.Cmd) error {
33 stdout, stderr, resErr := r.check("run", cmd)
34 _, err := cmd.Stdout.Write(stdout)
38 _, err = cmd.Stderr.Write(stderr)
44 func (r *testRunner) CombinedOutput(cmd *exec.Cmd) ([]byte, error) {
47 stdout, stderr, err := r.check("combinedOutput", cmd)
49 // stdout also contains stderr
50 r.t.Fatalf("CombinedOutput: stderr != nil, but %v", stderr)
54 func (r *testRunner) check(method string, cmd *exec.Cmd) (
55 []byte, []byte, error) {
58 if len(r.expCmds) == 0 {
59 r.t.Fatalf("%s: empty expCmds", method)
61 if len(r.resStdout) == 0 {
62 r.t.Fatalf("%s: empty resStdout", method)
64 if len(r.resStderr) == 0 {
65 r.t.Fatalf("%s: empty resStderr", method)
67 if len(r.resError) == 0 {
68 r.t.Fatalf("%s: empty resError", method)
72 r.expCmds = r.expCmds[1:]
73 if !reflect.DeepEqual(exp, cmd) {
74 opts := cmpopts.IgnoreUnexported(exec.Cmd{}, bytes.Buffer{})
75 r.t.Errorf("%s: %s", method, cmp.Diff(exp, cmd, opts))
78 var stdout, stderr []byte
81 stdout, r.resStdout = r.resStdout[0], r.resStdout[1:]
82 stderr, r.resStderr = r.resStderr[0], r.resStderr[1:]
83 err, r.resError = r.resError[0], r.resError[1:]
85 return stdout, stderr, err
88 type syncTestResult struct {
95 func prepareSync(req safcm.MsgSyncReq, runner *testRunner) (
96 *Sync, *syncTestResult) {
98 res := &syncTestResult{
99 ch: make(chan string),
109 res.dbg = append(res.dbg, x)
114 logger := log.NewLogger(func(level safcm.LogLevel, msg string) {
115 res.ch <- fmt.Sprintf("%d: %s", level, msg)
119 cmd: run.NewCmd(runner, logger),
124 func (s *syncTestResult) Wait() []string {
130 // All expected commands must have been executed
131 if len(s.runner.expCmds) != 0 {
132 s.runner.t.Errorf("expCmds left: %v", s.runner.expCmds)
134 if len(s.runner.resStdout) != 0 {
135 s.runner.t.Errorf("resStdout left: %v", s.runner.resStdout)
137 if len(s.runner.resStderr) != 0 {
138 s.runner.t.Errorf("resStderr left: %v", s.runner.resStderr)
140 if len(s.runner.resError) != 0 {
141 s.runner.t.Errorf("resError left: %v", s.runner.resError)