Debian Codegraph @

gopls/internal/cache/testfuncs/tests.go

raw symbols SCIP
1 // Copyright 2024 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package testfuncs
6
7 import (
8 "go/ast"
9 "go/constant"
10 "go/types"
11 "strings"
12 "unicode"
13 "unicode/utf8"
14
15 "golang.org/x/tools/gopls/internal/cache/parsego"
16 "golang.org/x/tools/gopls/internal/protocol"
17 "golang.org/x/tools/gopls/internal/util/frob"
18 "golang.org/x/tools/gopls/internal/util/safetoken"
19 )
20
21 // An Index records the test set of a package.
22 type Index struct {
23 pkg gobPackage
24 }
25
26 // Decode decodes the given gob-encoded data as an Index.
27 func Decode(data []byte) *Index {
28 return &Index{packageCodec.Decode(data)}
29 }
30
31 // Encode encodes the receiver as gob-encoded data.
32 func (index *Index) Encode() []byte {
33 return packageCodec.Encode(index.pkg)
34 }
35
36 func (index *Index) All() []Result {
37 var results []Result
38 for _, file := range index.pkg.Files {
39 for _, test := range file.Tests {
40 results = append(results, test.result())
41 }
42 }
43 return results
44 }
45
46 // A Result reports a test function
47 type Result struct {
48 Location protocol.Location // location of the test
49 Name string // name of the test
50 }
51
52 // NewIndex returns a new index of method-set information for all
53 // package-level types in the specified package.
54 func NewIndex(files []*parsego.File, info *types.Info) *Index {
55 b := &indexBuilder{
56 fileIndex: make(map[protocol.DocumentURI]int),
57 subNames: make(map[string]int),
58 visited: make(map[*types.Func]bool),
59 }
60 return b.build(files, info)
61 }
62
63 // build adds to the index all tests of the specified package.
64 func (b *indexBuilder) build(files []*parsego.File, info *types.Info) *Index {
65 for _, file := range files {
66 if !strings.HasSuffix(file.Tok.Name(), "_test.go") {
67 continue
68 }
69
70 for _, decl := range file.File.Decls {
71 decl, ok := decl.(*ast.FuncDecl)
72 if !ok {
73 continue
74 }
75 obj, ok := info.ObjectOf(decl.Name).(*types.Func)
76 if !ok || !obj.Exported() {
77 continue
78 }
79
80 // error.Error has empty Position, PkgPath, and ObjectPath.
81 if obj.Pkg() == nil {
82 continue
83 }
84
85 isTest, isExample := isTestOrExample(obj)
86 if !isTest && !isExample {
87 continue
88 }
89
90 var t gobTest
91 t.Name = decl.Name.Name
92 t.Location.URI = file.URI
93 t.Location.Range, _ = file.NodeRange(decl)
94
95 i, ok := b.fileIndex[t.Location.URI]
96 if !ok {
97 i = len(b.Files)
98 b.Files = append(b.Files, gobFile{})
99 b.fileIndex[t.Location.URI] = i
100 }
101
102 b.Files[i].Tests = append(b.Files[i].Tests, t)
103 b.visited[obj] = true
104
105 // Check for subtests
106 if isTest {
107 b.Files[i].Tests = append(b.Files[i].Tests, b.findSubtests(t, decl.Type, decl.Body, file, files, info)...)
108 }
109 }
110 }
111
112 return &Index{pkg: b.gobPackage}
113 }
114
115 func (b *indexBuilder) findSubtests(parent gobTest, typ *ast.FuncType, body *ast.BlockStmt, file *parsego.File, files []*parsego.File, info *types.Info) []gobTest {
116 if body == nil {
117 return nil
118 }
119
120 // If the [testing.T] parameter is unnamed, the func cannot call
121 // [testing.T.Run] and thus cannot create any subtests
122 if len(typ.Params.List[0].Names) == 0 {
123 return nil
124 }
125
126 // This "can't fail" because testKind should guarantee that the function has
127 // one parameter and the check above guarantees that parameter is named
128 param := info.ObjectOf(typ.Params.List[0].Names[0])
129
130 // Find statements of form t.Run(name, func(...) {...}) where t is the
131 // parameter of the enclosing test function.
132 var tests []gobTest
133 for _, stmt := range body.List {
134 expr, ok := stmt.(*ast.ExprStmt)
135 if !ok {
136 continue
137 }
138
139 call, ok := expr.X.(*ast.CallExpr)
140 if !ok || len(call.Args) != 2 {
141 continue
142 }
143 fun, ok := call.Fun.(*ast.SelectorExpr)
144 if !ok || fun.Sel.Name != "Run" {
145 continue
146 }
147 recv, ok := fun.X.(*ast.Ident)
148 if !ok || info.ObjectOf(recv) != param {
149 continue
150 }
151
152 sig, ok := info.TypeOf(call.Args[1]).(*types.Signature)
153 if !ok {
154 continue
155 }
156 if _, ok := testKind(sig); !ok {
157 continue // subtest has wrong signature
158 }
159
160 val := info.Types[call.Args[0]].Value // may be zero
161 if val == nil || val.Kind() != constant.String {
162 continue
163 }
164
165 var t gobTest
166 t.Name = b.uniqueName(parent.Name, rewrite(constant.StringVal(val)))
167 t.Location.URI = file.URI
168 t.Location.Range, _ = file.NodeRange(call)
169 tests = append(tests, t)
170
171 fn, typ, body := findFunc(files, info, body, call.Args[1])
172 if typ == nil {
173 continue
174 }
175
176 // Function literals don't have an associated object
177 if fn == nil {
178 tests = append(tests, b.findSubtests(t, typ, body, file, files, info)...)
179 continue
180 }
181
182 // Never recurse if the second argument is a top-level test function
183 if isTest, _ := isTestOrExample(fn); isTest {
184 continue
185 }
186
187 // Don't recurse into functions that have already been visited
188 if b.visited[fn] {
189 continue
190 }
191
192 b.visited[fn] = true
193 tests = append(tests, b.findSubtests(t, typ, body, file, files, info)...)
194 }
195 return tests
196 }
197
198 // findFunc finds the type and body of the given expr, which may be a function
199 // literal or reference to a declared function. If the expression is a declared
200 // function, findFunc returns its [types.Func]. If the expression is a function
201 // literal, findFunc returns nil for the first return value. If no function is
202 // found, findFunc returns (nil, nil, nil).
203 func findFunc(files []*parsego.File, info *types.Info, body *ast.BlockStmt, expr ast.Expr) (*types.Func, *ast.FuncType, *ast.BlockStmt) {
204 var obj types.Object
205 switch arg := expr.(type) {
206 case *ast.FuncLit:
207 return nil, arg.Type, arg.Body
208
209 case *ast.Ident:
210 obj = info.ObjectOf(arg)
211 if obj == nil {
212 return nil, nil, nil
213 }
214
215 case *ast.SelectorExpr:
216 // Look for methods within the current package. We will not handle
217 // imported functions and methods for now, as that would require access
218 // to the source of other packages and would be substantially more
219 // complex. However, those cases should be rare.
220 sel, ok := info.Selections[arg]
221 if !ok {
222 return nil, nil, nil
223 }
224 obj = sel.Obj()
225
226 default:
227 return nil, nil, nil
228 }
229
230 if v, ok := obj.(*types.Var); ok {
231 // TODO: Handle vars. This could handled by walking over the body (and
232 // the file), but that doesn't account for assignment. If the variable
233 // is assigned multiple times, we could easily get the wrong one.
234 _, _ = v, body
235 return nil, nil, nil
236 }
237
238 for _, file := range files {
239 // Skip files that don't contain the object (there should only be a
240 // single file that _does_ contain it)
241 if _, err := safetoken.Offset(file.Tok, obj.Pos()); err != nil {
242 continue
243 }
244
245 for _, decl := range file.File.Decls {
246 decl, ok := decl.(*ast.FuncDecl)
247 if !ok {
248 continue
249 }
250
251 if info.ObjectOf(decl.Name) == obj {
252 return obj.(*types.Func), decl.Type, decl.Body
253 }
254 }
255 }
256 return nil, nil, nil
257 }
258
259 // isTestOrExample reports whether the given func is a testing func or an
260 // example func (or neither). isTestOrExample returns (true, false) for testing
261 // funcs, (false, true) for example funcs, and (false, false) otherwise.
262 func isTestOrExample(fn *types.Func) (isTest, isExample bool) {
263 sig := fn.Type().(*types.Signature)
264 if sig.Params().Len() == 0 &&
265 sig.Results().Len() == 0 {
266 return false, isTestName(fn.Name(), "Example")
267 }
268
269 kind, ok := testKind(sig)
270 if !ok {
271 return false, false
272 }
273 switch kind.Name() {
274 case "T":
275 return isTestName(fn.Name(), "Test"), false
276 case "B":
277 return isTestName(fn.Name(), "Benchmark"), false
278 case "F":
279 return isTestName(fn.Name(), "Fuzz"), false
280 default:
281 return false, false // "can't happen" (see testKind)
282 }
283 }
284
285 // isTestName reports whether name is a valid test name for the test kind
286 // indicated by the given prefix ("Test", "Benchmark", etc.).
287 //
288 // Adapted from go/analysis/passes/tests.
289 func isTestName(name, prefix string) bool {
290 suffix, ok := strings.CutPrefix(name, prefix)
291 if !ok {
292 return false
293 }
294 if len(suffix) == 0 {
295 // "Test" is ok.
296 return true
297 }
298 r, _ := utf8.DecodeRuneInString(suffix)
299 return !unicode.IsLower(r)
300 }
301
302 // testKind returns the parameter type TypeName of a test, benchmark, or fuzz
303 // function (one of testing.[TBF]).
304 func testKind(sig *types.Signature) (*types.TypeName, bool) {
305 if sig.Params().Len() != 1 ||
306 sig.Results().Len() != 0 {
307 return nil, false
308 }
309
310 ptr, ok := sig.Params().At(0).Type().(*types.Pointer)
311 if !ok {
312 return nil, false
313 }
314
315 named, ok := ptr.Elem().(*types.Named)
316 if !ok || named.Obj().Pkg() == nil || named.Obj().Pkg().Path() != "testing" {
317 return nil, false
318 }
319
320 switch named.Obj().Name() {
321 case "T", "B", "F":
322 return named.Obj(), true
323 }
324 return nil, false
325 }
326
327 // An indexBuilder builds an index for a single package.
328 type indexBuilder struct {
329 gobPackage
330 fileIndex map[protocol.DocumentURI]int
331 subNames map[string]int
332 visited map[*types.Func]bool
333 }
334
335 // -- serial format of index --
336
337 // (The name says gob but in fact we use frob.)
338 var packageCodec = frob.CodecFor[gobPackage]()
339
340 // A gobPackage records the test set of each package-level type for a single package.
341 type gobPackage struct {
342 Files []gobFile
343 }
344
345 type gobFile struct {
346 Tests []gobTest
347 }
348
349 // A gobTest records the name, type, and position of a single test.
350 type gobTest struct {
351 Location protocol.Location // location of the test
352 Name string // name of the test
353 }
354
355 func (t *gobTest) result() Result {
356 return Result(*t)
357 }