github.com/jhump/golang-x-tools@v0.0.0-20220218190644-4958d6d39439/go/analysis/internal/checker/checker_test.go (about) 1 // Copyright 2019 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 checker_test 6 7 import ( 8 "fmt" 9 "go/ast" 10 "io/ioutil" 11 "path/filepath" 12 "testing" 13 14 "github.com/jhump/golang-x-tools/go/analysis" 15 "github.com/jhump/golang-x-tools/go/analysis/analysistest" 16 "github.com/jhump/golang-x-tools/go/analysis/internal/checker" 17 "github.com/jhump/golang-x-tools/go/analysis/passes/inspect" 18 "github.com/jhump/golang-x-tools/go/ast/inspector" 19 "github.com/jhump/golang-x-tools/internal/testenv" 20 ) 21 22 var from, to string 23 24 func TestApplyFixes(t *testing.T) { 25 testenv.NeedsGoPackages(t) 26 27 from = "bar" 28 to = "baz" 29 30 files := map[string]string{ 31 "rename/test.go": `package rename 32 33 func Foo() { 34 bar := 12 35 _ = bar 36 } 37 38 // the end 39 `} 40 want := `package rename 41 42 func Foo() { 43 baz := 12 44 _ = baz 45 } 46 47 // the end 48 ` 49 50 testdata, cleanup, err := analysistest.WriteFiles(files) 51 if err != nil { 52 t.Fatal(err) 53 } 54 path := filepath.Join(testdata, "src/rename/test.go") 55 checker.Fix = true 56 checker.Run([]string{"file=" + path}, []*analysis.Analyzer{analyzer}) 57 58 contents, err := ioutil.ReadFile(path) 59 if err != nil { 60 t.Fatal(err) 61 } 62 63 got := string(contents) 64 if got != want { 65 t.Errorf("contents of rewritten file\ngot: %s\nwant: %s", got, want) 66 } 67 68 defer cleanup() 69 } 70 71 var analyzer = &analysis.Analyzer{ 72 Name: "rename", 73 Requires: []*analysis.Analyzer{inspect.Analyzer}, 74 Run: run, 75 } 76 77 func run(pass *analysis.Pass) (interface{}, error) { 78 inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) 79 nodeFilter := []ast.Node{(*ast.Ident)(nil)} 80 inspect.Preorder(nodeFilter, func(n ast.Node) { 81 ident := n.(*ast.Ident) 82 if ident.Name == from { 83 msg := fmt.Sprintf("renaming %q to %q", from, to) 84 pass.Report(analysis.Diagnostic{ 85 Pos: ident.Pos(), 86 End: ident.End(), 87 Message: msg, 88 SuggestedFixes: []analysis.SuggestedFix{{ 89 Message: msg, 90 TextEdits: []analysis.TextEdit{{ 91 Pos: ident.Pos(), 92 End: ident.End(), 93 NewText: []byte(to), 94 }}, 95 }}, 96 }) 97 } 98 }) 99 100 return nil, nil 101 }