Debian Codegraph @

internal/astutil/fields_test.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 package astutil_test
5
6 import (
7 "bytes"
8 "fmt"
9 "go/ast"
10 "go/parser"
11 "go/token"
12 "go/types"
13 "testing"
14
15 "golang.org/x/tools/internal/astutil"
16 )
17
18 func TestFlatFields(t *testing.T) {
19 tests := []struct {
20 params string
21 want string
22 }{
23 {"", ""},
24 {"a int", "a int"},
25 {"int", "int"},
26 {"a, b int", "a int, b int"},
27 {"a, b, c int", "a int, b int, c int"},
28 {"int, string", "int, string"},
29 {"_ int, b string", "_ int, b string"},
30 {"a, _ int, b string", "a int, _ int, b string"},
31 }
32
33 for _, test := range tests {
34 src := fmt.Sprintf("package p; func _(%s)", test.params)
35 f, err := parser.ParseFile(token.NewFileSet(), "", src, 0)
36 if err != nil {
37 t.Fatal(err)
38 }
39 params := f.Decls[0].(*ast.FuncDecl).Type.Params
40 var got bytes.Buffer
41 for name, field := range astutil.FlatFields(params) {
42 if got.Len() > 0 {
43 got.WriteString(", ")
44 }
45 if name != nil {
46 fmt.Fprintf(&got, "%s ", name.Name)
47 }
48 got.WriteString(types.ExprString(field.Type))
49 }
50 if got := got.String(); got != test.want {
51 // align 'got' and 'want' for easier inspection
52 t.Errorf("FlatFields(%q):\n got: %q\nwant: %q", test.params, got, test.want)
53 }
54 }
55 }