Source file src/go/doc/example_internal_test.go

     1  // Copyright 2022 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 doc
     6  
     7  import (
     8  	"go/parser"
     9  	"go/token"
    10  	"reflect"
    11  	"strconv"
    12  	"strings"
    13  	"testing"
    14  )
    15  
    16  func TestImportGroupStarts(t *testing.T) {
    17  	for _, test := range []struct {
    18  		name string
    19  		in   string
    20  		want []string // paths of group-starting imports
    21  	}{
    22  		{
    23  			name: "one group",
    24  			in: `package p
    25  import (
    26  	"a"
    27  	"b"
    28  	"c"
    29  	"d"
    30  )
    31  `,
    32  			want: []string{"a"},
    33  		},
    34  		{
    35  			name: "several groups",
    36  			in: `package p
    37  import (
    38  	"a"
    39  
    40  	"b"
    41  	"c"
    42  
    43  	"d"
    44  )
    45  `,
    46  			want: []string{"a", "b", "d"},
    47  		},
    48  		{
    49  			name: "extra space",
    50  			in: `package p
    51  import (
    52  	"a"
    53  
    54  
    55  	"b"
    56  	"c"
    57  
    58  
    59  	"d"
    60  )
    61  `,
    62  			want: []string{"a", "b", "d"},
    63  		},
    64  		{
    65  			name: "line comment",
    66  			in: `package p
    67  import (
    68  	"a" // comment
    69  	"b" // comment
    70  
    71  	"c"
    72  )`,
    73  			want: []string{"a", "c"},
    74  		},
    75  		{
    76  			name: "named import",
    77  			in: `package p
    78  import (
    79  	"a"
    80  	n "b"
    81  
    82  	m "c"
    83  	"d"
    84  )`,
    85  			want: []string{"a", "c"},
    86  		},
    87  		{
    88  			name: "blank import",
    89  			in: `package p
    90  import (
    91  	"a"
    92  
    93  	_ "b"
    94  
    95  	_ "c"
    96  	"d"
    97  )`,
    98  			want: []string{"a", "b", "c"},
    99  		},
   100  	} {
   101  		t.Run(test.name, func(t *testing.T) {
   102  			fset := token.NewFileSet()
   103  			file, err := parser.ParseFile(fset, "test.go", strings.NewReader(test.in), parser.ParseComments)
   104  			if err != nil {
   105  				t.Fatal(err)
   106  			}
   107  			imps := findImportGroupStarts1(file.Imports)
   108  			got := make([]string, len(imps))
   109  			for i, imp := range imps {
   110  				got[i], err = strconv.Unquote(imp.Path.Value)
   111  				if err != nil {
   112  					t.Fatal(err)
   113  				}
   114  			}
   115  			if !reflect.DeepEqual(got, test.want) {
   116  				t.Errorf("got %v, want %v", got, test.want)
   117  			}
   118  		})
   119  	}
   120  
   121  }
   122  

View as plain text