/
cli_testsuite.go
48 lines (40 loc) · 1.02 KB
/
cli_testsuite.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
Copyright © 2023 David Aparicio david.aparicio@free.fr
*/
package internal
import (
"bytes"
"testing"
"github.com/spf13/cobra"
)
type Test struct {
Title string
Cmd *cobra.Command
Args []string
ExpectedStdout string
}
func ExecuteSuite(t *testing.T, tests []Test) {
// fatal error: concurrent map read and map write
// github.com/spf13/pflag.(*FlagSet).lookup(...)
// t.Parallel()
for _, test := range tests {
t.Run(test.Title, func(t *testing.T) {
output := &bytes.Buffer{}
test.Cmd.SetOut(output) // https://stackoverflow.com/a/66804032
test.Cmd.SetArgs(test.Args)
err := test.Cmd.Execute()
if !IsNil(err) {
t.Errorf("Unexpected error while executing command: %v", err)
}
if !IsEqualString(test.ExpectedStdout, output.String()) {
t.Errorf("Unexpected Stdout\ngot:\n%s\nexpected:\n%s\n", output.String(), test.ExpectedStdout)
}
})
}
}
func IsEqualString(s1, s2 string) bool {
return s1 == s2
}
func IsNil(object any) bool {
return object == nil
}