Source file src/go/ast/filter_test.go

     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  	"go/ast"
    11  	"go/format"
    12  	"go/parser"
    13  	"go/token"
    14  	"strings"
    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  const golden = `package p
    42  
    43  type t1 struct{}
    44  type t2 struct{}
    45  
    46  func f1() {}
    47  func f2() {}
    48  
    49  func (t1) f1() {}
    50  func (t1) f2() {}
    51  
    52  func (t2) f1() {}
    53  
    54  func (x *t2) f2() {}
    55  `
    56  
    57  func TestFilterDuplicates(t *testing.T) {
    58  	// parse input
    59  	fset := token.NewFileSet()
    60  	file, err := parser.ParseFile(fset, "", input, 0)
    61  	if err != nil {
    62  		t.Fatal(err)
    63  	}
    64  
    65  	// create package
    66  	files := map[string]*ast.File{"": file}
    67  	pkg, err := ast.NewPackage(fset, files, nil, nil)
    68  	if err != nil {
    69  		t.Fatal(err)
    70  	}
    71  
    72  	// filter
    73  	merged := ast.MergePackageFiles(pkg, ast.FilterFuncDuplicates)
    74  
    75  	// pretty-print
    76  	var buf strings.Builder
    77  	if err := format.Node(&buf, fset, merged); err != nil {
    78  		t.Fatal(err)
    79  	}
    80  	output := buf.String()
    81  
    82  	if output != golden {
    83  		t.Errorf("incorrect output:\n%s", output)
    84  	}
    85  }
    86  

View as plain text