Source file src/internal/analysis/gotestchecker/facts_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/gob"
     9  	"fmt"
    10  	"go/ast"
    11  	"go/parser"
    12  	"go/token"
    13  	"go/types"
    14  	"reflect"
    15  	"slices"
    16  	"strings"
    17  	"testing"
    18  
    19  	"internal/analysis/gotestchecker"
    20  )
    21  
    22  type testFact struct{ N int }
    23  
    24  func (*testFact) AFact() {}
    25  
    26  func (f *testFact) String() string { return fmt.Sprintf("testFact(%d)", f.N) }
    27  
    28  // An ifaceFact is a fact with an interface-typed field.
    29  type ifaceFact struct{ V any }
    30  
    31  func (*ifaceFact) AFact() {}
    32  
    33  func (f *ifaceFact) String() string { return fmt.Sprintf("ifaceFact(%v)", f.V) }
    34  
    35  type ifaceValue struct{ N int }
    36  
    37  // TestFactsTwoHops checks the encoding of fact sets (see facts.go)
    38  // across two hops of the import graph, c -> b -> a: facts exported by
    39  // a, decoded by b, re-exported by b, and decoded by c; and the pruning
    40  // of facts that are not re-exported (package facts, and facts about
    41  // package-level non-type objects, of dependencies).
    42  //
    43  // TODO(adonovan): make a more systematic coverage of fact behavior
    44  // through the go script test mechanism, when we can.
    45  func TestFactsTwoHops(t *testing.T) {
    46  	gotestchecker.RegisterFactType(new(testFact))
    47  	gotestchecker.RegisterFactType(new(ifaceFact))
    48  	gob.Register(ifaceValue{})
    49  
    50  	// Type-check the packages from source.
    51  	fset := token.NewFileSet()
    52  	pkgs := make(map[string]*types.Package)
    53  	check := func(path, src string) *types.Package {
    54  		t.Helper()
    55  		f, err := parser.ParseFile(fset, path+".go", src, 0)
    56  		if err != nil {
    57  			t.Fatal(err)
    58  		}
    59  		conf := types.Config{Importer: importerFunc(func(path string) (*types.Package, error) {
    60  			return pkgs[path], nil
    61  		})}
    62  		pkg, err := conf.Check(path, fset, []*ast.File{f}, nil)
    63  		if err != nil {
    64  			t.Fatal(err)
    65  		}
    66  		pkgs[path] = pkg
    67  		return pkg
    68  	}
    69  	a := check("a", `package a; type T struct{ F int }; func (T) M() {}; func G() {}`)
    70  	b := check("b", `package b; import "a"; type U struct{ a.T }; func H() a.T { return a.T{} }`)
    71  	c := check("c", `package c; import "b"; var _ b.U`)
    72  
    73  	T := a.Scope().Lookup("T").(*types.TypeName)
    74  	F := T.Type().Underlying().(*types.Struct).Field(0)
    75  	M, _, _ := types.LookupFieldOrMethod(T.Type(), false, a, "M")
    76  	G := a.Scope().Lookup("G")
    77  	H := b.Scope().Lookup("H")
    78  	names := map[types.Object]string{T: "a.T", F: "a.T.F", M: "a.T.M", G: "a.G", H: "b.H"}
    79  
    80  	// decode returns the fact set of pkg, given the encoded fact
    81  	// sets of its imports.
    82  	decode := func(pkg *types.Package, imports map[string][]byte) *gotestchecker.FactSet {
    83  		t.Helper()
    84  		getPackage := func(path string) *types.Package { return pkgs[path] }
    85  		set, err := gotestchecker.DecodeFacts(pkg, getPackage, func(path string) ([]byte, error) {
    86  			return imports[path], nil
    87  		})
    88  		if err != nil {
    89  			t.Fatal(err)
    90  		}
    91  		return set
    92  	}
    93  
    94  	// encode encodes the fact set, and checks the numbers of facts
    95  	// about the package itself (own) and its dependencies (deps).
    96  	encode := func(set *gotestchecker.FactSet, wantOwn, wantDeps int) []byte {
    97  		t.Helper()
    98  		data, own, deps := set.Encode()
    99  		if own != wantOwn || deps != wantDeps {
   100  			t.Errorf("Encode: own=%d deps=%d, want %d, %d", own, deps, wantOwn, wantDeps)
   101  		}
   102  		return data
   103  	}
   104  
   105  	// want checks that the fact set contains exactly the facts
   106  	// described by want, one per line, in any order.
   107  	want := func(set *gotestchecker.FactSet, want string) {
   108  		t.Helper()
   109  		allTypes := map[reflect.Type]bool{
   110  			reflect.TypeFor[*testFact]():  true,
   111  			reflect.TypeFor[*ifaceFact](): true,
   112  		}
   113  		var got []string
   114  		for _, f := range set.AllObjectFacts(allTypes) {
   115  			got = append(got, fmt.Sprintf("%s: %v", names[f.Object], f.Fact))
   116  		}
   117  		for _, f := range set.AllPackageFacts(allTypes) {
   118  			got = append(got, fmt.Sprintf("package %s: %v", f.Package.Path(), f.Fact))
   119  		}
   120  		slices.Sort(got)
   121  		var wantLines []string
   122  		for line := range strings.Lines(want) {
   123  			if line := strings.TrimSpace(line); line != "" {
   124  				wantLines = append(wantLines, line)
   125  			}
   126  		}
   127  		slices.Sort(wantLines)
   128  		if !slices.Equal(got, wantLines) {
   129  			t.Errorf("got facts:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(wantLines, "\n"))
   130  		}
   131  	}
   132  
   133  	// Package a exports facts about its objects and itself.
   134  	setA := decode(a, nil)
   135  	setA.ExportObjectFact(T, &ifaceFact{V: ifaceValue{N: 1}})
   136  	setA.ExportObjectFact(F, &testFact{2})
   137  	setA.ExportObjectFact(M, &testFact{3})
   138  	setA.ExportObjectFact(G, &testFact{4})
   139  	setA.ExportPackageFact(&testFact{5})
   140  	dataA := encode(setA, 5, 0)
   141  
   142  	// Package b sees all of a's facts, and exports one of its own.
   143  	setB := decode(b, map[string][]byte{"a": dataA})
   144  	setB.ExportObjectFact(H, &testFact{6})
   145  	dataB := encode(setB, 1, 3)
   146  	want(setB, `
   147  		a.G: testFact(4)
   148  		a.T: ifaceFact({1})
   149  		a.T.F: testFact(2)
   150  		a.T.M: testFact(3)
   151  		b.H: testFact(6)
   152  		package a: testFact(5)`)
   153  
   154  	// Package c sees a's facts about types and their members
   155  	// (re-exported by b), and b's own, but not a's facts about
   156  	// other package-level objects, nor its package facts.
   157  	setC := decode(c, map[string][]byte{"b": dataB})
   158  	want(setC, `
   159  		a.T: ifaceFact({1})
   160  		a.T.F: testFact(2)
   161  		a.T.M: testFact(3)
   162  		b.H: testFact(6)`)
   163  }
   164  
   165  type importerFunc func(path string) (*types.Package, error)
   166  
   167  func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) }
   168  

View as plain text