Debian Codegraph @

gopls/internal/golang/addtest.go

raw symbols SCIP
1 // Copyright 2019 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 golang
6
7 // This file defines the behavior of the "Add test for FUNC" command.
8
9 import (
10 "bytes"
11 "context"
12 "errors"
13 "fmt"
14 "go/ast"
15 "go/format"
16 "go/types"
17 "os"
18 "path/filepath"
19 "strconv"
20 "strings"
21 "text/template"
22 "unicode"
23
24 goastutil "golang.org/x/tools/go/ast/astutil"
25 "golang.org/x/tools/gopls/internal/cache"
26 "golang.org/x/tools/gopls/internal/cache/metadata"
27 "golang.org/x/tools/gopls/internal/cache/parsego"
28 "golang.org/x/tools/gopls/internal/protocol"
29 "golang.org/x/tools/gopls/internal/util/moremaps"
30 "golang.org/x/tools/internal/astutil"
31 "golang.org/x/tools/internal/imports"
32 "golang.org/x/tools/internal/typesinternal"
33 "golang.org/x/tools/internal/versions"
34 )
35
36 const testTmplString = `
37 func {{.TestFuncName}}(t *{{.TestingPackageName}}.T) {
38 {{- /* Test cases struct declaration and empty initialization. */}}
39 tests := []struct {
40 name string // description of this test case
41
42 {{- $commentPrinted := false }}
43 {{- if and .Receiver .Receiver.Constructor}}
44 {{- range .Receiver.Constructor.Args}}
45 {{- if .Name}}
46 {{- if not $commentPrinted}}
47 // Named input parameters for receiver constructor.
48 {{- $commentPrinted = true }}
49 {{- end}}
50 {{.Name}} {{.Type}}
51 {{- end}}
52 {{- end}}
53 {{- end}}
54
55 {{- $commentPrinted := false }}
56 {{- range .Func.Args}}
57 {{- if .Name}}
58 {{- if not $commentPrinted}}
59 // Named input parameters for target function.
60 {{- $commentPrinted = true }}
61 {{- end}}
62 {{.Name}} {{.Type}}
63 {{- end}}
64 {{- end}}
65
66 {{- range $index, $res := .Func.Results}}
67 {{- if eq $res.Name "gotErr"}}
68 wantErr bool
69 {{- else if eq $index 0}}
70 want {{$res.Type}}
71 {{- else}}
72 want{{add $index 1}} {{$res.Type}}
73 {{- end}}
74 {{- end}}
75 }{
76 // TODO: Add test cases.
77 }
78
79 {{- /* Loop over all the test cases. */}}
80 for _, tt := range tests {
81 t.Run(tt.name, func(t *{{.TestingPackageName}}.T) {
82 {{- /* Constructor or empty initialization. */}}
83 {{- if .Receiver}}
84 {{- if .Receiver.Constructor}}
85 {{- /* Receiver variable by calling constructor. */}}
86 {{fieldNames .Receiver.Constructor.Results ""}} := {{if .PackageName}}{{.PackageName}}.{{end}}
87 {{- .Receiver.Constructor.Name}}
88
89 {{- /* Constructor input parameters. */ -}}
90 (
91 {{- range $index, $arg := .Receiver.Constructor.Args}}
92 {{- if ne $index 0}}, {{end}}
93 {{- if .Name}}tt.{{.Name}}{{else}}{{.Value}}{{end}}
94 {{- end -}}
95 {{- if and .Receiver.Constructor.IsVariadic (not .Receiver.Constructor.IsUnusedVariadic) }}...{{- end -}}
96 )
97
98 {{- /* Handles the error return from constructor. */}}
99 {{- $last := last .Receiver.Constructor.Results}}
100 {{- if eq $last.Type "error"}}
101 if err != nil {
102 t.Fatalf("could not construct receiver type: %v", err)
103 }
104 {{- end}}
105 {{- else}}
106 {{- /* Receiver variable declaration. */}}
107 // TODO: construct the receiver type.
108 var {{.Receiver.Var.Name}} {{.Receiver.Var.Type}}
109 {{- end}}
110 {{- end}}
111
112 {{- /* Got variables. */}}
113 {{if .Func.Results}}{{fieldNames .Func.Results ""}} := {{end}}
114
115 {{- /* Call expression. */}}
116 {{- if .Receiver}}{{/* Call method by VAR.METHOD. */}}
117 {{- .Receiver.Var.Name}}.
118 {{- else if .PackageName}}{{/* Call function by PACKAGE.FUNC. */}}
119 {{- .PackageName}}.
120 {{- end}}{{.Func.Name}}
121
122 {{- /* Input parameters. */ -}}
123 (
124 {{- range $index, $arg := .Func.Args}}
125 {{- if ne $index 0}}, {{end}}
126 {{- if .Name}}tt.{{.Name}}{{else}}{{.Value}}{{end}}
127 {{- end -}}
128 {{- if and .Func.IsVariadic (not .Func.IsUnusedVariadic) }}...{{- end -}}
129 )
130
131 {{- /* Handles the returned error before the rest of return value. */}}
132 {{- $last := last .Func.Results}}
133 {{- if eq $last.Type "error"}}
134 if gotErr != nil {
135 if !tt.wantErr {
136 t.Errorf("{{$.Func.Name}}() failed: %v", gotErr)
137 }
138 return
139 }
140 if tt.wantErr {
141 t.Fatal("{{$.Func.Name}}() succeeded unexpectedly")
142 }
143 {{- end}}
144
145 {{- /* Compare the returned values except for the last returned error. */}}
146 {{- if or (and .Func.Results (ne $last.Type "error")) (and (gt (len .Func.Results) 1) (eq $last.Type "error"))}}
147 // TODO: update the condition below to compare got with tt.want.
148 {{- range $index, $res := .Func.Results}}
149 {{- if ne $res.Name "gotErr"}}
150 if true {
151 t.Errorf("{{$.Func.Name}}() = %v, want %v", {{.Name}}, tt.{{if eq $index 0}}want{{else}}want{{add $index 1}}{{end}})
152 }
153 {{- end}}
154 {{- end}}
155 {{- end}}
156 })
157 }
158 }
159 `
160
161 // Name is the name of the field this input parameter should reference.
162 // Value is the expression this input parameter should accept.
163 //
164 // Exactly one of Name or Value must be set.
165 type field struct {
166 Name, Type, Value string
167 }
168
169 type function struct {
170 Name string
171 Args []field
172 Results []field
173 // IsVariadic holds information if the function is variadic.
174 // In case of the IsVariadic=true must expand it in the function-under-test call.
175 IsVariadic bool
176 // IsUnusedVariadic holds information if the function's variadic args is not used.
177 // In this case ... must be skipped.
178 IsUnusedVariadic bool
179 }
180
181 type receiver struct {
182 // Var is the name and type of the receiver variable.
183 Var field
184 // Constructor holds information about the constructor for the receiver type.
185 // If no qualified constructor is found, this field will be nil.
186 Constructor *function
187 }
188
189 type testInfo struct {
190 // TestingPackageName is the package name should be used when referencing
191 // package "testing"
192 TestingPackageName string
193 // PackageName is the package name the target function/method is declared from.
194 PackageName string
195 TestFuncName string
196 // Func holds information about the function or method being tested.
197 Func function
198 // Receiver holds information about the receiver of the function or method
199 // being tested.
200 // This field is nil for functions and non-nil for methods.
201 Receiver *receiver
202 }
203
204 var testTmpl = template.Must(template.New("test").Funcs(template.FuncMap{
205 "add": func(a, b int) int { return a + b },
206 "last": func(slice []field) field {
207 if len(slice) == 0 {
208 return field{}
209 }
210 return slice[len(slice)-1]
211 },
212 "fieldNames": func(fields []field, qualifier string) (res string) {
213 var names []string
214 for _, f := range fields {
215 names = append(names, qualifier+f.Name)
216 }
217 return strings.Join(names, ", ")
218 },
219 }).Parse(testTmplString))
220
221 // AddTestForFunc adds a test for the function enclosing the given input range.
222 // It creates a _test.go file if one does not already exist.
223 // It returns the required text edits and the predicted location of the new test
224 // function, which is only valid after the edits have been successfully applied.
225 func AddTestForFunc(ctx context.Context, snapshot *cache.Snapshot, loc protocol.Location) (changes []protocol.DocumentChange, show *protocol.Location, _ error) {
226 pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, loc.URI)
227 if err != nil {
228 return nil, nil, err
229 }
230
231 if metadata.IsCommandLineArguments(pkg.Metadata().ID) {
232 return nil, nil, fmt.Errorf("current file in command-line-arguments package")
233 }
234
235 if errors := pkg.ParseErrors(); len(errors) > 0 {
236 return nil, nil, fmt.Errorf("package has parse errors: %v", errors[0])
237 }
238 if errors := pkg.TypeErrors(); len(errors) > 0 {
239 return nil, nil, fmt.Errorf("package has type errors: %v", errors[0])
240 }
241
242 // All three maps map the path of an imported package to
243 // the local name if explicit or "" otherwise.
244 var (
245 fileImports map[string]string // imports in foo.go file
246 testImports map[string]string // imports in foo_test.go file
247 extraImports = make(map[string]string) // imports to add to test file
248 )
249
250 collectImports := func(file *ast.File) (map[string]string, error) {
251 imps := make(map[string]string)
252 for _, spec := range file.Imports {
253 // TODO(hxjiang): support dot imports.
254 if spec.Name != nil && spec.Name.Name == "." {
255 return nil, fmt.Errorf("\"add test for func\" does not support files containing dot imports")
256 }
257 path, err := strconv.Unquote(spec.Path.Value)
258 if err != nil {
259 return nil, err
260 }
261 if spec.Name != nil {
262 if spec.Name.Name == "_" {
263 continue
264 }
265 imps[path] = spec.Name.Name
266 } else {
267 imps[path] = ""
268 }
269 }
270 return imps, nil
271 }
272
273 // Collect all the imports from the x.go, keep track of the local package name.
274 if fileImports, err = collectImports(pgf.File); err != nil {
275 return nil, nil, err
276 }
277
278 testBase := strings.TrimSuffix(loc.URI.Base(), ".go") + "_test.go"
279 goTestFileURI := protocol.URIFromPath(filepath.Join(loc.URI.DirPath(), testBase))
280
281 testFH, err := snapshot.ReadFile(ctx, goTestFileURI)
282 if err != nil {
283 return nil, nil, err
284 }
285
286 // TODO(hxjiang): use a fresh name if the same test function name already
287 // exist.
288
289 var (
290 eofRange protocol.Range // empty selection at end of new file
291 // edits contains all the text edits to be applied to the test file.
292 edits []protocol.TextEdit
293 // xtest indicates whether the test file use package x or x_test.
294 // TODO(hxjiang): We can discuss the option to interpret the user's
295 // intention by which function they are selecting. Have one file for
296 // x_test package testing, one file for x package testing.
297 xtest = true
298 )
299
300 start, end, err := pgf.RangePos(loc.Range)
301 if err != nil {
302 return nil, nil, err
303 }
304
305 path, _ := goastutil.PathEnclosingInterval(pgf.File, start, end)
306 if len(path) < 2 {
307 return nil, nil, fmt.Errorf("no enclosing function")
308 }
309
310 decl, ok := path[len(path)-2].(*ast.FuncDecl)
311 if !ok {
312 return nil, nil, fmt.Errorf("no enclosing function")
313 }
314
315 fn := pkg.TypesInfo().Defs[decl.Name].(*types.Func)
316 sig := fn.Signature()
317
318 testPGF, err := snapshot.ParseGo(ctx, testFH, parsego.Header)
319 if err != nil {
320 if !errors.Is(err, os.ErrNotExist) {
321 return nil, nil, err
322 }
323 changes = append(changes, protocol.DocumentChangeCreate(goTestFileURI))
324
325 // header is the buffer containing the text to add to the beginning of the file.
326 var header bytes.Buffer
327
328 // If this test file was created by the gopls, add a copyright header and
329 // package decl based on the originating file.
330 // Search for something that looks like a copyright header, to replicate
331 // in the new file.
332 if c := CopyrightComment(pgf.File); c != nil {
333 text, err := pgf.NodeText(c)
334 if err != nil {
335 return nil, nil, err
336 }
337 header.Write(text)
338 // One empty line between copyright header and following.
339 header.WriteString("\n\n")
340 }
341
342 // If this test file was created by gopls, add build constraints
343 // matching the non-test file.
344 if c := buildConstraintComment(pgf.File); c != nil {
345 text, err := pgf.NodeText(c)
346 if err != nil {
347 return nil, nil, err
348 }
349 header.Write(text)
350 // One empty line between build constraint and following.
351 header.WriteString("\n\n")
352 }
353
354 // Determine if a new test file should use in-package test (package x)
355 // or external test (package x_test). If any of the function parameters
356 // reference an unexported object, we cannot write out test cases from
357 // an x_test package.
358 externalTestOK := func() bool {
359 if !fn.Exported() {
360 return false
361 }
362 if fn.Signature().Recv() != nil {
363 if _, ident, _ := astutil.UnpackRecv(decl.Recv.List[0].Type); ident == nil || !ident.IsExported() {
364 return false
365 }
366 }
367 refsUnexported := false
368 ast.Inspect(decl, func(n ast.Node) bool {
369 // The original function refs to an unexported object from the
370 // same package, so further inspection is unnecessary.
371 if refsUnexported {
372 return false
373 }
374 switch t := n.(type) {
375 case *ast.BlockStmt:
376 // Avoid inspect the function body.
377 return false
378 case *ast.Ident:
379 // Use test variant (package foo) if the function signature
380 // references any unexported objects (like types or
381 // constants) from the same package.
382 // Note: types.PkgName is excluded from this check as it's
383 // always defined in the same package.
384 if obj, ok := pkg.TypesInfo().Uses[t]; ok && !obj.Exported() && obj.Pkg() == pkg.Types() && !is[*types.PkgName](obj) {
385 refsUnexported = true
386 }
387 return false
388 default:
389 return true
390 }
391 })
392 return !refsUnexported
393 }
394
395 xtest = externalTestOK()
396 if xtest {
397 fmt.Fprintf(&header, "package %s_test\n", pkg.Types().Name())
398 } else {
399 fmt.Fprintf(&header, "package %s\n", pkg.Types().Name())
400 }
401
402 // Write the copyright and package decl to the beginning of the file.
403 edits = append(edits, protocol.TextEdit{
404 Range: protocol.Range{},
405 NewText: header.String(),
406 })
407 } else { // existing _test.go file.
408 file := testPGF.File
409 if !file.Name.NamePos.IsValid() {
410 return nil, nil, fmt.Errorf("missing package declaration")
411 }
412 switch file.Name.Name {
413 case pgf.File.Name.Name:
414 xtest = false
415 case pgf.File.Name.Name + "_test":
416 xtest = true
417 default:
418 return nil, nil, fmt.Errorf("invalid package declaration %q in test file %q", file.Name, testPGF)
419 }
420
421 eofRange, err = testPGF.PosRange(file.FileEnd, file.FileEnd)
422 if err != nil {
423 return nil, nil, err
424 }
425
426 // Collect all the imports from the foo_test.go.
427 if testImports, err = collectImports(file); err != nil {
428 return nil, nil, err
429 }
430 }
431
432 // qual qualifier determines the correct package name to use for a type in
433 // foo_test.go. It does this by:
434 // - Consult imports map from test file foo_test.go.
435 // - If not found, consult imports map from original file foo.go.
436 // If the package is not imported in test file foo_test.go, it is added to
437 // extraImports map.
438 qual := func(p *types.Package) string {
439 // References from an in-package test should not be qualified.
440 if !xtest && p == pkg.Types() {
441 return ""
442 }
443 // Prefer using the package name if already defined in foo_test.go
444 if local, ok := testImports[p.Path()]; ok {
445 if local != "" {
446 return local
447 } else {
448 return p.Name()
449 }
450 }
451 // TODO(hxjiang): we should consult the scope of the test package to
452 // ensure these new imports do not shadow any package-level names.
453 // Prefer the local import name (if any) used in the package under test.
454 if local, ok := fileImports[p.Path()]; ok && local != "" {
455 extraImports[p.Path()] = local
456 return local
457 }
458 // Fall back to the package name since there is no renaming.
459 extraImports[p.Path()] = ""
460 return p.Name()
461 }
462
463 if xtest {
464 // Reject if function/method is unexported.
465 if !fn.Exported() {
466 return nil, nil, fmt.Errorf("cannot add test of unexported function %s to external test package %s_test", decl.Name, pgf.File.Name)
467 }
468
469 // Reject if receiver is unexported.
470 if sig.Recv() != nil {
471 if _, ident, _ := astutil.UnpackRecv(decl.Recv.List[0].Type); ident == nil || !ident.IsExported() {
472 return nil, nil, fmt.Errorf("cannot add external test for method %s.%s as receiver type is not exported", ident.Name, decl.Name)
473 }
474 }
475 // TODO(hxjiang): reject if the any input parameter type is unexported.
476 // TODO(hxjiang): reject if any return value type is unexported. Explore
477 // the option to drop the return value if the type is unexported.
478 }
479
480 testName, err := testName(fn)
481 if err != nil {
482 return nil, nil, err
483 }
484
485 fileVersion := pkg.TypesInfo().FileVersions[pgf.File]
486
487 data := testInfo{
488 TestingPackageName: qual(types.NewPackage("testing", "testing")),
489 PackageName: qual(pkg.Types()),
490 TestFuncName: testName,
491 Func: function{
492 Name: fn.Name(),
493 IsVariadic: sig.Variadic(),
494 },
495 }
496
497 // populateArgs fills fn.Args from sig's parameters, applying the conventions
498 // used by the test-generation template:
499 // - a leading context.Context parameter becomes t.Context() (Go 1.24+) or
500 // context.Background() (older modules), gated by fileVersion;
501 // - an unused trailing variadic parameter is dropped and recorded via
502 // fn.IsUnusedVariadic;
503 // - other unused ("" or "_") parameters get a zero-value literal;
504 // - named parameters keep their name and type for use as a test-table field.
505 populateArgs := func(fn *function, sig *types.Signature) {
506 for i := range sig.Params().Len() {
507 param := sig.Params().At(i)
508 name, typ := param.Name(), param.Type()
509 var f field
510 switch {
511 case i == 0 && typesinternal.IsTypeNamed(typ, "context", "Context"):
512 if versions.AtLeast(fileVersion, versions.Go1_24) {
513 f.Value = "t.Context()"
514 } else {
515 f.Type = types.TypeString(typ, qual)
516 f.Value = qual(types.NewPackage("context", "context")) + ".Background()"
517 }
518 case name == "" || name == "_":
519 if fn.IsVariadic && i == sig.Params().Len()-1 {
520 // The last argument is the variadic argument, and it's not used in the function body,
521 // so we don't need to render it in the test case struct.
522 fn.IsUnusedVariadic = true
523 continue
524 }
525 f.Type = types.TypeString(typ, qual)
526 f.Value, _ = typesinternal.ZeroString(typ, qual)
527 default:
528 f.Type = types.TypeString(typ, qual)
529 f.Name = name
530 }
531 fn.Args = append(fn.Args, f)
532 }
533 }
534
535 populateArgs(&data.Func, sig)
536
537 for i := range sig.Results().Len() {
538 typ := sig.Results().At(i).Type()
539 var name string
540 if i == sig.Results().Len()-1 && types.Identical(typ, errorType) {
541 name = "gotErr"
542 } else if i == 0 {
543 name = "got"
544 } else {
545 name = fmt.Sprintf("got%d", i+1)
546 }
547 data.Func.Results = append(data.Func.Results, field{
548 Name: name,
549 Type: types.TypeString(typ, qual),
550 })
551 }
552
553 if sig.Recv() != nil {
554 // Find the preferred type for the receiver. We don't use
555 // typesinternal.ReceiverNamed here as we want to preserve aliases.
556 recvType := sig.Recv().Type()
557 if ptr, ok := recvType.(*types.Pointer); ok {
558 recvType = ptr.Elem()
559 }
560
561 t, ok := recvType.(typesinternal.NamedOrAlias)
562 if !ok {
563 return nil, nil, fmt.Errorf("the receiver type is neither named type nor alias type")
564 }
565
566 var varName string
567 {
568 var possibleNames []string // list of candidates, preferring earlier entries.
569 if len(sig.Recv().Name()) > 0 {
570 possibleNames = append(possibleNames,
571 sig.Recv().Name(), // receiver name.
572 string(sig.Recv().Name()[0]), // first character of receiver name.
573 )
574 }
575 possibleNames = append(possibleNames,
576 string(t.Obj().Name()[0]), // first character of receiver type name.
577 )
578 if len(t.Obj().Name()) >= 2 {
579 possibleNames = append(possibleNames,
580 string(t.Obj().Name()[:2]), // first two character of receiver type name.
581 )
582 }
583 var camelCase []rune
584 for i, s := range t.Obj().Name() {
585 if i == 0 || unicode.IsUpper(s) {
586 camelCase = append(camelCase, s)
587 }
588 }
589 possibleNames = append(possibleNames,
590 string(camelCase), // captalized initials.
591 )
592 for _, name := range possibleNames {
593 name = strings.ToLower(name)
594 if name == "" || name == "t" || name == "tt" {
595 continue
596 }
597 varName = name
598 break
599 }
600 if varName == "" {
601 varName = "r" // default as "r" for "receiver".
602 }
603 }
604
605 data.Receiver = &receiver{
606 Var: field{
607 Name: varName,
608 Type: types.TypeString(recvType, qual),
609 },
610 }
611
612 // constructor is the selected constructor for type T.
613 var constructor *types.Func
614
615 // When finding the qualified constructor, the function should return the
616 // any type whose named type is the same type as T's named type.
617 _, wantType := typesinternal.ReceiverNamed(sig.Recv())
618 for _, name := range pkg.Types().Scope().Names() {
619 f, ok := pkg.Types().Scope().Lookup(name).(*types.Func)
620 if !ok {
621 continue
622 }
623 if f.Signature().Recv() != nil {
624 continue
625 }
626 // Unexported constructor is not visible in x_test package.
627 if xtest && !f.Exported() {
628 continue
629 }
630 // Only allow constructors returning T, T, (T, error), or (T, error).
631 if f.Signature().Results().Len() > 2 || f.Signature().Results().Len() == 0 {
632 continue
633 }
634
635 _, gotType := typesinternal.ReceiverNamed(f.Signature().Results().At(0))
636 if gotType == nil || !types.Identical(gotType, wantType) {
637 continue
638 }
639
640 if f.Signature().Results().Len() == 2 && !types.Identical(f.Signature().Results().At(1).Type(), errorType) {
641 continue
642 }
643
644 if constructor == nil {
645 constructor = f
646 }
647
648 // Functions named NewType are prioritized as constructors over other
649 // functions that match only the signature criteria.
650 if strings.EqualFold(strings.ToLower(f.Name()), strings.ToLower("new"+t.Obj().Name())) {
651 constructor = f
652 }
653 }
654
655 if constructor != nil {
656 data.Receiver.Constructor = &function{
657 Name: constructor.Name(),
658 IsVariadic: constructor.Signature().Variadic(),
659 }
660 populateArgs(data.Receiver.Constructor, constructor.Signature())
661 for i := range constructor.Signature().Results().Len() {
662 typ := constructor.Signature().Results().At(i).Type()
663 var name string
664 if i == 0 {
665 // The first return value must be of type T, *T, or a type whose named
666 // type is the same as named type of T.
667 name = varName
668 } else if i == constructor.Signature().Results().Len()-1 && types.Identical(typ, errorType) {
669 name = "err"
670 } else {
671 // Drop any return values beyond the first and the last.
672 // e.g., "f, _, _, err := NewFoo()".
673 name = "_"
674 }
675 data.Receiver.Constructor.Results = append(data.Receiver.Constructor.Results, field{
676 Name: name,
677 Type: types.TypeString(typ, qual),
678 })
679 }
680 }
681 }
682
683 // Resolves duplicate parameter names between the function and its
684 // receiver's constructor. It adds prefix to the constructor's parameters
685 // until no conflicts remain.
686 if data.Receiver != nil && data.Receiver.Constructor != nil {
687 seen := map[string]bool{}
688 for _, f := range data.Func.Args {
689 if f.Name == "" {
690 continue
691 }
692 seen[f.Name] = true
693 }
694
695 // "" for no change, "c" for constructor, "i" for input.
696 for _, prefix := range []string{"", "c", "c_", "i", "i_"} {
697 conflict := false
698 for _, f := range data.Receiver.Constructor.Args {
699 if f.Name == "" {
700 continue
701 }
702 if seen[prefix+f.Name] {
703 conflict = true
704 break
705 }
706 }
707 if !conflict {
708 for i, f := range data.Receiver.Constructor.Args {
709 if f.Name == "" {
710 continue
711 }
712 data.Receiver.Constructor.Args[i].Name = prefix + data.Receiver.Constructor.Args[i].Name
713 }
714 break
715 }
716 }
717 }
718
719 // Compute edits to update imports.
720 //
721 // If we're adding to an existing test file, we need to adjust existing
722 // imports. Otherwise, we can simply write out the imports to the new file.
723 if testPGF != nil {
724 var importFixes []*imports.ImportFix
725 for path, name := range extraImports {
726 importFixes = append(importFixes, &imports.ImportFix{
727 StmtInfo: imports.ImportInfo{
728 ImportPath: path,
729 Name: name,
730 },
731 FixType: imports.AddImport,
732 })
733 }
734 importEdits, err := ComputeImportFixEdits(snapshot.Options().Local, testPGF.Src, importFixes...)
735 if err != nil {
736 return nil, nil, fmt.Errorf("could not compute the import fix edits: %w", err)
737 }
738 edits = append(edits, importEdits...)
739 } else {
740 var importsBuffer bytes.Buffer
741 if len(extraImports) == 1 {
742 importsBuffer.WriteString("\nimport ")
743 for path, name := range extraImports {
744 if name != "" {
745 importsBuffer.WriteString(name + " ")
746 }
747 importsBuffer.WriteString(fmt.Sprintf("\"%s\"\n", path))
748 }
749 } else {
750 importsBuffer.WriteString("\nimport(")
751 // Sort for determinism.
752 for path, name := range moremaps.Sorted(extraImports) {
753 importsBuffer.WriteString("\n\t")
754 if name != "" {
755 importsBuffer.WriteString(name + " ")
756 }
757 importsBuffer.WriteString(fmt.Sprintf("\"%s\"", path))
758 }
759 importsBuffer.WriteString("\n)\n")
760 }
761 edits = append(edits, protocol.TextEdit{
762 Range: protocol.Range{},
763 NewText: importsBuffer.String(),
764 })
765 }
766
767 var test bytes.Buffer
768 if err := testTmpl.Execute(&test, data); err != nil {
769 return nil, nil, err
770 }
771
772 formatted, err := format.Source(test.Bytes())
773 if err != nil {
774 return nil, nil, err
775 }
776
777 edits = append(edits,
778 protocol.TextEdit{
779 Range: eofRange,
780 NewText: string(formatted),
781 },
782 )
783
784 // Show the line of generated test function.
785 {
786 line := eofRange.Start.Line
787 for i := range len(edits) - 1 { // last edits is the func decl
788 e := edits[i]
789 oldLines := e.Range.End.Line - e.Range.Start.Line
790 newLines := uint32(strings.Count(e.NewText, "\n"))
791 line += (newLines - oldLines)
792 }
793 show = &protocol.Location{
794 URI: testFH.URI(),
795 Range: protocol.Range{
796 // Test function template have a new line at beginning.
797 Start: protocol.Position{Line: line + 1},
798 End: protocol.Position{Line: line + 1},
799 },
800 }
801 }
802
803 return append(changes, protocol.DocumentChangeEdit(testFH, edits)), show, nil
804 }
805
806 // testName returns the name of the function to use for the new function that
807 // tests fn.
808 // Returns empty string if the fn is ill typed or nil.
809 func testName(fn *types.Func) (string, error) {
810 if fn == nil {
811 return "", fmt.Errorf("input nil function")
812 }
813 testName := "Test"
814 if recv := fn.Signature().Recv(); recv != nil { // method declaration.
815 // Retrieve the unpointered receiver type to ensure the test name is based
816 // on the topmost alias or named type, not the alias' RHS type (potentially
817 // unexported) type.
818 // For example:
819 // type Foo = foo // Foo is an exported alias for the unexported type foo
820 recvType := recv.Type()
821 if ptr, ok := recv.Type().(*types.Pointer); ok {
822 recvType = ptr.Elem()
823 }
824
825 t, ok := recvType.(typesinternal.NamedOrAlias)
826 if !ok {
827 return "", fmt.Errorf("receiver type is not named type or alias type")
828 }
829
830 if !t.Obj().Exported() {
831 testName += "_"
832 }
833
834 testName += t.Obj().Name() + "_"
835 } else if !fn.Exported() { // unexported function declaration.
836 testName += "_"
837 }
838 return testName + fn.Name(), nil
839 }