github.com/daixiang0/gci@v0.13.0/pkg/analyzer/diff_test.go (about) 1 package analyzer_test 2 3 import ( 4 "go/parser" 5 "go/token" 6 "testing" 7 8 "github.com/stretchr/testify/assert" 9 "golang.org/x/tools/go/analysis" 10 11 "github.com/daixiang0/gci/pkg/analyzer" 12 ) 13 14 const formattedFile = `package analyzer 15 16 import ( 17 "fmt" 18 "go/token" 19 "strings" 20 21 "golang.org/x/tools/go/analysis" 22 23 "github.com/daixiang0/gci/pkg/config" 24 "github.com/daixiang0/gci/pkg/gci" 25 "github.com/daixiang0/gci/pkg/io" 26 "github.com/daixiang0/gci/pkg/log" 27 ) 28 ` 29 30 func TestGetSuggestedFix(t *testing.T) { 31 for _, tt := range []struct { 32 name string 33 unformattedFile string 34 expectedFix *analysis.SuggestedFix 35 expectedErr string 36 }{ 37 { 38 name: "same files", 39 unformattedFile: formattedFile, 40 }, 41 { 42 name: "one change", 43 unformattedFile: `package analyzer 44 45 import ( 46 "fmt" 47 "go/token" 48 "strings" 49 50 "golang.org/x/tools/go/analysis" 51 52 "github.com/daixiang0/gci/pkg/config" 53 "github.com/daixiang0/gci/pkg/gci" 54 55 "github.com/daixiang0/gci/pkg/io" 56 "github.com/daixiang0/gci/pkg/log" 57 ) 58 `, 59 expectedFix: &analysis.SuggestedFix{ 60 TextEdits: []analysis.TextEdit{ 61 { 62 Pos: 133, 63 End: 205, 64 NewText: []byte(` "github.com/daixiang0/gci/pkg/gci" 65 "github.com/daixiang0/gci/pkg/io" 66 `, 67 ), 68 }, 69 }, 70 }, 71 }, 72 { 73 name: "multiple changes", 74 unformattedFile: `package analyzer 75 76 import ( 77 "fmt" 78 "go/token" 79 80 "strings" 81 82 "golang.org/x/tools/go/analysis" 83 84 "github.com/daixiang0/gci/pkg/config" 85 "github.com/daixiang0/gci/pkg/gci" 86 87 "github.com/daixiang0/gci/pkg/io" 88 "github.com/daixiang0/gci/pkg/log" 89 ) 90 `, 91 expectedFix: &analysis.SuggestedFix{ 92 TextEdits: []analysis.TextEdit{ 93 { 94 Pos: 35, 95 End: 59, 96 NewText: []byte(` "go/token" 97 "strings" 98 `, 99 ), 100 }, 101 { 102 Pos: 134, 103 End: 206, 104 NewText: []byte(` "github.com/daixiang0/gci/pkg/gci" 105 "github.com/daixiang0/gci/pkg/io" 106 `, 107 ), 108 }, 109 }, 110 }, 111 }, 112 } { 113 t.Run(tt.name, func(t *testing.T) { 114 fset := token.NewFileSet() 115 f, err := parser.ParseFile(fset, "analyzer.go", tt.unformattedFile, 0) 116 assert.NoError(t, err) 117 118 actualFix, err := analyzer.GetSuggestedFix(fset.File(f.Pos()), []byte(tt.unformattedFile), []byte(formattedFile)) 119 if tt.expectedErr != "" { 120 assert.ErrorContains(t, err, tt.expectedErr) 121 return 122 } 123 assert.NoError(t, err) 124 assert.Equal(t, tt.expectedFix, actualFix) 125 }) 126 } 127 }