Source file src/internal/analysis/gotestchecker/driver_test.go

     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 gotestchecker_test
     6  
     7  import (
     8  	"encoding/json"
     9  	"go/analysis"
    10  	"go/ast"
    11  	"go/types"
    12  	"internal/testenv"
    13  	"os"
    14  	"path/filepath"
    15  	"runtime"
    16  	"strings"
    17  	"testing"
    18  
    19  	"internal/analysis/gotestchecker"
    20  	"internal/analysis/gotestchecker/protocol"
    21  )
    22  
    23  // toolEnv is the environment variable that causes the test binary to
    24  // act as an analysis tool containing the variables of toolVars.
    25  const toolEnv = "GOTESTCHECKER_TEST_TOOL"
    26  
    27  const toolSymbol = "example.com/special.Analyzer"
    28  
    29  var toolVars = []gotestchecker.Var{{Symbol: toolSymbol, Value: specialAnalyzer}}
    30  
    31  func TestMain(m *testing.M) {
    32  	if os.Getenv(toolEnv) != "" {
    33  		gotestchecker.Main(toolVars)
    34  		os.Exit(0)
    35  	}
    36  	os.Exit(m.Run())
    37  }
    38  
    39  // TestRun executes the driver as the go command would, without the
    40  // go command: it runs the test binary as the analysis tool, first to
    41  // query the metadata, then to analyze two packages, lib and a (which
    42  // imports lib), using the results of the first (its export data and
    43  // facts) as inputs to the second.
    44  //
    45  // TODO(adonovan): turn this into a go script integration test when we can.
    46  func TestRun(t *testing.T) {
    47  	testenv.MustHaveExec(t)
    48  	dir := t.TempDir()
    49  	file := func(name string) string { return filepath.Join(dir, name) }
    50  	writeFile := func(name, content string) string {
    51  		t.Helper()
    52  		if err := os.WriteFile(file(name), []byte(content), 0666); err != nil {
    53  			t.Fatal(err)
    54  		}
    55  		return file(name)
    56  	}
    57  
    58  	// tool runs the analysis tool with the specified arguments.
    59  	tool := func(args ...string) {
    60  		t.Helper()
    61  		cmd := testenv.Command(t, testenv.Executable(t), args...)
    62  		cmd.Env = append(os.Environ(), toolEnv+"=1")
    63  		if out, err := cmd.CombinedOutput(); err != nil {
    64  			t.Fatalf("%v failed: %v\n%s", cmd, err, out)
    65  		}
    66  	}
    67  
    68  	// Query the metadata for the analyzer's index.
    69  	tool("-describe=" + file("metadata.json"))
    70  	data, err := os.ReadFile(file("metadata.json"))
    71  	if err != nil {
    72  		t.Fatal(err)
    73  	}
    74  	var md protocol.Metadata
    75  	if err := json.Unmarshal(data, &md); err != nil {
    76  		t.Fatal(err)
    77  	}
    78  	info := md.Var(toolSymbol)
    79  	if info == nil || info.Error != "" || len(info.Members) != 1 {
    80  		t.Fatalf("metadata for %s: %+v", toolSymbol, info)
    81  	}
    82  	special := info.Members[0].Analyzer
    83  	if a := md.Analyzers[special]; a.Name != "special" || !a.Facts {
    84  		t.Fatalf("analyzer %d: got %+v, want special, which uses facts", special, a)
    85  	}
    86  
    87  	// analyze runs the tool on the package described by req,
    88  	// and returns the pass of the special analyzer.
    89  	analyze := func(req *protocol.AnalyzeRequest) *protocol.Pass {
    90  		t.Helper()
    91  		data, err := json.Marshal(req)
    92  		if err != nil {
    93  			t.Fatal(err)
    94  		}
    95  		tool(writeFile(req.ID+".json", string(data)))
    96  		pass, err := protocol.ReadPass(req.Outputs[special])
    97  		if err != nil {
    98  			t.Fatal(err)
    99  		}
   100  		if pass.Failure != nil || pass.Skipped {
   101  			t.Fatalf("%s: pass failed (%v) or was skipped (%t)", req.ID, pass.Failure, pass.Skipped)
   102  		}
   103  		return pass
   104  	}
   105  
   106  	// Analyze lib, whose diagnostics are not reported,
   107  	// for its export data and facts.
   108  	libPass := analyze(&protocol.AnalyzeRequest{
   109  		ID:          "lib",
   110  		ImportPath:  "lib",
   111  		Dir:         dir,
   112  		GoFiles:     {writeFile("lib.go", "package lib\n\nfunc SpecialF() {}\n\nfunc G() { SpecialF() }\n")},
   113  		GoVersion:   "go1.28",
   114  		GOARCH:      runtime.GOARCH,
   115  		TypeImports: {},
   116  		TypeExport:  file("lib.export"),
   117  		Facts:       {},
   118  		Outputs:     {special: file("lib.pass")},
   119  	})
   120  	if len(libPass.Facts) == 0 {
   121  		t.Errorf("lib: no facts")
   122  	}
   123  	if len(libPass.Diagnostics) > 0 {
   124  		t.Errorf("lib: unexpected diagnostics: %v", libPass.Diagnostics)
   125  	}
   126  
   127  	// Analyze a, using the results of lib.
   128  	aPass := analyze(&protocol.AnalyzeRequest{
   129  		ID:          "a",
   130  		ImportPath:  "a",
   131  		Dir:         dir,
   132  		GoFiles:     {writeFile("a.go", "package a\n\nimport \"lib\"\n\nfunc f() {\n\tlib.SpecialF()\n\tlib.G()\n}\n")},
   133  		ImportMap:   {"lib": "lib"},
   134  		GoVersion:   "go1.28",
   135  		GOARCH:      runtime.GOARCH,
   136  		TypeImports: {"lib": file("lib.export")},
   137  		Facts:       {special: {"lib": file("lib.pass")}},
   138  		Outputs:     {special: file("a.pass")},
   139  		Report:      {special},
   140  	})
   141  	if len(aPass.Diagnostics) != 1 {
   142  		t.Fatalf("a: got diagnostics %v, want one", aPass.Diagnostics)
   143  	}
   144  	d := aPass.Diagnostics[0]
   145  	if want := "call of special function lib.SpecialF"; d.Message != want {
   146  		t.Errorf("a: got diagnostic %q, want %q", d.Message, want)
   147  	}
   148  	if want := "a.go:6:2"; !strings.HasSuffix(d.Posn, want) {
   149  		t.Errorf("a: got diagnostic at %s, want %s", d.Posn, want)
   150  	}
   151  }
   152  
   153  // specialAnalyzer reports calls of functions whose names start with
   154  // "Special", using facts to identify such functions in other packages.
   155  var specialAnalyzer = &analysis.Analyzer{
   156  	Name:      "special",
   157  	Doc:       "report calls of special functions",
   158  	FactTypes: []analysis.Fact{new(isSpecial)},
   159  	Run: func(pass *analysis.Pass) (any, error) {
   160  		for _, f := range pass.Files {
   161  			for _, decl := range f.Decls {
   162  				if decl, ok := decl.(*ast.FuncDecl); ok && strings.HasPrefix(decl.Name.Name, "Special") {
   163  					pass.ExportObjectFact(pass.TypesInfo.Defs[decl.Name], &isSpecial{true})
   164  				}
   165  			}
   166  		}
   167  		for _, f := range pass.Files {
   168  			ast.Inspect(f, func(n ast.Node) bool {
   169  				if sel, ok := n.(*ast.SelectorExpr); ok {
   170  					if fn, ok := pass.TypesInfo.Uses[sel.Sel].(*types.Func); ok && pass.ImportObjectFact(fn, new(isSpecial)) {
   171  						pass.ReportRangef(sel, "call of special function %s.%s", fn.Pkg().Name(), fn.Name())
   172  					}
   173  				}
   174  				return true
   175  			})
   176  		}
   177  		return nil, nil
   178  	},
   179  }
   180  
   181  // An isSpecial fact marks a special function.
   182  type isSpecial struct{ Special bool } // (gob requires an exported field)
   183  
   184  func (*isSpecial) AFact() {}
   185  

View as plain text