Debian Codegraph @

cmd/go-yaml/cli_test.go

raw symbols SCIP
1 package main
2
3 import (
4 "bytes"
5 "fmt"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "strings"
10 "testing"
11
12 "go.yaml.in/yaml/v4"
13 )
14
15 // testBinary holds the path to the pre-built CLI binary for testing
16 var testBinary string
17
18 // TestMain builds the CLI binary once before running tests
19 func TestMain(m *testing.M) {
20 // Create a temporary directory for the test binary
21 tmpDir, err := os.MkdirTemp("", "go-yaml-test")
22 if err != nil {
23 fmt.Fprintf(os.Stderr, "Failed to create temp dir: %v\n", err)
24 os.Exit(1)
25 }
26
27 // Build the binary once
28 testBinary = filepath.Join(tmpDir, "go-yaml")
29 cmd := exec.Command("go", "build", "-o", testBinary, ".")
30 cmd.Stderr = os.Stderr
31 if err := cmd.Run(); err != nil {
32 fmt.Fprintf(os.Stderr, "Failed to build test binary: %v\n", err)
33 os.RemoveAll(tmpDir)
34 os.Exit(1)
35 }
36
37 // Run tests
38 code := m.Run()
39
40 // Cleanup before exit (defer won't run with os.Exit)
41 os.RemoveAll(tmpDir)
42 os.Exit(code)
43 }
44
45 // TestCase represents a single test case from a test file
46 type TestCase struct {
47 Name string `yaml:"name"`
48 Text string `yaml:"text"`
49 Token string `yaml:"token,omitempty"`
50 TOKEN string `yaml:"TOKEN,omitempty"`
51 Event string `yaml:"event,omitempty"`
52 EVENT string `yaml:"EVENT,omitempty"`
53 Node string `yaml:"node,omitempty"`
54 NODE string `yaml:"NODE,omitempty"`
55 Yaml string `yaml:"yaml,omitempty"`
56 YAML string `yaml:"YAML,omitempty"`
57 Json string `yaml:"json,omitempty"`
58 JSON string `yaml:"JSON,omitempty"`
59 // Option flags
60 V2Yaml string `yaml:"v2-yaml,omitempty"`
61 V3Yaml string `yaml:"v3-yaml,omitempty"`
62 Indent3Yaml string `yaml:"indent3-yaml,omitempty"`
63 Width40Yaml string `yaml:"width40-yaml,omitempty"`
64 CompactYaml string `yaml:"compact-yaml,omitempty"`
65 V3Indent2 string `yaml:"v3-indent2-yaml,omitempty"`
66 CanonicalYaml string `yaml:"canonical-yaml,omitempty"`
67 ExplicitYaml string `yaml:"explicit-yaml,omitempty"`
68 ExplicitStartYaml string `yaml:"explicit-start-yaml,omitempty"`
69 NoUnicodeYaml string `yaml:"no-unicode-yaml,omitempty"`
70 CanonicalExplicitYaml string `yaml:"canonical-explicit-yaml,omitempty"`
71 V2Indent4Yaml string `yaml:"v2-indent4-yaml,omitempty"`
72 // Stream option flags
73 StreamNode string `yaml:"stream-node,omitempty"`
74 StreamNODE string `yaml:"stream-NODE,omitempty"`
75 }
76
77 // TestSuite is a sequence of test cases
78 type TestSuite []TestCase
79
80 // flagMapping maps test file field names to CLI flags
81 var flagMapping = map[string]string{
82 "token": "-t",
83 "TOKEN": "-T",
84 "event": "-e",
85 "EVENT": "-E",
86 "node": "-n",
87 "NODE": "-N",
88 "yaml": "-y",
89 "YAML": "-Y",
90 "json": "-j",
91 "JSON": "-J",
92 "v2-yaml": "-o v2 -y",
93 "v3-yaml": "-o v3 -y",
94 "indent3-yaml": "-o indent=3 -y",
95 "width40-yaml": "-o width=40 -y",
96 "compact-yaml": "-o compact -y",
97 "v3-indent2-yaml": "-o v3,indent=2 -y",
98 "canonical-yaml": "-o canonical -y",
99 "explicit-yaml": "-o explicit -y",
100 "explicit-start-yaml": "-o explicit-start -y",
101 "no-unicode-yaml": "-o no-unicode -y",
102 "canonical-explicit-yaml": "-o canonical,explicit -y",
103 "v2-indent4-yaml": "-o v2,indent=4 -y",
104 "stream-node": "-o stream -n",
105 "stream-NODE": "-o stream -N",
106 }
107
108 func TestCLI(t *testing.T) {
109 // Find all test files in testdata/
110 testFiles, err := filepath.Glob(filepath.Join("testdata", "*.yaml"))
111 if err != nil {
112 t.Fatalf("Failed to find test files: %v", err)
113 }
114
115 if len(testFiles) == 0 {
116 t.Fatal("No test files found in testdata/")
117 }
118
119 // Process each test file
120 for _, testFile := range testFiles {
121 testFileName := filepath.Base(testFile)
122 t.Run(testFileName, func(t *testing.T) {
123 runTestFile(t, testFile)
124 })
125 }
126 }
127
128 func runTestFile(t *testing.T, testFile string) {
129 t.Helper()
130 // Read and parse the test file
131 data, err := os.ReadFile(testFile)
132 if err != nil {
133 t.Fatalf("Failed to read test file %s: %v", testFile, err)
134 }
135
136 var suite TestSuite
137 if err := yaml.Load(data, &suite); err != nil {
138 t.Fatalf("Failed to parse test file %s: %v", testFile, err)
139 }
140
141 // Run each test case
142 for _, testCase := range suite {
143 t.Run(testCase.Name, func(t *testing.T) {
144 runTestCase(t, testCase)
145 })
146 }
147 }
148
149 func runTestCase(t *testing.T, tc TestCase) {
150 t.Helper()
151 // Test each output format that has an expected value
152 tests := []struct {
153 field string
154 flag string
155 expected string
156 }{
157 {"token", flagMapping["token"], tc.Token},
158 {"TOKEN", flagMapping["TOKEN"], tc.TOKEN},
159 {"event", flagMapping["event"], tc.Event},
160 {"EVENT", flagMapping["EVENT"], tc.EVENT},
161 {"node", flagMapping["node"], tc.Node},
162 {"NODE", flagMapping["NODE"], tc.NODE},
163 {"yaml", flagMapping["yaml"], tc.Yaml},
164 {"YAML", flagMapping["YAML"], tc.YAML},
165 {"json", flagMapping["json"], tc.Json},
166 {"JSON", flagMapping["JSON"], tc.JSON},
167 {"v2-yaml", flagMapping["v2-yaml"], tc.V2Yaml},
168 {"v3-yaml", flagMapping["v3-yaml"], tc.V3Yaml},
169 {"indent3-yaml", flagMapping["indent3-yaml"], tc.Indent3Yaml},
170 {"width40-yaml", flagMapping["width40-yaml"], tc.Width40Yaml},
171 {"compact-yaml", flagMapping["compact-yaml"], tc.CompactYaml},
172 {"v3-indent2-yaml", flagMapping["v3-indent2-yaml"], tc.V3Indent2},
173 {"canonical-yaml", flagMapping["canonical-yaml"], tc.CanonicalYaml},
174 {"explicit-yaml", flagMapping["explicit-yaml"], tc.ExplicitYaml},
175 {"explicit-start-yaml", flagMapping["explicit-start-yaml"], tc.ExplicitStartYaml},
176 {"no-unicode-yaml", flagMapping["no-unicode-yaml"], tc.NoUnicodeYaml},
177 {"canonical-explicit-yaml", flagMapping["canonical-explicit-yaml"], tc.CanonicalExplicitYaml},
178 {"v2-indent4-yaml", flagMapping["v2-indent4-yaml"], tc.V2Indent4Yaml},
179 {"stream-node", flagMapping["stream-node"], tc.StreamNode},
180 {"stream-NODE", flagMapping["stream-NODE"], tc.StreamNODE},
181 }
182
183 for _, test := range tests {
184 if test.expected == "" {
185 continue // Skip if no expected output for this format
186 }
187
188 t.Run(test.field, func(t *testing.T) {
189 // Run the pre-built CLI binary
190 args := strings.Fields(test.flag)
191 cmd := exec.Command(testBinary, args...)
192 cmd.Stdin = strings.NewReader(tc.Text)
193
194 var stdout, stderr bytes.Buffer
195 cmd.Stdout = &stdout
196 cmd.Stderr = &stderr
197
198 if err := cmd.Run(); err != nil {
199 t.Fatalf("Command failed: %v\nStderr: %s", err, stderr.String())
200 }
201
202 // Normalize output for comparison
203 actual := normalizeOutput(stdout.String())
204 expected := normalizeOutput(test.expected)
205
206 if actual != expected {
207 t.Errorf("Output mismatch for flag %s\nExpected:\n%s\n\nActual:\n%s\n\nDiff:\n%s",
208 test.flag, expected, actual, diff(expected, actual))
209 }
210 })
211 }
212 }
213
214 // normalizeOutput trims whitespace and ensures consistent line endings
215 func normalizeOutput(s string) string {
216 s = strings.TrimSpace(s)
217 s = strings.ReplaceAll(s, "\r\n", "\n")
218 return s
219 }
220
221 // CmdTestCase represents a command-based test case
222 type CmdTestCase struct {
223 Name string `yaml:"name"`
224 Cmd string `yaml:"cmd"`
225 Out string `yaml:"out"`
226 }
227
228 // CmdTestSuite is a sequence of command test cases
229 type CmdTestSuite []CmdTestCase
230
231 // TestCLICommands runs command-based tests from testdata/cmd/*.yaml
232 func TestCLICommands(t *testing.T) {
233 // Find all test files in testdata/cmd/
234 testFiles, err := filepath.Glob(filepath.Join("testdata", "cmd", "*.yaml"))
235 if err != nil {
236 t.Fatalf("Failed to find test files: %v", err)
237 }
238
239 if len(testFiles) == 0 {
240 t.Fatal("No command test files found in testdata/cmd/")
241 }
242
243 // Process each test file
244 for _, testFile := range testFiles {
245 testFileName := filepath.Base(testFile)
246 t.Run(testFileName, func(t *testing.T) {
247 runCmdTestFile(t, testFile)
248 })
249 }
250 }
251
252 func runCmdTestFile(t *testing.T, testFile string) {
253 t.Helper()
254 // Read and parse the test file
255 data, err := os.ReadFile(testFile)
256 if err != nil {
257 t.Fatalf("Failed to read test file %s: %v", testFile, err)
258 }
259
260 var suite CmdTestSuite
261 if err := yaml.Load(data, &suite); err != nil {
262 t.Fatalf("Failed to parse test file %s: %v", testFile, err)
263 }
264
265 // Run each test case
266 for _, tc := range suite {
267 t.Run(tc.Name, func(t *testing.T) {
268 runCmdTestCase(t, tc)
269 })
270 }
271 }
272
273 func runCmdTestCase(t *testing.T, tc CmdTestCase) {
274 t.Helper()
275
276 // Replace "go-yaml" with actual test binary path in the command
277 cmdStr := strings.Replace(tc.Cmd, "go-yaml", testBinary, 1)
278
279 // Run the command through bash to handle pipes, heredocs, etc.
280 cmd := exec.Command("bash", "-c", cmdStr)
281
282 var stdout, stderr bytes.Buffer
283 cmd.Stdout = &stdout
284 cmd.Stderr = &stderr
285
286 if err := cmd.Run(); err != nil {
287 t.Fatalf("Command failed: %v\nCommand: %s\nStderr: %s", err, tc.Cmd, stderr.String())
288 }
289
290 // Normalize output for comparison
291 actual := normalizeOutput(stdout.String())
292 expected := normalizeOutput(tc.Out)
293
294 if actual != expected {
295 t.Errorf("Output mismatch\nCommand: %s\nExpected:\n%s\n\nActual:\n%s\n\nDiff:\n%s",
296 tc.Cmd, expected, actual, diff(expected, actual))
297 }
298 }
299
300 // diff provides a simple diff output for debugging
301 func diff(expected, actual string) string {
302 expLines := strings.Split(expected, "\n")
303 actLines := strings.Split(actual, "\n")
304
305 maxLines := len(expLines)
306 if len(actLines) > maxLines {
307 maxLines = len(actLines)
308 }
309
310 var result strings.Builder
311 for i := 0; i < maxLines; i++ {
312 expLine := ""
313 actLine := ""
314
315 if i < len(expLines) {
316 expLine = expLines[i]
317 }
318 if i < len(actLines) {
319 actLine = actLines[i]
320 }
321
322 if expLine != actLine {
323 fmt.Fprintf(&result, "Line %d:\n", i+1)
324 if expLine != "" {
325 result.WriteString("- ")
326 result.WriteString(expLine)
327 result.WriteString("\n")
328 }
329 if actLine != "" {
330 result.WriteString("+ ")
331 result.WriteString(actLine)
332 result.WriteString("\n")
333 }
334 }
335 }
336
337 return result.String()
338 }