@@ -960,6 +960,81 @@ func TestImplicitsInfo(t *testing.T) {
960
960
}
961
961
}
962
962
963
+ func TestPkgNameOf (t * testing.T ) {
964
+ testenv .MustHaveGoBuild (t )
965
+
966
+ const src = `
967
+ package p
968
+
969
+ import (
970
+ . "os"
971
+ _ "io"
972
+ "math"
973
+ "path/filepath"
974
+ snort "sort"
975
+ )
976
+
977
+ // avoid imported and not used errors
978
+ var (
979
+ _ = Open // os.Open
980
+ _ = math.Sin
981
+ _ = filepath.Abs
982
+ _ = snort.Ints
983
+ )
984
+ `
985
+
986
+ var tests = []struct {
987
+ path string // path string enclosed in "'s
988
+ want string
989
+ }{
990
+ {`"os"` , "." },
991
+ {`"io"` , "_" },
992
+ {`"math"` , "math" },
993
+ {`"path/filepath"` , "filepath" },
994
+ {`"sort"` , "snort" },
995
+ }
996
+
997
+ fset := token .NewFileSet ()
998
+ f := mustParse (fset , src )
999
+ info := Info {
1000
+ Defs : make (map [* ast.Ident ]Object ),
1001
+ Implicits : make (map [ast.Node ]Object ),
1002
+ }
1003
+ var conf Config
1004
+ conf .Importer = importer .Default ()
1005
+ _ , err := conf .Check ("p" , fset , []* ast.File {f }, & info )
1006
+ if err != nil {
1007
+ t .Fatal (err )
1008
+ }
1009
+
1010
+ // map import paths to importDecl
1011
+ imports := make (map [string ]* ast.ImportSpec )
1012
+ for _ , s := range f .Decls [0 ].(* ast.GenDecl ).Specs {
1013
+ if imp , _ := s .(* ast.ImportSpec ); imp != nil {
1014
+ imports [imp .Path .Value ] = imp
1015
+ }
1016
+ }
1017
+
1018
+ for _ , test := range tests {
1019
+ imp := imports [test .path ]
1020
+ if imp == nil {
1021
+ t .Fatalf ("invalid test case: import path %s not found" , test .path )
1022
+ }
1023
+ got := info .PkgNameOf (imp )
1024
+ if got == nil {
1025
+ t .Fatalf ("import %s: package name not found" , test .path )
1026
+ }
1027
+ if got .Name () != test .want {
1028
+ t .Errorf ("import %s: got %s; want %s" , test .path , got .Name (), test .want )
1029
+ }
1030
+ }
1031
+
1032
+ // test non-existing importDecl
1033
+ if got := info .PkgNameOf (new (ast.ImportSpec )); got != nil {
1034
+ t .Errorf ("got %s for non-existing import declaration" , got .Name ())
1035
+ }
1036
+ }
1037
+
963
1038
func predString (tv TypeAndValue ) string {
964
1039
var buf strings.Builder
965
1040
pred := func (b bool , s string ) {
0 commit comments