github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/codegen/loaderx/comment_scanner_test.go (about) 1 package loaderx 2 3 import ( 4 "go/ast" 5 "go/parser" 6 "go/token" 7 "io/ioutil" 8 "strings" 9 "testing" 10 11 "github.com/stretchr/testify/assert" 12 ) 13 14 func getDocTextOfNode(node ast.Node) string { 15 var doc *ast.CommentGroup 16 17 switch node.(type) { 18 case *ast.File: 19 doc = node.(*ast.File).Doc 20 case *ast.GenDecl: 21 doc = node.(*ast.GenDecl).Doc 22 case *ast.FuncDecl: 23 doc = node.(*ast.FuncDecl).Doc 24 case *ast.Field: 25 doc = node.(*ast.Field).Doc 26 case *ast.ImportSpec: 27 doc = node.(*ast.ImportSpec).Doc 28 case *ast.TypeSpec: 29 doc = node.(*ast.TypeSpec).Doc 30 case *ast.ValueSpec: 31 doc = node.(*ast.ValueSpec).Doc 32 } 33 34 if doc != nil { 35 return strings.TrimSpace(doc.Text()) 36 } 37 return "" 38 } 39 40 func TestCommentScanner(t *testing.T) { 41 tt := assert.New(t) 42 43 fileContent, _ := ioutil.ReadFile("./fixtures/comments.go") 44 fset := token.NewFileSet() 45 file, _ := parser.ParseFile(fset, "./fixtures/comments.go", string(fileContent), parser.ParseComments) 46 commentScanner := NewCommentScanner(fset, file) 47 48 ast.Inspect(file, func(node ast.Node) bool { 49 comments := commentScanner.CommentsOf(node) 50 51 switch node.(type) { 52 case *ast.File, *ast.Field, ast.Decl: 53 tt.Equal(getDocTextOfNode(node), comments) 54 case *ast.ImportSpec: 55 c := getDocTextOfNode(node) 56 if c == "" { 57 c = "import" 58 } 59 tt.Equal(c, comments) 60 case *ast.TypeSpec: 61 c := getDocTextOfNode(node) 62 if c == "" { 63 c = "type" 64 } 65 tt.Equal(c, comments) 66 case *ast.ValueSpec: 67 c := getDocTextOfNode(node) 68 if c == "" { 69 c = "var" 70 } 71 tt.Equal(c, comments) 72 case ast.Stmt: 73 commentGroupList := commentScanner.CommentMap[node] 74 tt.Equal(StringifyCommentGroup(commentGroupList...), comments) 75 } 76 return true 77 }) 78 }