github.com/flyinox/gosm@v0.0.0-20171117061539-16768cb62077/src/go/ast/filter_test.go (about) 1 // Copyright 2013 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 // To avoid a cyclic dependency with go/parser, this file is in a separate package. 6 7 package ast_test 8 9 import ( 10 "bytes" 11 "go/ast" 12 "go/format" 13 "go/parser" 14 "go/token" 15 "testing" 16 ) 17 18 const input = `package p 19 20 type t1 struct{} 21 type t2 struct{} 22 23 func f1() {} 24 func f1() {} 25 func f2() {} 26 27 func (*t1) f1() {} 28 func (t1) f1() {} 29 func (t1) f2() {} 30 31 func (t2) f1() {} 32 func (t2) f2() {} 33 func (x *t2) f2() {} 34 ` 35 36 // Calling ast.MergePackageFiles with ast.FilterFuncDuplicates 37 // keeps a duplicate entry with attached documentation in favor 38 // of one without, and it favors duplicate entries appearing 39 // later in the source over ones appearing earlier. This is why 40 // (*t2).f2 is kept and t2.f2 is eliminated in this test case. 41 // 42 const golden = `package p 43 44 type t1 struct{} 45 type t2 struct{} 46 47 func f1() {} 48 func f2() {} 49 50 func (t1) f1() {} 51 func (t1) f2() {} 52 53 func (t2) f1() {} 54 55 func (x *t2) f2() {} 56 ` 57 58 func TestFilterDuplicates(t *testing.T) { 59 // parse input 60 fset := token.NewFileSet() 61 file, err := parser.ParseFile(fset, "", input, 0) 62 if err != nil { 63 t.Fatal(err) 64 } 65 66 // create package 67 files := map[string]*ast.File{"": file} 68 pkg, err := ast.NewPackage(fset, files, nil, nil) 69 if err != nil { 70 t.Fatal(err) 71 } 72 73 // filter 74 merged := ast.MergePackageFiles(pkg, ast.FilterFuncDuplicates) 75 76 // pretty-print 77 var buf bytes.Buffer 78 if err := format.Node(&buf, fset, merged); err != nil { 79 t.Fatal(err) 80 } 81 output := buf.String() 82 83 if output != golden { 84 t.Errorf("incorrect output:\n%s", output) 85 } 86 }