1
2
3
4
5
6 package tests
7
8 import (
9 "go/ast"
10 "go/parser"
11 "go/token"
12 "testing"
13 )
14
15 func TestSortImportsUpdatesFileImportsField(t *testing.T) {
16 t.Run("one import statement", func(t *testing.T) {
17 const src = `package test
18
19 import (
20 "test"
21 "test" // test comment
22 )
23 `
24
25 fset := token.NewFileSet()
26 f, err := parser.ParseFile(fset, "test.go", src, parser.ParseComments|parser.SkipObjectResolution)
27 if err != nil {
28 t.Fatal(err)
29 }
30
31 ast.SortImports(fset, f)
32
33
34 importDeclSpecCount := len(f.Decls[0].(*ast.GenDecl).Specs)
35 if importDeclSpecCount != 1 {
36 t.Fatalf("len(f.Decls[0].(*ast.GenDecl).Specs) = %v; want = 1", importDeclSpecCount)
37 }
38
39
40 if len(f.Imports) != 1 {
41 t.Fatalf("len(f.Imports) = %v; want = 1", len(f.Imports))
42 }
43 })
44
45 t.Run("multiple import statements", func(t *testing.T) {
46 const src = `package test
47
48 import "unsafe"
49
50 import (
51 "package"
52 "package"
53 )
54
55 import (
56 "test"
57 "test"
58 )
59 `
60
61 fset := token.NewFileSet()
62 f, err := parser.ParseFile(fset, "test.go", src, parser.ParseComments|parser.SkipObjectResolution)
63 if err != nil {
64 t.Fatal(err)
65 }
66
67 ast.SortImports(fset, f)
68
69
70 for i := range 3 {
71 importDeclSpecCount := len(f.Decls[i].(*ast.GenDecl).Specs)
72 if importDeclSpecCount != 1 {
73 t.Fatalf("len(f.Decls[%v].(*ast.GenDecl).Specs) = %v; want = 1", i, importDeclSpecCount)
74 }
75 }
76
77
78 if len(f.Imports) != 3 {
79 t.Fatalf("len(f.Imports) = %v; want = 3", len(f.Imports))
80 }
81 })
82 }
83
View as plain text