golang.org/x/tools@v0.21.1-0.20240520172518-788d39e776b1/internal/versions/types_test.go (about) 1 // Copyright 2023 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 versions_test 6 7 import ( 8 "fmt" 9 "go/ast" 10 "go/importer" 11 "go/parser" 12 "go/token" 13 "go/types" 14 "testing" 15 16 "golang.org/x/tools/internal/testenv" 17 "golang.org/x/tools/internal/versions" 18 ) 19 20 func Test(t *testing.T) { 21 testenv.NeedsGo1Point(t, 22) 22 23 var contents = map[string]string{ 24 "gobuild.go": ` 25 //go:build go1.23 26 package p 27 `, 28 "noversion.go": ` 29 package p 30 `, 31 } 32 type fileTest struct { 33 fname string 34 want string 35 } 36 for _, item := range []struct { 37 goversion string 38 pversion string 39 tests []fileTest 40 }{ 41 {"", "", []fileTest{{"noversion.go", ""}, {"gobuild.go", ""}}}, 42 {"go1.22", "go1.22", []fileTest{{"noversion.go", "go1.22"}, {"gobuild.go", "go1.23"}}}, 43 } { 44 name := fmt.Sprintf("types.Config{GoVersion:%q}", item.goversion) 45 t.Run(name, func(t *testing.T) { 46 fset := token.NewFileSet() 47 files := make([]*ast.File, len(item.tests)) 48 for i, test := range item.tests { 49 files[i] = parse(t, fset, test.fname, contents[test.fname]) 50 } 51 pkg, info := typeCheck(t, fset, files, item.goversion) 52 if got, want := versions.GoVersion(pkg), item.pversion; versions.Compare(got, want) != 0 { 53 t.Errorf("GoVersion()=%q. expected %q", got, want) 54 } 55 if got := versions.FileVersion(info, nil); got != "" { 56 t.Errorf(`FileVersions(nil)=%q. expected ""`, got) 57 } 58 for i, test := range item.tests { 59 if got, want := versions.FileVersion(info, files[i]), test.want; got != want { 60 t.Errorf("FileVersions(%s)=%q. expected %q", test.fname, got, want) 61 } 62 } 63 }) 64 } 65 } 66 67 func parse(t *testing.T, fset *token.FileSet, name, src string) *ast.File { 68 file, err := parser.ParseFile(fset, name, src, 0) 69 if err != nil { 70 t.Fatal(err) 71 } 72 return file 73 } 74 75 func typeCheck(t *testing.T, fset *token.FileSet, files []*ast.File, goversion string) (*types.Package, *types.Info) { 76 conf := types.Config{ 77 Importer: importer.Default(), 78 GoVersion: goversion, 79 } 80 info := types.Info{} 81 versions.InitFileVersions(&info) 82 pkg, err := conf.Check("", fset, files, &info) 83 if err != nil { 84 t.Fatal(err) 85 } 86 return pkg, &info 87 }