-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrules_test.go
98 lines (88 loc) · 2.34 KB
/
rules_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
package rules
import (
"go/ast"
"go/parser"
"go/token"
"path/filepath"
"strings"
"testing"
"github.com/nobl9/govy/internal"
)
func TestRules_EnsureTestsAndBenchmarksAreWritten(t *testing.T) {
// Functions that should be excluded from this test.
// It's easier to list them here rather than complicate the AST traversal.
excludeFuncs := map[string]bool{
"HashFuncSelf": true,
"CompareFunc": true,
"CompareDeepEqualFunc": true,
}
rulesDir := filepath.Join(internal.FindModuleRoot(), "pkg/rules")
fset := token.NewFileSet()
// Parse the directory
pkgs, err := parser.ParseDir(fset, rulesDir, nil, parser.ParseComments)
if err != nil {
t.Fatalf("Failed to parse directory: %v", err)
}
exportedFuncs := make(map[string]struct{})
testFuncs := make(map[string]bool)
benchmarkFuncs := make(map[string]bool)
// Collect exported functions
for _, pkg := range pkgs {
for fileName, file := range pkg.Files {
if strings.HasSuffix(fileName, "_test.go") {
continue
}
ast.Inspect(file, func(n ast.Node) bool {
fn, ok := n.(*ast.FuncDecl)
if !ok {
return true
}
if excludeFuncs[fn.Name.Name] || !fn.Name.IsExported() || fn.Recv != nil {
return false
}
exportedFuncs[fn.Name.Name] = struct{}{}
return false
})
}
}
// Collect test and benchmark functions
for _, pkg := range pkgs {
for fileName, file := range pkg.Files {
if !strings.HasSuffix(fileName, "_test.go") {
continue
}
ast.Inspect(file, func(n ast.Node) bool {
if fn, ok := n.(*ast.FuncDecl); ok {
if strings.HasPrefix(fn.Name.Name, "Test") {
testFuncs[fn.Name.Name] = true
} else if strings.HasPrefix(fn.Name.Name, "Benchmark") {
benchmarkFuncs[fn.Name.Name] = true
}
}
return true
})
}
}
// Check for corresponding test and benchmark functions
for funcName := range exportedFuncs {
testName := "Test" + funcName
benchmarkName := "Benchmark" + funcName
if !mapContainsString(testFuncs, testName) {
t.Errorf("Missing test function for %s", funcName)
}
if !mapContainsString(benchmarkFuncs, benchmarkName) {
t.Errorf("Missing benchmark function for %s", funcName)
}
}
}
func mapContainsString(m map[string]bool, s string) bool {
if _, ok := m[s]; ok {
return true
}
for k := range m {
if strings.Contains(k, s) {
return true
}
}
return false
}