Debian Codegraph @

testdata/yaml-test-suite/yaml.go

raw symbols SCIP
1 package yamltestsuite
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "io/fs"
9 "os"
10 "path/filepath"
11 "runtime"
12 "sort"
13 "strings"
14 )
15
16 type TestSuite struct {
17 Name string
18 InYAML []byte
19 InJSON []any
20 OutYAML []byte
21 Error bool
22 }
23
24 func curDir() string {
25 _, file, _, _ := runtime.Caller(0) //nolint:dogsled
26 return filepath.Dir(file)
27 }
28
29 func TestSuites() ([]*TestSuite, error) {
30 dir := curDir()
31 testMap := make(map[string]*TestSuite)
32 if err := filepath.Walk(dir, func(path string, info fs.FileInfo, err error) error {
33 if strings.HasSuffix(path, ".go") {
34 // this file.
35 return nil
36 }
37 if info.IsDir() {
38 return nil
39 }
40 if err != nil {
41 return err
42 }
43 name := strings.TrimPrefix(path, dir+"/")
44 name = strings.TrimSuffix(name, "/"+filepath.Base(name))
45 if _, exists := testMap[name]; !exists {
46 testMap[name] = &TestSuite{}
47 }
48 f, err := os.ReadFile(path)
49 if err != nil {
50 return err
51 }
52 fileName := filepath.Base(path)
53 switch fileName {
54 case "in.yaml":
55 testMap[name].InYAML = f
56 case "in.json":
57 dec := json.NewDecoder(bytes.NewReader(f))
58 var inJSON []any
59 for {
60 var v any
61 if err := dec.Decode(&v); err != nil {
62 if err == io.EOF {
63 break
64 }
65 return fmt.Errorf("failed to decode json: %s: %s: %w", name, string(f), err)
66 }
67 inJSON = append(inJSON, v)
68 }
69 testMap[name].InJSON = inJSON
70 case "out.yaml":
71 testMap[name].OutYAML = f
72 case "error":
73 testMap[name].Error = true
74 }
75 testMap[name].Name = name
76 return nil
77 }); err != nil {
78 return nil, err
79 }
80
81 tests := make([]*TestSuite, 0, len(testMap))
82 for _, test := range testMap {
83 if test.InYAML == nil {
84 continue
85 }
86 tests = append(tests, test)
87 }
88 sort.Slice(tests, func(i, j int) bool {
89 return tests[i].Name < tests[j].Name
90 })
91 return tests, nil
92 }