forked from losisin/helm-values-schema-json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_test.go
116 lines (103 loc) · 2.49 KB
/
main_test.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"bytes"
"io"
"log"
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func TestMain(t *testing.T) {
tests := []struct {
name string
args []string
setup func()
cleanup func()
expectedError string
expectedOut string
}{
{
name: "HelpFlag",
args: []string{"schema", "-h"},
expectedOut: "Usage of schema",
expectedError: "",
},
{
name: "InvalidFlags",
args: []string{"schema", "-fail"},
expectedOut: "",
expectedError: "flag provided but not defined",
},
{
name: "SuccessfulRun",
args: []string{"schema", "-input", "testdata/basic.yaml"},
expectedOut: "JSON schema successfully generated",
expectedError: "",
},
{
name: "GenerateError",
args: []string{"schema", "-input", "fail.yaml", "-draft", "2020"},
expectedOut: "error reading YAML file(s)",
expectedError: "",
},
{
name: "ErrorLoadingConfigFile",
args: []string{"schema", "-input", "testdata/basic.yaml"},
setup: func() {
if _, err := os.Stat(".schema.yaml"); err == nil {
if err := os.Rename(".schema.yaml", ".schema.yaml.bak"); err != nil {
log.Fatalf("Error renaming file: %v", err)
}
}
file, _ := os.Create(".schema.yaml")
defer file.Close()
if _, err := file.WriteString("draft: invalid\n"); err != nil {
log.Fatalf("Error writing to file: %v", err)
}
},
cleanup: func() {
if _, err := os.Stat(".schema.yaml.bak"); err == nil {
os.Remove(".schema.yaml")
if err := os.Rename(".schema.yaml.bak", ".schema.yaml"); err != nil {
log.Fatalf("Error renaming file: %v", err)
}
} else {
os.Remove(".schema.yaml")
}
},
expectedOut: "",
expectedError: "Error loading config file",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
originalArgs := os.Args
originalStdout := os.Stdout
if tt.setup != nil {
tt.setup()
}
if tt.cleanup != nil {
defer tt.cleanup()
}
r, w, _ := os.Pipe()
os.Stdout = w
os.Args = tt.args
go func() {
main()
w.Close()
}()
var buf bytes.Buffer
_, err := io.Copy(&buf, r)
if err != nil {
t.Errorf("Error reading stdout: %v", err)
}
os.Args = originalArgs
os.Stdout = originalStdout
out := buf.String()
assert.Contains(t, out, tt.expectedError)
if tt.expectedOut != "" {
assert.Contains(t, out, tt.expectedOut)
}
})
}
}