Skip to content

Commit b09f061

Browse files
committed
test(utils): Add test for GetStructNameForField
Adds a new test case for the `GetStructNameForField` utility function. This test uses the `analysistest` package to run a dedicated analyzer over a test data file, ensuring the function correctly identifies the parent struct for a given field.
1 parent 9127bf1 commit b09f061

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package getstructname
2+
3+
type MyStruct1 struct {
4+
Field1 string // want "field Field1 is in struct MyStruct1"
5+
Field2 int // want "field Field2 is in struct MyStruct1"
6+
}
7+
8+
type MyStruct2 struct {
9+
AnotherField bool // want "field AnotherField is in struct MyStruct2"
10+
}

pkg/analysis/utils/utils_test.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ import (
2020

2121
. "github.com/onsi/ginkgo/v2"
2222
. "github.com/onsi/gomega"
23+
"golang.org/x/tools/go/analysis"
24+
"golang.org/x/tools/go/analysis/analysistest"
25+
"golang.org/x/tools/go/analysis/passes/inspect"
26+
"golang.org/x/tools/go/ast/inspector"
2327

2428
"sigs.k8s.io/kube-api-linter/pkg/analysis/utils"
2529
)
@@ -73,3 +77,45 @@ var _ = Describe("FieldName", func() {
7377
}),
7478
)
7579
})
80+
81+
var _ = Describe("GetStructNameForField", func() {
82+
It("should find the correct struct name for a field", func() {
83+
testdata := analysistest.TestData()
84+
analysistest.Run(GinkgoT(), testdata, testGetStructNameAnalyzer(), "getstructname")
85+
})
86+
})
87+
88+
func testGetStructNameAnalyzer() *analysis.Analyzer {
89+
return &analysis.Analyzer{
90+
Name: "testgetstructname",
91+
Doc: "test analyzer for GetStructNameForField",
92+
Requires: []*analysis.Analyzer{inspect.Analyzer},
93+
Run: func(pass *analysis.Pass) (any, error) {
94+
inspect, ok := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
95+
if !ok {
96+
return nil, errCouldNotGetInspector
97+
}
98+
99+
nodeFilter := []ast.Node{
100+
(*ast.Field)(nil),
101+
}
102+
103+
inspect.Preorder(nodeFilter, func(n ast.Node) {
104+
field, ok := n.(*ast.Field)
105+
if !ok {
106+
return
107+
}
108+
if len(field.Names) == 0 {
109+
return
110+
}
111+
112+
structName := utils.GetStructNameForField(pass, field)
113+
if structName != "" {
114+
pass.Reportf(field.Pos(), "field %s is in struct %s", field.Names[0].Name, structName)
115+
}
116+
})
117+
118+
return nil, nil
119+
},
120+
}
121+
}

0 commit comments

Comments
 (0)