github.com/golangci/go-tools@v0.0.0-20190318060251-af6baa5dc196/ssa/ssautil/load_test.go (about) 1 // Copyright 2015 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 ssautil_test 6 7 import ( 8 "go/ast" 9 "go/importer" 10 "go/parser" 11 "go/token" 12 "go/types" 13 "os" 14 "testing" 15 16 "github.com/golangci/go-tools/ssa/ssautil" 17 ) 18 19 const hello = `package main 20 21 import "fmt" 22 23 func main() { 24 fmt.Println("Hello, world") 25 } 26 ` 27 28 func TestBuildPackage(t *testing.T) { 29 // There is a more substantial test of BuildPackage and the 30 // SSA program it builds in ../ssa/builder_test.go. 31 32 fset := token.NewFileSet() 33 f, err := parser.ParseFile(fset, "hello.go", hello, 0) 34 if err != nil { 35 t.Fatal(err) 36 } 37 38 pkg := types.NewPackage("hello", "") 39 ssapkg, _, err := ssautil.BuildPackage(&types.Config{Importer: importer.Default()}, fset, pkg, []*ast.File{f}, 0) 40 if err != nil { 41 t.Fatal(err) 42 } 43 if pkg.Name() != "main" { 44 t.Errorf("pkg.Name() = %s, want main", pkg.Name()) 45 } 46 if ssapkg.Func("main") == nil { 47 ssapkg.WriteTo(os.Stderr) 48 t.Errorf("ssapkg has no main function") 49 } 50 } 51 52 func TestBuildPackage_MissingImport(t *testing.T) { 53 fset := token.NewFileSet() 54 f, err := parser.ParseFile(fset, "bad.go", `package bad; import "missing"`, 0) 55 if err != nil { 56 t.Fatal(err) 57 } 58 59 pkg := types.NewPackage("bad", "") 60 ssapkg, _, err := ssautil.BuildPackage(new(types.Config), fset, pkg, []*ast.File{f}, 0) 61 if err == nil || ssapkg != nil { 62 t.Fatal("BuildPackage succeeded unexpectedly") 63 } 64 }