| 1 | // Copyright 2026 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 excfg |
| 6 | |
| 7 | import ( |
| 8 | "bytes" |
| 9 | "flag" |
| 10 | "go/ast" |
| 11 | "go/parser" |
| 12 | "go/token" |
| 13 | "os" |
| 14 | "path/filepath" |
| 15 | "strings" |
| 16 | "testing" |
| 17 | |
| 18 | "golang.org/x/tools/go/cfg" |
| 19 | "golang.org/x/tools/txtar" |
| 20 | ) |
| 21 | |
| 22 | var update = flag.Bool("update", false, "update expected output") |
| 23 | |
| 24 | func TestExCFG(t *testing.T) { |
| 25 | files, err := filepath.Glob("testdata/*.txt") |
| 26 | if err != nil { |
| 27 | t.Fatal(err) |
| 28 | } |
| 29 | if len(files) == 0 { |
| 30 | t.Fatal("no test files found in testdata/") |
| 31 | } |
| 32 | |
| 33 | for _, file := range files { |
| 34 | t.Run(filepath.Base(file), func(t *testing.T) { |
| 35 | data, err := os.ReadFile(file) |
| 36 | if err != nil { |
| 37 | t.Fatal(err) |
| 38 | } |
| 39 | ar := txtar.Parse(data) |
| 40 | var src, want []byte |
| 41 | for _, f := range ar.Files { |
| 42 | switch f.Name { |
| 43 | case "src.go": |
| 44 | src = f.Data |
| 45 | case "want": |
| 46 | want = bytes.TrimSpace(f.Data) |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | if src == nil { |
| 51 | t.Fatal("missing src.go in test file") |
| 52 | } |
| 53 | |
| 54 | fset := token.NewFileSet() |
| 55 | f, err := parser.ParseFile(fset, "src.go", src, 0) |
| 56 | if err != nil { |
| 57 | t.Fatal(err) |
| 58 | } |
| 59 | |
| 60 | // Find function body. |
| 61 | var body *ast.BlockStmt |
| 62 | for _, decl := range f.Decls { |
| 63 | if fd, ok := decl.(*ast.FuncDecl); ok && fd.Name.Name == "main" { |
| 64 | body = fd.Body |
| 65 | break |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | if body == nil { |
| 70 | t.Fatal("no main function found") |
| 71 | } |
| 72 | |
| 73 | c := cfg.New(body, func(call *ast.CallExpr) bool { return true }) |
| 74 | ec := New(c, fset) |
| 75 | got := strings.TrimSpace(ec.String()) |
| 76 | |
| 77 | if *update { |
| 78 | found := false |
| 79 | for i := range ar.Files { |
| 80 | if ar.Files[i].Name == "want" { |
| 81 | ar.Files[i].Data = []byte(got) |
| 82 | found = true |
| 83 | break |
| 84 | } |
| 85 | } |
| 86 | if !found { |
| 87 | ar.Files = append(ar.Files, txtar.File{ |
| 88 | Name: "want", |
| 89 | Data: []byte(got), |
| 90 | }) |
| 91 | } |
| 92 | if err := os.WriteFile(file, txtar.Format(ar), 0644); err != nil { |
| 93 | t.Fatal(err) |
| 94 | } |
| 95 | return |
| 96 | } |
| 97 | |
| 98 | if want == nil { |
| 99 | t.Logf("Output for %s:\n%s", file, got) |
| 100 | t.Errorf("missing expected output") |
| 101 | } else if got != string(want) { |
| 102 | t.Errorf("mismatch:\ngot:\n%s\nwant:\n%s", got, want) |
| 103 | } |
| 104 | }) |
| 105 | } |
| 106 | } |