Source file src/go/ast/internal/tests/sortimports_test.go

     1  // Copyright 2024 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  // Tests is a helper package to avoid cyclic dependency between go/ast and go/parser.
     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  		// Check that the duplicate import spec is eliminated.
    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  		// Check that File.Imports is consistent.
    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  		// Check that three single-spec import decls remain.
    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  		// Check that File.Imports is consistent.
    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