Debian Codegraph @

internal/imports/fix_test.go

raw symbols SCIP
1 // Copyright 2013 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 imports
6
7 import (
8 "context"
9 "flag"
10 "fmt"
11 "go/build"
12 "log"
13 "os"
14 "path"
15 "path/filepath"
16 "reflect"
17 "sort"
18 "strings"
19 "sync"
20 "sync/atomic"
21 "testing"
22
23 "golang.org/x/tools/internal/gocommand"
24 "golang.org/x/tools/internal/packagestest"
25 "golang.org/x/tools/internal/stdlib"
26 )
27
28 var testDebug = flag.Bool("debug", false, "enable debug output")
29
30 var tests = []struct {
31 name string
32 formatOnly bool
33 in, out string
34 }{
35 // Adding an import to an existing parenthesized import
36 {
37 name: "factored_imports_add",
38 in: `package foo
39 import (
40 "fmt"
41 )
42 func bar() {
43 var b bytes.Buffer
44 fmt.Println(b.String())
45 }
46 `,
47 out: `package foo
48
49 import (
50 "bytes"
51 "fmt"
52 )
53
54 func bar() {
55 var b bytes.Buffer
56 fmt.Println(b.String())
57 }
58 `,
59 },
60
61 // Adding an import to an existing parenthesized import,
62 // verifying it goes into the first section.
63 {
64 name: "factored_imports_add_first_sec",
65 in: `package foo
66 import (
67 "fmt"
68
69 "github.com/golang/snappy"
70 )
71 func bar() {
72 var b bytes.Buffer
73 _ = snappy.ErrCorrupt
74 fmt.Println(b.String())
75 }
76 `,
77 out: `package foo
78
79 import (
80 "bytes"
81 "fmt"
82
83 "github.com/golang/snappy"
84 )
85
86 func bar() {
87 var b bytes.Buffer
88 _ = snappy.ErrCorrupt
89 fmt.Println(b.String())
90 }
91 `,
92 },
93
94 // Adding an import to an existing parenthesized import,
95 // verifying it goes into the first section. (test 2)
96 {
97 name: "factored_imports_add_first_sec_2",
98 in: `package foo
99 import (
100 "fmt"
101
102 "github.com/golang/snappy"
103 )
104 func bar() {
105 _ = math.NaN
106 _ = fmt.Sprintf
107 _ = snappy.ErrCorrupt
108 }
109 `,
110 out: `package foo
111
112 import (
113 "fmt"
114 "math"
115
116 "github.com/golang/snappy"
117 )
118
119 func bar() {
120 _ = math.NaN
121 _ = fmt.Sprintf
122 _ = snappy.ErrCorrupt
123 }
124 `,
125 },
126
127 // Adding a new import line, without parens
128 {
129 name: "add_import_section",
130 in: `package foo
131 func bar() {
132 var b bytes.Buffer
133 }
134 `,
135 out: `package foo
136
137 import "bytes"
138
139 func bar() {
140 var b bytes.Buffer
141 }
142 `,
143 },
144
145 // Adding two new imports, which should make a parenthesized import decl.
146 {
147 name: "add_import_paren_section",
148 in: `package foo
149 func bar() {
150 _, _ := bytes.Buffer, zip.NewReader
151 }
152 `,
153 out: `package foo
154
155 import (
156 "archive/zip"
157 "bytes"
158 )
159
160 func bar() {
161 _, _ := bytes.Buffer, zip.NewReader
162 }
163 `,
164 },
165
166 // Make sure we don't add things twice
167 {
168 name: "no_double_add",
169 in: `package foo
170 func bar() {
171 _, _ := bytes.Buffer, bytes.NewReader
172 }
173 `,
174 out: `package foo
175
176 import "bytes"
177
178 func bar() {
179 _, _ := bytes.Buffer, bytes.NewReader
180 }
181 `,
182 },
183
184 // Make sure we don't add packages that don't have the right exports
185 {
186 name: "no_mismatched_add",
187 in: `package foo
188
189 func bar() {
190 _ := bytes.NonexistentSymbol
191 }
192 `,
193 out: `package foo
194
195 func bar() {
196 _ := bytes.NonexistentSymbol
197 }
198 `,
199 },
200
201 // Remove unused imports, 1 of a factored block
202 {
203 name: "remove_unused_1_of_2",
204 in: `package foo
205 import (
206 "bytes"
207 "fmt"
208 )
209
210 func bar() {
211 _, _ := bytes.Buffer, bytes.NewReader
212 }
213 `,
214 out: `package foo
215
216 import (
217 "bytes"
218 )
219
220 func bar() {
221 _, _ := bytes.Buffer, bytes.NewReader
222 }
223 `,
224 },
225
226 // Remove unused imports, 2 of 2
227 {
228 name: "remove_unused_2_of_2",
229 in: `package foo
230 import (
231 "bytes"
232 "fmt"
233 )
234
235 func bar() {
236 }
237 `,
238 out: `package foo
239
240 func bar() {
241 }
242 `,
243 },
244
245 // Remove unused imports, 1 of 1
246 {
247 name: "remove_unused_1_of_1",
248 in: `package foo
249
250 import "fmt"
251
252 func bar() {
253 }
254 `,
255 out: `package foo
256
257 func bar() {
258 }
259 `,
260 },
261
262 // Don't remove empty imports.
263 {
264 name: "dont_remove_empty_imports",
265 in: `package foo
266 import (
267 _ "image/png"
268 _ "image/jpeg"
269 )
270 `,
271 out: `package foo
272
273 import (
274 _ "image/jpeg"
275 _ "image/png"
276 )
277 `,
278 },
279
280 // Don't remove dot imports.
281 {
282 name: "dont_remove_dot_imports",
283 in: `package foo
284 import (
285 . "foo"
286 . "bar"
287 )
288 `,
289 out: `package foo
290
291 import (
292 . "bar"
293 . "foo"
294 )
295 `,
296 },
297
298 // Skip refs the parser can resolve.
299 {
300 name: "skip_resolved_refs",
301 in: `package foo
302
303 func f() {
304 type t struct{ Println func(string) }
305 fmt := t{Println: func(string) {}}
306 fmt.Println("foo")
307 }
308 `,
309 out: `package foo
310
311 func f() {
312 type t struct{ Println func(string) }
313 fmt := t{Println: func(string) {}}
314 fmt.Println("foo")
315 }
316 `,
317 },
318
319 // Do not add a package we already have a resolution for.
320 {
321 name: "skip_template",
322 in: `package foo
323
324 import "html/template"
325
326 func f() { t = template.New("sometemplate") }
327 `,
328 out: `package foo
329
330 import "html/template"
331
332 func f() { t = template.New("sometemplate") }
333 `,
334 },
335
336 // Don't touch cgo
337 {
338 name: "cgo",
339 in: `package foo
340
341 /*
342 #include <foo.h>
343 */
344 import "C"
345 `,
346 out: `package foo
347
348 /*
349 #include <foo.h>
350 */
351 import "C"
352 `,
353 },
354
355 // Put some things in their own section
356 {
357 name: "make_sections",
358 in: `package foo
359
360 import (
361 "os"
362 )
363
364 func foo () {
365 _, _ = os.Args, fmt.Println
366 _, _ = snappy.ErrCorrupt, p.P
367 }
368 `,
369 out: `package foo
370
371 import (
372 "fmt"
373 "os"
374
375 "github.com/golang/snappy"
376 "rsc.io/p"
377 )
378
379 func foo() {
380 _, _ = os.Args, fmt.Println
381 _, _ = snappy.ErrCorrupt, p.P
382 }
383 `,
384 },
385 // Merge import blocks, even when no additions are required.
386 {
387 name: "merge_import_blocks_no_fix",
388 in: `package foo
389
390 import (
391 "fmt"
392 )
393 import "os"
394
395 import (
396 "rsc.io/p"
397 )
398
399 var _, _ = os.Args, fmt.Println
400 var _, _ = snappy.ErrCorrupt, p.P
401 `,
402 out: `package foo
403
404 import (
405 "fmt"
406 "os"
407
408 "github.com/golang/snappy"
409 "rsc.io/p"
410 )
411
412 var _, _ = os.Args, fmt.Println
413 var _, _ = snappy.ErrCorrupt, p.P
414 `,
415 },
416 // Delete existing empty import block
417 {
418 name: "delete_empty_import_block",
419 in: `package foo
420
421 import ()
422 `,
423 out: `package foo
424 `,
425 },
426
427 // Use existing empty import block
428 {
429 name: "use_empty_import_block",
430 in: `package foo
431
432 import ()
433
434 func f() {
435 _ = fmt.Println
436 }
437 `,
438 out: `package foo
439
440 import "fmt"
441
442 func f() {
443 _ = fmt.Println
444 }
445 `,
446 },
447
448 // Blank line before adding new section.
449 {
450 name: "blank_line_before_new_group",
451 in: `package foo
452
453 import (
454 "fmt"
455 "net"
456 )
457
458 func f() {
459 _ = net.Dial
460 _ = fmt.Printf
461 _ = snappy.ErrCorrupt
462 }
463 `,
464 out: `package foo
465
466 import (
467 "fmt"
468 "net"
469
470 "github.com/golang/snappy"
471 )
472
473 func f() {
474 _ = net.Dial
475 _ = fmt.Printf
476 _ = snappy.ErrCorrupt
477 }
478 `,
479 },
480
481 // Blank line between standard library and third-party stuff.
482 {
483 name: "blank_line_separating_std_and_third_party",
484 in: `package foo
485
486 import (
487 "github.com/golang/snappy"
488 "fmt"
489 "net"
490 )
491
492 func f() {
493 _ = net.Dial
494 _ = fmt.Printf
495 _ = snappy.Foo
496 }
497 `,
498 out: `package foo
499
500 import (
501 "fmt"
502 "net"
503
504 "github.com/golang/snappy"
505 )
506
507 func f() {
508 _ = net.Dial
509 _ = fmt.Printf
510 _ = snappy.Foo
511 }
512 `,
513 },
514
515 // golang.org/issue/6884
516 {
517 name: "new_imports_before_comment",
518 in: `package main
519
520 // A comment
521 func main() {
522 fmt.Println("Hello, world")
523 }
524 `,
525 out: `package main
526
527 import "fmt"
528
529 // A comment
530 func main() {
531 fmt.Println("Hello, world")
532 }
533 `,
534 },
535
536 // golang.org/issue/7132
537 {
538 name: "new_section_for_dotless_import",
539 in: `package main
540
541 import (
542 "fmt"
543
544 "gu"
545 "manypackages.com/packagea"
546 )
547
548 var (
549 a = packagea.A
550 b = gu.A
551 c = fmt.Printf
552 )
553 `,
554 out: `package main
555
556 import (
557 "fmt"
558
559 "gu"
560
561 "manypackages.com/packagea"
562 )
563
564 var (
565 a = packagea.A
566 b = gu.A
567 c = fmt.Printf
568 )
569 `,
570 },
571
572 {
573 name: "fragment_with_main",
574 in: `func main(){fmt.Println("Hello, world")}`,
575 out: `package main
576
577 import "fmt"
578
579 func main() { fmt.Println("Hello, world") }
580 `,
581 },
582
583 {
584 name: "fragment_without_main",
585 in: `func notmain(){fmt.Println("Hello, world")}`,
586 out: `import "fmt"
587
588 func notmain() { fmt.Println("Hello, world") }`,
589 },
590
591 // Remove first import within in a 2nd/3rd/4th/etc. section.
592 // golang.org/issue/7679
593 {
594 name: "remove_first_import_in_section",
595 in: `package main
596
597 import (
598 "fmt"
599
600 "manypackages.com/packagea"
601 "manypackages.com/packageb"
602 )
603
604 func main() {
605 var _ = fmt.Println
606 //var _ = packagea.A
607 var _ = packageb.B
608 }
609 `,
610 out: `package main
611
612 import (
613 "fmt"
614
615 "manypackages.com/packageb"
616 )
617
618 func main() {
619 var _ = fmt.Println
620 //var _ = packagea.A
621 var _ = packageb.B
622 }
623 `,
624 },
625
626 // Blank line can be added before all types of import declarations.
627 // golang.org/issue/7866
628 {
629 name: "new_section_for_all_kinds_of_imports",
630 in: `package main
631
632 import (
633 "fmt"
634 renamed_packagea "manypackages.com/packagea"
635
636 . "manypackages.com/packageb"
637 "io"
638
639 _ "manypackages.com/packagec"
640 "strings"
641 )
642
643 var _, _, _, _, _ = fmt.Errorf, io.Copy, strings.Contains, renamed_packagea.A, B
644 `,
645 out: `package main
646
647 import (
648 "fmt"
649
650 renamed_packagea "manypackages.com/packagea"
651
652 "io"
653
654 . "manypackages.com/packageb"
655
656 "strings"
657
658 _ "manypackages.com/packagec"
659 )
660
661 var _, _, _, _, _ = fmt.Errorf, io.Copy, strings.Contains, renamed_packagea.A, B
662 `,
663 },
664
665 // Blank line can be added even when first import of group has comment with quote
666 {
667 name: "new_section_where_trailing_comment_has_quote",
668 in: `package main
669
670 import (
671 "context"
672 bar "local.com/bar"
673 baz "local.com/baz"
674 buzz "local.com/buzz"
675 "github.com/golang/snappy" // this is a "typical" import
676 )
677
678 var _, _, _, _, _ = context.Background, bar.B, baz.B, buzz.B, snappy.ErrCorrupt
679 `,
680 out: `package main
681
682 import (
683 "context"
684
685 "github.com/golang/snappy" // this is a "typical" import
686
687 bar "local.com/bar"
688 baz "local.com/baz"
689 buzz "local.com/buzz"
690 )
691
692 var _, _, _, _, _ = context.Background, bar.B, baz.B, buzz.B, snappy.ErrCorrupt
693 `,
694 },
695
696 // Non-idempotent comment formatting
697 // golang.org/issue/8035
698 {
699 name: "comments_formatted",
700 in: `package main
701
702 import (
703 "fmt" // A
704 "go/ast" // B
705 _ "manypackages.com/packagec" // C
706 )
707
708 func main() { _, _ = fmt.Print, ast.Walk }
709 `,
710 out: `package main
711
712 import (
713 "fmt" // A
714 "go/ast" // B
715
716 _ "manypackages.com/packagec" // C
717 )
718
719 func main() { _, _ = fmt.Print, ast.Walk }
720 `,
721 },
722
723 // Failure to delete all duplicate imports
724 // golang.org/issue/8459
725 {
726 name: "remove_duplicates",
727 in: `package main
728
729 import (
730 "fmt"
731 "log"
732 "log"
733 "math"
734 )
735
736 func main() { fmt.Println("pi:", math.Pi) }
737 `,
738 out: `package main
739
740 import (
741 "fmt"
742 "math"
743 )
744
745 func main() { fmt.Println("pi:", math.Pi) }
746 `,
747 },
748
749 // Too aggressive prefix matching
750 // golang.org/issue/9961
751 {
752 name: "no_extra_groups",
753 in: `package p
754
755 import (
756 "zip"
757
758 "rsc.io/p"
759 )
760
761 var (
762 _ = fmt.Print
763 _ = zip.Store
764 _ p.P
765 _ = regexp.Compile
766 )
767 `,
768 out: `package p
769
770 import (
771 "fmt"
772 "regexp"
773 "zip"
774
775 "rsc.io/p"
776 )
777
778 var (
779 _ = fmt.Print
780 _ = zip.Store
781 _ p.P
782 _ = regexp.Compile
783 )
784 `,
785 },
786
787 // Unused named import is mistaken for unnamed import
788 // golang.org/issue/8149
789 {
790 name: "named_import_doesnt_provide_package_name",
791 in: `package main
792
793 import foo "fmt"
794
795 func main() { fmt.Println() }
796 `,
797 out: `package main
798
799 import "fmt"
800
801 func main() { fmt.Println() }
802 `,
803 },
804
805 // Unused named import is mistaken for unnamed import
806 // golang.org/issue/8149
807 {
808 name: "unused_named_import_removed",
809 in: `package main
810
811 import (
812 "fmt"
813 x "fmt"
814 )
815
816 func main() { fmt.Println() }
817 `,
818 out: `package main
819
820 import (
821 "fmt"
822 )
823
824 func main() { fmt.Println() }
825 `,
826 },
827
828 {
829 name: "ignore_unexported_identifier",
830 in: `package main
831 var _ = fmt.unexported`,
832 out: `package main
833
834 var _ = fmt.unexported
835 `,
836 },
837
838 // FormatOnly
839 {
840 name: "formatonly_works",
841 formatOnly: true,
842 in: `package main
843
844 import (
845 "fmt"
846 "manypackages.com/packagea"
847 )
848
849 func main() {}
850 `,
851 out: `package main
852
853 import (
854 "fmt"
855
856 "manypackages.com/packagea"
857 )
858
859 func main() {}
860 `,
861 },
862
863 {
864 name: "preserve_import_group",
865 in: `package p
866
867 import (
868 "bytes"
869 "fmt"
870 )
871
872 var _ = fmt.Sprintf
873 `,
874 out: `package p
875
876 import (
877 "fmt"
878 )
879
880 var _ = fmt.Sprintf
881 `,
882 },
883 {
884 name: "import_grouping_not_path_dependent_no_groups",
885 in: `package main
886
887 import (
888 "time"
889 )
890
891 func main() {
892 _ = snappy.ErrCorrupt
893 _ = p.P
894 _ = time.Parse
895 }
896 `,
897 out: `package main
898
899 import (
900 "time"
901
902 "github.com/golang/snappy"
903 "rsc.io/p"
904 )
905
906 func main() {
907 _ = snappy.ErrCorrupt
908 _ = p.P
909 _ = time.Parse
910 }
911 `,
912 },
913
914 {
915 name: "import_grouping_not_path_dependent_existing_group",
916 in: `package main
917
918 import (
919 "time"
920
921 "github.com/golang/snappy"
922 )
923
924 func main() {
925 _ = snappy.ErrCorrupt
926 _ = p.P
927 _ = time.Parse
928 }
929 `,
930 out: `package main
931
932 import (
933 "time"
934
935 "github.com/golang/snappy"
936 "rsc.io/p"
937 )
938
939 func main() {
940 _ = snappy.ErrCorrupt
941 _ = p.P
942 _ = time.Parse
943 }
944 `,
945 },
946
947 // golang.org/issue/12097
948 {
949 name: "package_statement_insertion_preserves_comments",
950 in: `// a
951 // b
952 // c
953
954 func main() {
955 _ = fmt.Println
956 }`,
957 out: `package main
958
959 import "fmt"
960
961 // a
962 // b
963 // c
964
965 func main() {
966 _ = fmt.Println
967 }
968 `,
969 },
970
971 {
972 name: "import_comment_stays_on_import",
973 in: `package main
974
975 import (
976 "math" // fun
977 )
978
979 func main() {
980 x := math.MaxInt64
981 fmt.Println(strings.Join(",", []string{"hi"}), x)
982 }`,
983 out: `package main
984
985 import (
986 "fmt"
987 "math" // fun
988 "strings"
989 )
990
991 func main() {
992 x := math.MaxInt64
993 fmt.Println(strings.Join(",", []string{"hi"}), x)
994 }
995 `,
996 },
997
998 {
999 name: "no_blank_after_comment",
1000 in: `package main
1001
1002 import (
1003 _ "io"
1004 _ "net/http"
1005 _ "net/http/pprof" // install the pprof http handlers
1006 _ "strings"
1007 )
1008
1009 func main() {
1010 }
1011 `,
1012 out: `package main
1013
1014 import (
1015 _ "io"
1016 _ "net/http"
1017 _ "net/http/pprof" // install the pprof http handlers
1018 _ "strings"
1019 )
1020
1021 func main() {
1022 }
1023 `,
1024 },
1025
1026 {
1027 name: "no_blank_after_comment_reordered",
1028 in: `package main
1029
1030 import (
1031 _ "io"
1032 _ "net/http/pprof" // install the pprof http handlers
1033 _ "net/http"
1034 _ "strings"
1035 )
1036
1037 func main() {
1038 }
1039 `,
1040 out: `package main
1041
1042 import (
1043 _ "io"
1044 _ "net/http"
1045 _ "net/http/pprof" // install the pprof http handlers
1046 _ "strings"
1047 )
1048
1049 func main() {
1050 }
1051 `,
1052 },
1053
1054 {
1055 name: "no_blank_after_comment_unnamed",
1056 in: `package main
1057
1058 import (
1059 "encoding/json"
1060 "io"
1061 "net/http"
1062 _ "net/http/pprof" // install the pprof http handlers
1063 "strings"
1064
1065 "manypackages.com/packagea"
1066 )
1067
1068 func main() {
1069 _ = strings.ToUpper("hello")
1070 _ = io.EOF
1071 var (
1072 _ json.Number
1073 _ *http.Request
1074 _ packagea.A
1075 )
1076 }
1077 `,
1078 out: `package main
1079
1080 import (
1081 "encoding/json"
1082 "io"
1083 "net/http"
1084 _ "net/http/pprof" // install the pprof http handlers
1085 "strings"
1086
1087 "manypackages.com/packagea"
1088 )
1089
1090 func main() {
1091 _ = strings.ToUpper("hello")
1092 _ = io.EOF
1093 var (
1094 _ json.Number
1095 _ *http.Request
1096 _ packagea.A
1097 )
1098 }
1099 `,
1100 },
1101
1102 {
1103 name: "blank_after_package_statement_with_comment",
1104 in: `package p // comment
1105
1106 import "math"
1107
1108 var _ = fmt.Printf
1109 `,
1110 out: `package p // comment
1111
1112 import "fmt"
1113
1114 var _ = fmt.Printf
1115 `,
1116 },
1117
1118 {
1119 name: "blank_after_package_statement_no_comment",
1120 in: `package p
1121
1122 import "math"
1123
1124 var _ = fmt.Printf
1125 `,
1126 out: `package p
1127
1128 import "fmt"
1129
1130 var _ = fmt.Printf
1131 `,
1132 },
1133
1134 {
1135 name: "cryptorand_preferred_easy_possible",
1136 in: `package p
1137
1138 var _ = rand.Read
1139 `,
1140 out: `package p
1141
1142 import "crypto/rand"
1143
1144 var _ = rand.Read
1145 `,
1146 },
1147
1148 {
1149 name: "cryptorand_preferred_easy_impossible",
1150 in: `package p
1151
1152 var _ = rand.NewZipf
1153 `,
1154 out: `package p
1155
1156 import "math/rand/v2"
1157
1158 var _ = rand.NewZipf
1159 `,
1160 },
1161
1162 {
1163 name: "cryptorand_preferred_complex_possible",
1164 in: `package p
1165
1166 var _, _ = rand.Read, rand.Prime
1167 `,
1168 out: `package p
1169
1170 import "crypto/rand"
1171
1172 var _, _ = rand.Read, rand.Prime
1173 `,
1174 },
1175
1176 {
1177 name: "cryptorand_preferred_complex_impossible",
1178 in: `package p
1179
1180 var _, _ = rand.Read, rand.NewZipf
1181 `,
1182 out: `package p
1183
1184 import "math/rand"
1185
1186 var _, _ = rand.Read, rand.NewZipf
1187 `,
1188 },
1189 {
1190 name: "unused_duplicate_imports_remove",
1191 in: `package main
1192
1193 import (
1194 "errors"
1195
1196 "github.com/pkg/errors"
1197 )
1198 `,
1199 out: `package main
1200 `,
1201 },
1202 }
1203
1204 func TestSimpleCases(t *testing.T) {
1205 const localPrefix = "local.com,github.com/local"
1206 for _, tt := range tests {
1207 t.Run(tt.name, func(t *testing.T) {
1208 testConfig{
1209 modules: []packagestest.Module{
1210 {
1211 Name: "golang.org/fake",
1212 Files: fm{"x.go": tt.in},
1213 },
1214 // Skeleton non-stdlib packages for use during testing.
1215 // Each includes one arbitrary symbol, e.g. the first declaration in the first file.
1216 // Try not to add more without a good reason.
1217 // DO NOT USE PACKAGES NOT LISTED HERE -- they will be downloaded!
1218 {
1219 Name: "rsc.io",
1220 Files: fm{"p/x.go": "package p\nfunc P(){}\n"},
1221 },
1222 {
1223 Name: "github.com/golang/snappy",
1224 Files: fm{"x.go": "package snappy\nvar ErrCorrupt error\n"},
1225 },
1226 {
1227 Name: "manypackages.com",
1228 Files: fm{
1229 "packagea/x.go": "package packagea\nfunc A(){}\n",
1230 "packageb/x.go": "package packageb\nfunc B(){}\n",
1231 "packagec/x.go": "package packagec\nfunc C(){}\n",
1232 "packaged/x.go": "package packaged\nfunc D(){}\n",
1233 },
1234 },
1235 {
1236 Name: "local.com",
1237 Files: fm{"foo/x.go": "package foo\nfunc Foo(){}\n"},
1238 },
1239 {
1240 Name: "github.com/local",
1241 Files: fm{"bar/x.go": "package bar\nfunc Bar(){}\n"},
1242 },
1243 },
1244 }.test(t, func(t *goimportTest) {
1245 options := &Options{
1246 LocalPrefix: localPrefix,
1247 TabWidth: 8,
1248 TabIndent: true,
1249 Comments: true,
1250 Fragment: true,
1251 FormatOnly: tt.formatOnly,
1252 }
1253 t.assertProcessEquals("golang.org/fake", "x.go", nil, options, tt.out)
1254 })
1255
1256 })
1257 }
1258 }
1259
1260 func TestAppengine(t *testing.T) {
1261 const input = `package p
1262
1263 var _, _, _ = fmt.Printf, appengine.Main, datastore.ErrInvalidEntityType
1264 `
1265
1266 const want = `package p
1267
1268 import (
1269 "fmt"
1270
1271 "appengine"
1272 "appengine/datastore"
1273 )
1274
1275 var _, _, _ = fmt.Printf, appengine.Main, datastore.ErrInvalidEntityType
1276 `
1277
1278 testConfig{
1279 gopathOnly: true, // can't create a module named appengine, so no module tests.
1280 modules: []packagestest.Module{
1281 {
1282 Name: "golang.org/fake",
1283 Files: fm{"x.go": input},
1284 },
1285 {
1286 Name: "appengine",
1287 Files: fm{
1288 "x.go": "package appengine\nfunc Main(){}\n",
1289 "datastore/x.go": "package datastore\nvar ErrInvalidEntityType error\n",
1290 },
1291 },
1292 },
1293 }.processTest(t, "golang.org/fake", "x.go", nil, nil, want)
1294 }
1295
1296 func TestReadFromFilesystem(t *testing.T) {
1297 tests := []struct {
1298 name string
1299 in, out string
1300 }{
1301 {
1302 name: "works",
1303 in: `package foo
1304 func bar() {
1305 fmt.Println("hi")
1306 }
1307 `,
1308 out: `package foo
1309
1310 import "fmt"
1311
1312 func bar() {
1313 fmt.Println("hi")
1314 }
1315 `,
1316 },
1317 {
1318 name: "missing_package",
1319 in: `
1320 func bar() {
1321 fmt.Println("hi")
1322 }
1323 `,
1324 out: `
1325 import "fmt"
1326
1327 func bar() {
1328 fmt.Println("hi")
1329 }
1330 `,
1331 },
1332 }
1333
1334 for _, tt := range tests {
1335 t.Run(tt.name, func(t *testing.T) {
1336 options := &Options{
1337 TabWidth: 8,
1338 TabIndent: true,
1339 Comments: true,
1340 Fragment: true,
1341 }
1342 testConfig{
1343 module: packagestest.Module{
1344 Name: "golang.org/fake",
1345 Files: fm{"x.go": tt.in},
1346 },
1347 }.processTest(t, "golang.org/fake", "x.go", nil, options, tt.out)
1348 })
1349 }
1350
1351 }
1352
1353 // Test support for packages in GOPATH that are actually symlinks.
1354 // Also test that a symlink loop does not block the process.
1355 func TestImportSymlinks(t *testing.T) {
1356 const input = `package p
1357
1358 var (
1359 _ = fmt.Print
1360 _ = mypkg.Foo
1361 )
1362 `
1363 const want = `package p
1364
1365 import (
1366 "fmt"
1367
1368 "golang.org/fake/x/y/mypkg"
1369 )
1370
1371 var (
1372 _ = fmt.Print
1373 _ = mypkg.Foo
1374 )
1375 `
1376
1377 testConfig{
1378 module: packagestest.Module{
1379 Name: "golang.org/fake",
1380 Files: fm{
1381 "target/f.go": "package mypkg\nvar Foo = 123\n",
1382 "x/y/mypkg": packagestest.Symlink("../../target"), // valid symlink
1383 "x/y/apkg": packagestest.Symlink(".."), // symlink loop
1384 "myotherpackage/toformat.go": input,
1385 },
1386 },
1387 }.processTest(t, "golang.org/fake", "myotherpackage/toformat.go", nil, nil, want)
1388 }
1389
1390 // Test support for packages in GOPATH whose files are symlinks.
1391 func TestImportSymlinkFiles(t *testing.T) {
1392 const input = `package p
1393
1394 var (
1395 _ = fmt.Print
1396 _ = mypkg.Foo
1397 )
1398 `
1399 const want = `package p
1400
1401 import (
1402 "fmt"
1403
1404 "golang.org/fake/x/y/mypkg"
1405 )
1406
1407 var (
1408 _ = fmt.Print
1409 _ = mypkg.Foo
1410 )
1411 `
1412
1413 testConfig{
1414 module: packagestest.Module{
1415 Name: "golang.org/fake",
1416 Files: fm{
1417 "target/f.go": "package mypkg\nvar Foo = 123\n",
1418 "x/y/mypkg/f.go": packagestest.Symlink("../../../target/f.go"),
1419 "myotherpackage/toformat.go": input,
1420 },
1421 },
1422 }.processTest(t, "golang.org/fake", "myotherpackage/toformat.go", nil, nil, want)
1423 }
1424
1425 func TestImportSymlinksWithIgnore(t *testing.T) {
1426 const input = `package p
1427
1428 var (
1429 _ = fmt.Print
1430 _ = mypkg.Foo
1431 )
1432 `
1433 const want = `package p
1434
1435 import "fmt"
1436
1437 var (
1438 _ = fmt.Print
1439 _ = mypkg.Foo
1440 )
1441 `
1442
1443 testConfig{
1444 gopathOnly: true,
1445 module: packagestest.Module{
1446 Name: "golang.org/fake",
1447 Files: fm{
1448 "target/f.go": "package mypkg\nvar Foo = 123\n",
1449 "x/y/mypkg": packagestest.Symlink("../../target"), // valid symlink
1450 "x/y/apkg": packagestest.Symlink(".."), // symlink loop
1451 "myotherpkg/toformat.go": input,
1452 "../../.goimportsignore": "golang.org/fake/x/y/mypkg\n" +
1453 "golang.org/fake/x/y/apkg\n",
1454 },
1455 },
1456 }.processTest(t, "golang.org/fake", "myotherpkg/toformat.go", nil, nil, want)
1457 }
1458
1459 // Test for x/y/v2 convention for package y.
1460 func TestModuleVersion(t *testing.T) {
1461 const input = `package p
1462
1463 import (
1464 "fmt"
1465
1466 "github.com/foo/v2"
1467 )
1468
1469 var (
1470 _ = fmt.Print
1471 _ = foo.Foo
1472 )
1473 `
1474
1475 testConfig{
1476 modules: []packagestest.Module{
1477 {
1478 Name: "mypkg.com/outpkg",
1479 Files: fm{"toformat.go": input},
1480 },
1481 {
1482 Name: "github.com/foo/v2",
1483 Files: fm{"x.go": "package foo\n func Foo(){}\n"},
1484 },
1485 },
1486 }.processTest(t, "mypkg.com/outpkg", "toformat.go", nil, nil, input)
1487 }
1488
1489 // Test for correctly identifying the name of a vendored package when it
1490 // differs from its directory name. In this test, the import line
1491 // "mypkg.com/mypkg_v1" would be removed if goimports wasn't able to detect
1492 // that the package name is "mypkg".
1493 func TestVendorPackage(t *testing.T) {
1494 const input = `package p
1495 import (
1496 "fmt"
1497 "mypkg.com/mypkg_v1"
1498 )
1499 var _, _ = fmt.Print, mypkg.Foo
1500 `
1501
1502 const want = `package p
1503
1504 import (
1505 "fmt"
1506
1507 mypkg "mypkg.com/mypkg_v1"
1508 )
1509
1510 var _, _ = fmt.Print, mypkg.Foo
1511 `
1512
1513 testConfig{
1514 gopathOnly: true,
1515 module: packagestest.Module{
1516 Name: "mypkg.com/outpkg",
1517 Files: fm{
1518 "vendor/mypkg.com/mypkg_v1/f.go": "package mypkg\nvar Foo = 123\n",
1519 "toformat.go": input,
1520 },
1521 },
1522 }.processTest(t, "mypkg.com/outpkg", "toformat.go", nil, nil, want)
1523 }
1524
1525 func TestInternal(t *testing.T) {
1526 const input = `package bar
1527
1528 var _ = race.Acquire
1529 `
1530 const importAdded = `package bar
1531
1532 import "foo.com/internal/race"
1533
1534 var _ = race.Acquire
1535 `
1536
1537 // Packages under the same directory should be able to use internal packages.
1538 testConfig{
1539 module: packagestest.Module{
1540 Name: "foo.com",
1541 Files: fm{
1542 "internal/race/x.go": "package race\n func Acquire(){}\n",
1543 "bar/x.go": input,
1544 },
1545 },
1546 }.processTest(t, "foo.com", "bar/x.go", nil, nil, importAdded)
1547
1548 // Packages outside the same directory should not.
1549 testConfig{
1550 modules: []packagestest.Module{
1551 {
1552 Name: "foo.com",
1553 Files: fm{"internal/race/x.go": "package race\n func Acquire(){}\n"},
1554 },
1555 {
1556 Name: "bar.com",
1557 Files: fm{"x.go": input},
1558 },
1559 },
1560 }.processTest(t, "bar.com", "x.go", nil, nil, input)
1561 }
1562
1563 func TestProcessVendor(t *testing.T) {
1564 const input = `package p
1565
1566 var _ = hpack.HuffmanDecode
1567 `
1568 const want = `package p
1569
1570 import "golang.org/x/net/http2/hpack"
1571
1572 var _ = hpack.HuffmanDecode
1573 `
1574 testConfig{
1575 gopathOnly: true,
1576 module: packagestest.Module{
1577 Name: "foo.com",
1578 Files: fm{
1579 "vendor/golang.org/x/net/http2/hpack/huffman.go": "package hpack\nfunc HuffmanDecode() { }\n",
1580 "bar/x.go": input,
1581 },
1582 },
1583 }.processTest(t, "foo.com", "bar/x.go", nil, nil, want)
1584 }
1585
1586 func TestFindStdlib(t *testing.T) {
1587 tests := []struct {
1588 pkg string
1589 symbols []string
1590 want string
1591 }{
1592 {"http", []string{"Get"}, "net/http"},
1593 {"http", []string{"Get", "Post"}, "net/http"},
1594 {"http", []string{"Get", "Foo"}, ""},
1595 {"bytes", []string{"Buffer"}, "bytes"},
1596 {"ioutil", []string{"Discard"}, "io/ioutil"},
1597 }
1598 for _, tt := range tests {
1599 var input strings.Builder
1600 input.WriteString("package p\n")
1601 for _, sym := range tt.symbols {
1602 fmt.Fprintf(&input, "var _ = %s.%s\n", tt.pkg, sym)
1603 }
1604 testConfig{
1605 module: packagestest.Module{
1606 Name: "foo.com",
1607 Files: fm{"x.go": input.String()},
1608 },
1609 }.test(t, func(t *goimportTest) {
1610 buf, err := t.process("foo.com", "x.go", nil, nil)
1611 if err != nil {
1612 t.Fatal(err)
1613 }
1614 if got := string(buf); !strings.Contains(got, tt.want) {
1615 t.Errorf("Process(%q) = %q, wanted it to contain %q", input.String(), buf, tt.want)
1616 }
1617 })
1618 }
1619 }
1620
1621 // https://golang.org/issue/31814
1622 func TestStdlibNotPrefixed(t *testing.T) {
1623 const input = `package p
1624 var _ = bytes.Buffer
1625 `
1626 const want = `package p
1627
1628 import "bytes"
1629
1630 var _ = bytes.Buffer
1631 `
1632 // Force a scan of the stdlib.
1633 savedStdlib := stdlib.PackageSymbols
1634 defer func() { stdlib.PackageSymbols = savedStdlib }()
1635 stdlib.PackageSymbols = nil
1636
1637 testConfig{
1638 module: packagestest.Module{
1639 Name: "ignored.com",
1640 Files: fm{"x.go": "package x"},
1641 },
1642 }.test(t, func(t *goimportTest) {
1643 // Run in GOROOT/src so that the std module shows up in go list -m all.
1644 t.env.WorkingDir = filepath.Join(t.goroot, "src")
1645 got, err := t.processNonModule(filepath.Join(t.goroot, "src/x.go"), []byte(input), nil)
1646 if err != nil {
1647 t.Fatalf("Process() = %v", err)
1648 }
1649 if string(got) != want {
1650 t.Errorf("Got:\n%s\nWant:\n%s", got, want)
1651 }
1652 })
1653 }
1654
1655 func TestStdlibSelfImports(t *testing.T) {
1656 const input = `package rc4
1657
1658 var _ = rc4.NewCipher
1659 `
1660
1661 testConfig{
1662 module: packagestest.Module{
1663 Name: "ignored.com",
1664 Files: fm{"x.go": "package x"},
1665 },
1666 }.test(t, func(t *goimportTest) {
1667 got, err := t.processNonModule(filepath.Join(t.goroot, "src/crypto/rc4/foo.go"), []byte(input), nil)
1668 if err != nil {
1669 t.Fatalf("Process() = %v", err)
1670 }
1671 if string(got) != input {
1672 t.Errorf("Got:\n%s\nWant:\n%s", got, input)
1673 }
1674 })
1675 }
1676
1677 type testConfig struct {
1678 gopathOnly bool
1679 module packagestest.Module
1680 modules []packagestest.Module
1681 }
1682
1683 // fm is the type for a packagestest.Module's Files, abbreviated for shorter lines.
1684 type fm map[string]any
1685
1686 func (c testConfig) test(t *testing.T, fn func(*goimportTest)) {
1687 t.Helper()
1688
1689 if c.module.Name != "" {
1690 c.modules = []packagestest.Module{c.module}
1691 }
1692
1693 for _, exporter := range packagestest.All {
1694 t.Run(exporter.Name(), func(t *testing.T) {
1695 t.Helper()
1696 if c.gopathOnly && exporter.Name() == "Modules" {
1697 t.Skip("test marked GOPATH-only")
1698 }
1699 exported := packagestest.Export(t, exporter, c.modules)
1700 defer exported.Cleanup()
1701
1702 env := map[string]string{}
1703 for _, kv := range exported.Config.Env {
1704 split := strings.SplitN(kv, "=", 2)
1705 env[split[0]] = split[1]
1706 }
1707 it := &goimportTest{
1708 T: t,
1709 env: &ProcessEnv{
1710 Env: env,
1711 WorkingDir: exported.Config.Dir,
1712 GocmdRunner: &gocommand.Runner{},
1713 },
1714 exported: exported,
1715 }
1716 if *testDebug {
1717 it.env.Logf = log.Printf
1718 }
1719 // packagestest clears out GOROOT to work around golang/go#32849,
1720 // which isn't relevant here. Fill it back in so we can find the standard library.
1721 it.env.Env["GOROOT"] = build.Default.GOROOT
1722 it.goroot = build.Default.GOROOT
1723
1724 fn(it)
1725 })
1726 }
1727 }
1728
1729 func (c testConfig) processTest(t *testing.T, module, file string, contents []byte, opts *Options, want string) {
1730 t.Helper()
1731 c.test(t, func(t *goimportTest) {
1732 t.Helper()
1733 t.assertProcessEquals(module, file, contents, opts, want)
1734 })
1735 }
1736
1737 type goimportTest struct {
1738 *testing.T
1739 goroot string
1740 env *ProcessEnv
1741 exported *packagestest.Exported
1742 }
1743
1744 func (t *goimportTest) process(module, file string, contents []byte, opts *Options) ([]byte, error) {
1745 t.Helper()
1746 f := t.exported.File(module, file)
1747 if f == "" {
1748 t.Fatalf("%v not found in exported files (typo in filename?)", file)
1749 }
1750 return t.processNonModule(f, contents, opts)
1751 }
1752
1753 func (t *goimportTest) processNonModule(file string, contents []byte, opts *Options) ([]byte, error) {
1754 if contents == nil {
1755 var err error
1756 contents, err = os.ReadFile(file)
1757 if err != nil {
1758 return nil, err
1759 }
1760 }
1761 if opts == nil {
1762 opts = &Options{Comments: true, TabIndent: true, TabWidth: 8}
1763 }
1764 // ProcessEnv is not safe for concurrent use. Make a copy.
1765 opts.Env = t.env.CopyConfig()
1766 return Process(file, contents, opts)
1767 }
1768
1769 func (t *goimportTest) assertProcessEquals(module, file string, contents []byte, opts *Options, want string) {
1770 buf, err := t.process(module, file, contents, opts)
1771 if err != nil {
1772 t.Fatalf("Process() = %v", err)
1773 }
1774 if string(buf) != want {
1775 t.Errorf("Got:\n'%s'\nWant:\n'%s'", buf, want) // 's show empty lines
1776 }
1777 }
1778
1779 // Tests that added imports are renamed when the import path's base doesn't
1780 // match its package name.
1781 func TestRenameWhenPackageNameMismatch(t *testing.T) {
1782 const input = `package main
1783 const Y = bar.X`
1784
1785 const want = `package main
1786
1787 import bar "foo.com/foo/bar/baz"
1788
1789 const Y = bar.X
1790 `
1791 testConfig{
1792 module: packagestest.Module{
1793 Name: "foo.com",
1794 Files: fm{
1795 "foo/bar/baz/x.go": "package bar \n const X = 1",
1796 "test/t.go": input,
1797 },
1798 },
1799 }.processTest(t, "foo.com", "test/t.go", nil, nil, want)
1800 }
1801
1802 func TestPanicAstutils(t *testing.T) {
1803 t.Skip("panic in ast/astutil/imports.go, should be PostionFor(,false) at lines 273, 274, at least")
1804 const input = `package main
1805 //line mah.go:600
1806
1807 import (
1808 "foo.com/a.thing"
1809 "foo.com/surprise"
1810 "foo.com/v1"
1811 "foo.com/other/v2"
1812 "foo.com/other/v3"
1813 )
1814 `
1815
1816 const want = `package main
1817
1818 //line mah.go:600
1819
1820 import (
1821 "foo.com/a.thing"
1822 "foo.com/go-thing"
1823 gow "foo.com/go-wrong"
1824 v2 "foo.com/other/v2"
1825 "foo.com/other/v3"
1826 bar "foo.com/surprise"
1827 v1 "foo.com/v1"
1828 )
1829
1830 `
1831
1832 testConfig{
1833 module: packagestest.Module{
1834 Name: "foo.com",
1835 Files: fm{
1836 "test/t.go": input,
1837 },
1838 },
1839 }.processTest(t, "foo.com", "test/t.go", nil, nil, want)
1840 }
1841
1842 // without PositionFor in sortImports this test panics
1843 func TestPanic51916(t *testing.T) {
1844 const input = `package main
1845 //line mah.go:600
1846
1847 import (
1848 "foo.com/a.thing"
1849 "foo.com/surprise"
1850 "foo.com/v1"
1851 "foo.com/other/v2"
1852 "foo.com/other/v3"
1853 "foo.com/go-thing"
1854 "foo.com/go-wrong"
1855 )
1856
1857 var _ = []interface{}{bar.X, v1.Y, a.A, v2.V2, other.V3, thing.Thing, gow.Wrong}`
1858
1859 const want = `package main
1860
1861 //line mah.go:600
1862
1863 import (
1864 "foo.com/a.thing"
1865 "foo.com/go-thing"
1866 gow "foo.com/go-wrong"
1867 v2 "foo.com/other/v2"
1868 "foo.com/other/v3"
1869 bar "foo.com/surprise"
1870 v1 "foo.com/v1"
1871 )
1872
1873 var _ = []interface{}{bar.X, v1.Y, a.A, v2.V2, other.V3, thing.Thing, gow.Wrong}
1874 `
1875
1876 testConfig{
1877 module: packagestest.Module{
1878 Name: "foo.com",
1879 Files: fm{
1880 "a.thing/a.go": "package a \n const A = 1",
1881 "surprise/x.go": "package bar \n const X = 1",
1882 "v1/x.go": "package v1 \n const Y = 1",
1883 "other/v2/y.go": "package v2 \n const V2 = 1",
1884 "other/v3/z.go": "package other \n const V3 = 1",
1885 "go-thing/b.go": "package thing \n const Thing = 1",
1886 "go-wrong/b.go": "package gow \n const Wrong = 1",
1887 "test/t.go": input,
1888 },
1889 },
1890 }.processTest(t, "foo.com", "test/t.go", nil, nil, want)
1891 }
1892
1893 // Tests that an existing import with badly mismatched path/name has its name
1894 // correctly added. See #28645 and #29041.
1895 // and check that //line directives are ignored (#51916)
1896 func TestAddNameToMismatchedImport(t *testing.T) {
1897 const input = `package main
1898
1899 import (
1900 "foo.com/a.thing"
1901 "foo.com/surprise"
1902 "foo.com/v1"
1903 "foo.com/other/v2"
1904 "foo.com/other/v3"
1905 "foo.com/go-thing"
1906 "foo.com/go-wrong"
1907 )
1908
1909 var _ = []interface{}{bar.X, v1.Y, a.A, v2.V2, other.V3, thing.Thing, gow.Wrong}`
1910
1911 const want = `package main
1912
1913 import (
1914 "foo.com/a.thing"
1915 "foo.com/go-thing"
1916 gow "foo.com/go-wrong"
1917 v2 "foo.com/other/v2"
1918 "foo.com/other/v3"
1919 bar "foo.com/surprise"
1920 v1 "foo.com/v1"
1921 )
1922
1923 var _ = []interface{}{bar.X, v1.Y, a.A, v2.V2, other.V3, thing.Thing, gow.Wrong}
1924 `
1925
1926 testConfig{
1927 module: packagestest.Module{
1928 Name: "foo.com",
1929 Files: fm{
1930 "a.thing/a.go": "package a \n const A = 1",
1931 "surprise/x.go": "package bar \n const X = 1",
1932 "v1/x.go": "package v1 \n const Y = 1",
1933 "other/v2/y.go": "package v2 \n const V2 = 1",
1934 "other/v3/z.go": "package other \n const V3 = 1",
1935 "go-thing/b.go": "package thing \n const Thing = 1",
1936 "go-wrong/b.go": "package gow \n const Wrong = 1",
1937 "test/t.go": input,
1938 },
1939 },
1940 }.processTest(t, "foo.com", "test/t.go", nil, nil, want)
1941 }
1942
1943 // Tests that the LocalPrefix option causes imports
1944 // to be added into a later group (num=3).
1945 func TestLocalPrefix(t *testing.T) {
1946 tests := []struct {
1947 name string
1948 modules []packagestest.Module
1949 localPrefix string
1950 src string
1951 want string
1952 }{
1953 {
1954 name: "one_local",
1955 modules: []packagestest.Module{
1956 {
1957 Name: "foo.com",
1958 Files: fm{
1959 "bar/bar.go": "package bar \n const X = 1",
1960 },
1961 },
1962 },
1963 localPrefix: "foo.com/",
1964 src: "package main \n const Y = bar.X \n const _ = runtime.GOOS",
1965 want: `package main
1966
1967 import (
1968 "runtime"
1969
1970 "foo.com/bar"
1971 )
1972
1973 const Y = bar.X
1974 const _ = runtime.GOOS
1975 `,
1976 },
1977 {
1978 name: "two_local",
1979 modules: []packagestest.Module{
1980 {
1981 Name: "foo.com",
1982 Files: fm{
1983 "foo/foo.go": "package foo \n const X = 1",
1984 "foo/bar/bar.go": "package bar \n const X = 1",
1985 },
1986 },
1987 },
1988 localPrefix: "foo.com/foo",
1989 src: "package main \n const Y = bar.X \n const Z = foo.X \n const _ = runtime.GOOS",
1990 want: `package main
1991
1992 import (
1993 "runtime"
1994
1995 "foo.com/foo"
1996 "foo.com/foo/bar"
1997 )
1998
1999 const Y = bar.X
2000 const Z = foo.X
2001 const _ = runtime.GOOS
2002 `,
2003 },
2004 {
2005 name: "three_prefixes",
2006 modules: []packagestest.Module{
2007 {
2008 Name: "example.org/pkg",
2009 Files: fm{"pkg.go": "package pkg \n const A = 1"},
2010 },
2011 {
2012 Name: "foo.com",
2013 Files: fm{"bar/bar.go": "package bar \n const B = 1"},
2014 },
2015 {
2016 Name: "code.org/r/p",
2017 Files: fm{"expproj/expproj.go": "package expproj \n const C = 1"},
2018 },
2019 },
2020 localPrefix: "example.org/pkg,foo.com/,code.org",
2021 src: "package main \n const X = pkg.A \n const Y = bar.B \n const Z = expproj.C \n const _ = runtime.GOOS",
2022 want: `package main
2023
2024 import (
2025 "runtime"
2026
2027 "code.org/r/p/expproj"
2028 "example.org/pkg"
2029 "foo.com/bar"
2030 )
2031
2032 const X = pkg.A
2033 const Y = bar.B
2034 const Z = expproj.C
2035 const _ = runtime.GOOS
2036 `,
2037 },
2038 }
2039
2040 for _, tt := range tests {
2041 t.Run(tt.name, func(t *testing.T) {
2042 testConfig{
2043 // The module being processed has to be first so it's the primary module.
2044 modules: append([]packagestest.Module{{
2045 Name: "test.com",
2046 Files: fm{"t.go": tt.src},
2047 }}, tt.modules...),
2048 }.test(t, func(t *goimportTest) {
2049 options := &Options{
2050 LocalPrefix: tt.localPrefix,
2051 TabWidth: 8,
2052 TabIndent: true,
2053 Comments: true,
2054 Fragment: true,
2055 }
2056 t.assertProcessEquals("test.com", "t.go", nil, options, tt.want)
2057 })
2058 })
2059 }
2060 }
2061
2062 // Tests that "package documentation" files are ignored.
2063 func TestIgnoreDocumentationPackage(t *testing.T) {
2064 const input = `package x
2065
2066 const Y = foo.X
2067 `
2068 const want = `package x
2069
2070 import "foo.com/foo"
2071
2072 const Y = foo.X
2073 `
2074
2075 testConfig{
2076 module: packagestest.Module{
2077 Name: "foo.com",
2078 Files: fm{
2079 "foo/foo.go": "package foo\nconst X = 1\n",
2080 "foo/doc.go": "package documentation \n // just to confuse things\n",
2081 "x/x.go": input,
2082 },
2083 },
2084 }.processTest(t, "foo.com", "x/x.go", nil, nil, want)
2085 }
2086
2087 // Tests importPathToNameGoPathParse and in particular that it stops
2088 // after finding the first non-documentation package name, not
2089 // reporting an error on inconsistent package names (since it should
2090 // never make it that far).
2091 func TestImportPathToNameGoPathParse(t *testing.T) {
2092 testConfig{
2093 module: packagestest.Module{
2094 Name: "example.net/pkg",
2095 Files: fm{
2096 "doc.go": "package documentation\n", // ignored
2097 "gen.go": "package main\n", // also ignored
2098 "pkg.go": "package the_pkg_name_to_find\n and this syntax error is ignored because of parser.PackageClauseOnly",
2099 "z.go": "package inconsistent\n", // inconsistent but ignored
2100 },
2101 },
2102 }.test(t, func(t *goimportTest) {
2103 if strings.Contains(t.Name(), "GoPackages") {
2104 t.Skip("go/packages does not ignore package main")
2105 }
2106 r, err := t.env.GetResolver()
2107 if err != nil {
2108 t.Fatal(err)
2109 }
2110 srcDir := filepath.Dir(t.exported.File("example.net/pkg", "z.go"))
2111 names, err := r.loadPackageNames([]string{"example.net/pkg"}, srcDir)
2112 if err != nil {
2113 t.Fatal(err)
2114 }
2115 const want = "the_pkg_name_to_find"
2116 if got := names["example.net/pkg"]; got != want {
2117 t.Errorf("loadPackageNames(..) = %q; want %q", got, want)
2118 }
2119 })
2120 }
2121
2122 func TestIgnoreConfiguration(t *testing.T) {
2123 const input = `package x
2124
2125 const _ = pkg.X
2126 `
2127 const want = `package x
2128
2129 import "foo.com/otherwise-longer-so-worse-example/foo/pkg"
2130
2131 const _ = pkg.X
2132 `
2133
2134 testConfig{
2135 gopathOnly: true,
2136 module: packagestest.Module{
2137 Name: "foo.com",
2138 Files: fm{
2139 "../.goimportsignore": "# comment line\n\n foo.com/example", // tests comment, blank line, whitespace trimming
2140 "example/pkg/pkg.go": "package pkg\nconst X = 1",
2141 "otherwise-longer-so-worse-example/foo/pkg/pkg.go": "package pkg\nconst X = 1",
2142 "x/x.go": input,
2143 },
2144 },
2145 }.processTest(t, "foo.com", "x/x.go", nil, nil, want)
2146 }
2147
2148 // Skip "node_modules" directory.
2149 func TestSkipNodeModules(t *testing.T) {
2150 const input = `package x
2151
2152 const _ = pkg.X
2153 `
2154 const want = `package x
2155
2156 import "foo.com/otherwise-longer/not_modules/pkg"
2157
2158 const _ = pkg.X
2159 `
2160
2161 testConfig{
2162 gopathOnly: true,
2163 module: packagestest.Module{
2164 Name: "foo.com",
2165 Files: fm{
2166 "example/node_modules/pkg/a.go": "package pkg\nconst X = 1",
2167 "otherwise-longer/not_modules/pkg/a.go": "package pkg\nconst X = 1",
2168 "x/x.go": input,
2169 },
2170 },
2171 }.processTest(t, "foo.com", "x/x.go", nil, nil, want)
2172 }
2173
2174 // Tests that package global variables with the same name and function name as
2175 // a function in a separate package do not result in an import which masks
2176 // the global variable
2177 func TestGlobalImports(t *testing.T) {
2178 const usesGlobal = `package pkg
2179
2180 func doSomething() {
2181 t := time.Now()
2182 }
2183 `
2184
2185 const declaresGlobal = `package pkg
2186
2187 type Time struct{}
2188
2189 func (t Time) Now() Time {
2190 return Time{}
2191 }
2192
2193 var time Time
2194 `
2195
2196 testConfig{
2197 module: packagestest.Module{
2198 Name: "foo.com",
2199 Files: fm{
2200 "pkg/uses.go": usesGlobal,
2201 "pkg/global.go": declaresGlobal,
2202 },
2203 },
2204 }.processTest(t, "foo.com", "pkg/uses.go", nil, nil, usesGlobal)
2205 }
2206
2207 // Some people put multiple packages' files in the same directory. Globals
2208 // declared in other packages should be ignored.
2209 func TestGlobalImports_DifferentPackage(t *testing.T) {
2210 const declaresGlobal = `package main
2211 var fmt int
2212 `
2213 const input = `package pkg
2214 var _ = fmt.Printf
2215 `
2216 const want = `package pkg
2217
2218 import "fmt"
2219
2220 var _ = fmt.Printf
2221 `
2222
2223 testConfig{
2224 module: packagestest.Module{
2225 Name: "foo.com",
2226 Files: fm{
2227 "pkg/main.go": declaresGlobal,
2228 "pkg/uses.go": input,
2229 },
2230 },
2231 }.processTest(t, "foo.com", "pkg/uses.go", nil, nil, want)
2232 }
2233
2234 func TestGlobalImports_MultipleMains(t *testing.T) {
2235 const declaresGlobal = `package main
2236 var fmt int
2237 `
2238 const input = `package main
2239 import "fmt"
2240 var _, _ = fmt.Printf, bytes.Equal
2241 `
2242 const want = `package main
2243
2244 import (
2245 "bytes"
2246 "fmt"
2247 )
2248
2249 var _, _ = fmt.Printf, bytes.Equal
2250 `
2251
2252 testConfig{
2253 module: packagestest.Module{
2254 Name: "foo.com",
2255 Files: fm{
2256 "pkg/main.go": declaresGlobal,
2257 "pkg/uses.go": input,
2258 },
2259 },
2260 }.processTest(t, "foo.com", "pkg/uses.go", nil, nil, want)
2261 }
2262
2263 // Tests that sibling files - other files in the same package - can provide an
2264 // import that may not be the default one otherwise.
2265 func TestSiblingImports(t *testing.T) {
2266
2267 // provide is the sibling file that provides the desired import.
2268 const provide = `package siblingimporttest
2269
2270 import "local/log"
2271 import "my/bytes"
2272 import renamed "fmt"
2273
2274 func LogSomething() {
2275 log.Print("Something")
2276 bytes.SomeFunc()
2277 renamed.Println("Something")
2278 }
2279 `
2280
2281 // need is the file being tested that needs the import.
2282 const need = `package siblingimporttest
2283
2284 var _ = bytes.Buffer{}
2285
2286 func LogSomethingElse() {
2287 log.Print("Something else")
2288 renamed.Println("Yet another")
2289 }
2290 `
2291
2292 // want is the expected result file
2293 const want = `package siblingimporttest
2294
2295 import (
2296 "bytes"
2297 renamed "fmt"
2298 "local/log"
2299 )
2300
2301 var _ = bytes.Buffer{}
2302
2303 func LogSomethingElse() {
2304 log.Print("Something else")
2305 renamed.Println("Yet another")
2306 }
2307 `
2308
2309 testConfig{
2310 module: packagestest.Module{
2311 Name: "foo.com",
2312 Files: fm{
2313 "p/needs_import.go": need,
2314 "p/provides_import.go": provide,
2315 },
2316 },
2317 }.processTest(t, "foo.com", "p/needs_import.go", nil, nil, want)
2318 }
2319
2320 // Tests #29180: a sibling import of the right package with the wrong name is used.
2321 func TestSiblingImport_Misnamed(t *testing.T) {
2322 const sibling = `package main
2323 import renamed "fmt"
2324 var _ = renamed.Printf
2325 `
2326 const input = `package pkg
2327 var _ = fmt.Printf
2328 `
2329 const want = `package pkg
2330
2331 import "fmt"
2332
2333 var _ = fmt.Printf
2334 `
2335
2336 testConfig{
2337 module: packagestest.Module{
2338 Name: "foo.com",
2339 Files: fm{
2340 "pkg/main.go": sibling,
2341 "pkg/uses.go": input,
2342 },
2343 },
2344 }.processTest(t, "foo.com", "pkg/uses.go", nil, nil, want)
2345
2346 }
2347
2348 // Tests that an input file's own package is ignored.
2349 func TestIgnoreOwnPackage(t *testing.T) {
2350 const input = `package pkg
2351
2352 const _ = pkg.X
2353 `
2354 const want = `package pkg
2355
2356 const _ = pkg.X
2357 `
2358
2359 testConfig{
2360 module: packagestest.Module{
2361 Name: "foo.com",
2362 Files: fm{
2363 "pkg/a.go": "package pkg\nconst X = 1",
2364 "pkg/b.go": input,
2365 },
2366 },
2367 }.processTest(t, "foo.com", "pkg/b.go", nil, nil, want)
2368 }
2369
2370 func TestExternalTestImportsPackageUnderTest(t *testing.T) {
2371 const provide = `package pkg
2372 func DoIt(){}
2373 `
2374 const input = `package pkg_test
2375
2376 var _ = pkg.DoIt`
2377
2378 const want = `package pkg_test
2379
2380 import "foo.com/pkg"
2381
2382 var _ = pkg.DoIt
2383 `
2384
2385 testConfig{
2386 module: packagestest.Module{
2387 Name: "foo.com",
2388 Files: fm{
2389 "pkg/provide.go": provide,
2390 "pkg/x_test.go": input,
2391 },
2392 },
2393 }.processTest(t, "foo.com", "pkg/x_test.go", nil, nil, want)
2394 }
2395
2396 func TestPkgIsCandidate(t *testing.T) {
2397 tests := []struct {
2398 name string
2399 filename string
2400 pkgIdent string
2401 pkg *pkg
2402 want bool
2403 }{
2404 {
2405 name: "normal_match",
2406 filename: "/gopath/src/my/pkg/pkg.go",
2407 pkgIdent: "client",
2408 pkg: &pkg{
2409 dir: "/gopath/src/client",
2410 importPathShort: "client",
2411 },
2412 want: true,
2413 },
2414 {
2415 name: "no_match",
2416 filename: "/gopath/src/my/pkg/pkg.go",
2417 pkgIdent: "zzz",
2418 pkg: &pkg{
2419 dir: "/gopath/src/client",
2420 importPathShort: "client",
2421 },
2422 want: false,
2423 },
2424 {
2425 name: "match_too_early",
2426 filename: "/gopath/src/my/pkg/pkg.go",
2427 pkgIdent: "client",
2428 pkg: &pkg{
2429 dir: "/gopath/src/client/foo/foo/foo",
2430 importPathShort: "client/foo/foo",
2431 },
2432 want: false,
2433 },
2434 {
2435 name: "substring_match",
2436 filename: "/gopath/src/my/pkg/pkg.go",
2437 pkgIdent: "client",
2438 pkg: &pkg{
2439 dir: "/gopath/src/foo/go-client",
2440 importPathShort: "foo/go-client",
2441 },
2442 want: true,
2443 },
2444 {
2445 name: "hidden_internal",
2446 filename: "/gopath/src/my/pkg/pkg.go",
2447 pkgIdent: "client",
2448 pkg: &pkg{
2449 dir: "/gopath/src/foo/internal/client",
2450 importPathShort: "foo/internal/client",
2451 },
2452 want: false,
2453 },
2454 {
2455 name: "visible_internal",
2456 filename: "/gopath/src/foo/bar.go",
2457 pkgIdent: "client",
2458 pkg: &pkg{
2459 dir: "/gopath/src/foo/internal/client",
2460 importPathShort: "foo/internal/client",
2461 },
2462 want: true,
2463 },
2464 {
2465 name: "invisible_vendor",
2466 filename: "/gopath/src/foo/bar.go",
2467 pkgIdent: "client",
2468 pkg: &pkg{
2469 dir: "/gopath/src/other/vendor/client",
2470 importPathShort: "client",
2471 },
2472 want: false,
2473 },
2474 {
2475 name: "visible_vendor",
2476 filename: "/gopath/src/foo/bar.go",
2477 pkgIdent: "client",
2478 pkg: &pkg{
2479 dir: "/gopath/src/foo/vendor/client",
2480 importPathShort: "client",
2481 },
2482 want: true,
2483 },
2484 {
2485 name: "match_with_hyphens",
2486 filename: "/gopath/src/foo/bar.go",
2487 pkgIdent: "socketio",
2488 pkg: &pkg{
2489 dir: "/gopath/src/foo/socket-io",
2490 importPathShort: "foo/socket-io",
2491 },
2492 want: true,
2493 },
2494 {
2495 name: "match_with_mixed_case",
2496 filename: "/gopath/src/foo/bar.go",
2497 pkgIdent: "fooprod",
2498 pkg: &pkg{
2499 dir: "/gopath/src/foo/FooPROD",
2500 importPathShort: "foo/FooPROD",
2501 },
2502 want: true,
2503 },
2504 {
2505 name: "matches_with_hyphen_and_caps",
2506 filename: "/gopath/src/foo/bar.go",
2507 pkgIdent: "fooprod",
2508 pkg: &pkg{
2509 dir: "/gopath/src/foo/Foo-PROD",
2510 importPathShort: "foo/Foo-PROD",
2511 },
2512 want: true,
2513 },
2514 }
2515 for i, tt := range tests {
2516 t.Run(tt.name, func(t *testing.T) {
2517 refs := References{tt.pkgIdent: nil}
2518 got := pkgIsCandidate(tt.filename, refs, tt.pkg)
2519 if got != tt.want {
2520 t.Errorf("test %d. pkgIsCandidate(%q, %q, %+v) = %v; want %v",
2521 i, tt.filename, tt.pkgIdent, *tt.pkg, got, tt.want)
2522 }
2523 })
2524 }
2525 }
2526
2527 // Issue 20941: this used to panic on Windows.
2528 func TestProcessStdin(t *testing.T) {
2529 testConfig{
2530 module: packagestest.Module{
2531 Name: "foo.com",
2532 },
2533 }.test(t, func(t *goimportTest) {
2534 got, err := t.processNonModule("<standard input>", []byte("package main\nfunc main() {\n\tfmt.Println(123)\n}\n"), nil)
2535 if err != nil {
2536 t.Fatal(err)
2537 }
2538 if !strings.Contains(string(got), `"fmt"`) {
2539 t.Errorf("expected fmt import; got: %s", got)
2540 }
2541 })
2542 }
2543
2544 // Tests LocalPackagePromotion when there is a local package that matches, it
2545 // should be the closest match.
2546 // https://golang.org/issues/17557
2547 func TestLocalPackagePromotion(t *testing.T) {
2548 const input = `package main
2549 var c = &config.SystemConfig{}
2550 `
2551 const want = `package main
2552
2553 import "mycompany.net/tool/config"
2554
2555 var c = &config.SystemConfig{}
2556 `
2557
2558 testConfig{
2559 modules: []packagestest.Module{
2560 {
2561 Name: "config.net/config",
2562 Files: fm{"config.go": "package config\n type SystemConfig struct {}"}, // Will match but should not be first choice
2563 },
2564 {
2565 Name: "mycompany.net/config",
2566 Files: fm{"config.go": "package config\n type SystemConfig struct {}"}, // Will match but should not be first choice
2567 },
2568 {
2569 Name: "mycompany.net/tool",
2570 Files: fm{
2571 "config/config.go": "package config\n type SystemConfig struct {}", // Local package should be promoted over shorter package
2572 "main.go": input,
2573 },
2574 },
2575 },
2576 }.processTest(t, "mycompany.net/tool", "main.go", nil, nil, want)
2577 }
2578
2579 // Tests FindImportInLocalGoFiles looks at the import lines for other Go files in the
2580 // local directory, since the user is likely to import the same packages in the current
2581 // Go file. If an import is found that satisfies the need, it should be used over the
2582 // standard library.
2583 // https://golang.org/issues/17557
2584 func TestFindImportInLocalGoFiles(t *testing.T) {
2585 const input = `package main
2586 var _ = &bytes.Buffer{}`
2587
2588 const want = `package main
2589
2590 import "bytes.net/bytes"
2591
2592 var _ = &bytes.Buffer{}
2593 `
2594 testConfig{
2595 modules: []packagestest.Module{
2596 {
2597 Name: "mycompany.net/tool",
2598 Files: fm{
2599 "io.go": "package main\n import \"bytes.net/bytes\"\n var _ = &bytes.Buffer{}", // Contains package import that will cause stdlib to be ignored
2600 "main.go": input,
2601 },
2602 },
2603 {
2604 Name: "bytes.net/bytes",
2605 Files: fm{"bytes.go": "package bytes\n type Buffer struct {}"}, // Should be selected over standard library
2606 },
2607 },
2608 }.processTest(t, "mycompany.net/tool", "main.go", nil, nil, want)
2609 }
2610
2611 func TestInMemoryFile(t *testing.T) {
2612 const input = `package main
2613 var _ = &bytes.Buffer{}`
2614
2615 const want = `package main
2616
2617 import "bytes"
2618
2619 var _ = &bytes.Buffer{}
2620 `
2621 testConfig{
2622 module: packagestest.Module{
2623 Name: "foo.com",
2624 Files: fm{"x.go": "package x\n"},
2625 },
2626 }.processTest(t, "foo.com", "x.go", []byte(input), nil, want)
2627 }
2628
2629 func TestImportNoGoFiles(t *testing.T) {
2630 const input = `package main
2631 var _ = &bytes.Buffer{}`
2632
2633 const want = `package main
2634
2635 import "bytes"
2636
2637 var _ = &bytes.Buffer{}
2638 `
2639 testConfig{
2640 module: packagestest.Module{
2641 Name: "mycompany.net",
2642 },
2643 }.test(t, func(t *goimportTest) {
2644 buf, err := t.processNonModule("mycompany.net/tool/main.go", []byte(input), nil)
2645 if err != nil {
2646 t.Fatalf("Process() = %v", err)
2647 }
2648 if string(buf) != want {
2649 t.Errorf("Got:\n%s\nWant:\n%s", buf, want)
2650 }
2651 })
2652
2653 }
2654
2655 // Ensures a token as large as 500000 bytes can be handled
2656 // https://golang.org/issues/18201
2657 func TestProcessLargeToken(t *testing.T) {
2658 largeString := strings.Repeat("x", 500000)
2659
2660 input := `package testimports
2661
2662 import (
2663 "bytes"
2664 )
2665
2666 const s = fmt.Sprintf("%s", "` + largeString + `")
2667 var _ = bytes.Buffer{}
2668
2669 // end
2670 `
2671
2672 want := `package testimports
2673
2674 import (
2675 "bytes"
2676 "fmt"
2677 )
2678
2679 const s = fmt.Sprintf("%s", "` + largeString + `")
2680
2681 var _ = bytes.Buffer{}
2682
2683 // end
2684 `
2685
2686 testConfig{
2687 module: packagestest.Module{
2688 Name: "foo.com",
2689 Files: fm{"foo.go": input},
2690 },
2691 }.processTest(t, "foo.com", "foo.go", nil, nil, want)
2692 }
2693
2694 // Tests that an external test package will import the package under test if it
2695 // also uses symbols exported only in test files.
2696 // https://golang.org/issues/29979
2697 func TestExternalTest(t *testing.T) {
2698 const input = `package a_test
2699 func TestX() {
2700 a.X()
2701 a.Y()
2702 }
2703 `
2704 const want = `package a_test
2705
2706 import "foo.com/a"
2707
2708 func TestX() {
2709 a.X()
2710 a.Y()
2711 }
2712 `
2713
2714 testConfig{
2715 modules: []packagestest.Module{
2716 {
2717 Name: "foo.com/a",
2718 Files: fm{
2719 "a.go": "package a\n func X() {}",
2720 "export_test.go": "package a\n func Y() {}",
2721 "a_test.go": input,
2722 },
2723 },
2724 },
2725 }.processTest(t, "foo.com/a", "a_test.go", nil, nil, want)
2726 }
2727
2728 // TestGetCandidates tests that get packages finds packages
2729 // with correct priorities.
2730 func TestGetCandidates(t *testing.T) {
2731 type res struct {
2732 relevance float64
2733 name, path string
2734 }
2735 want := []res{
2736 {0, "bytes", "bytes"},
2737 {0, "http", "net/http"},
2738 {0, "rand", "crypto/rand"},
2739 {0, "bar", "bar.com/bar"},
2740 {0, "foo", "foo.com/foo"},
2741 }
2742
2743 testConfig{
2744 modules: []packagestest.Module{
2745 {
2746 Name: "bar.com",
2747 Files: fm{"bar/bar.go": "package bar\n"},
2748 },
2749 {
2750 Name: "foo.com",
2751 Files: fm{"foo/foo.go": "package foo\n"},
2752 },
2753 },
2754 }.test(t, func(t *goimportTest) {
2755 var mu sync.Mutex
2756 var got []res
2757 add := func(c ImportFix) {
2758 mu.Lock()
2759 defer mu.Unlock()
2760 for _, w := range want {
2761 if c.StmtInfo.ImportPath == w.path {
2762 got = append(got, res{c.Relevance, c.IdentName, c.StmtInfo.ImportPath})
2763 }
2764 }
2765 }
2766 if err := GetAllCandidates(context.Background(), add, "", "x.go", "x", t.env); err != nil {
2767 t.Fatalf("GetAllCandidates() = %v", err)
2768 }
2769 // Sort, then clear out relevance so it doesn't mess up the DeepEqual.
2770 sort.Slice(got, func(i, j int) bool {
2771 ri, rj := got[i], got[j]
2772 if ri.relevance != rj.relevance {
2773 return ri.relevance > rj.relevance // Highest first.
2774 }
2775 return ri.name < rj.name
2776 })
2777 for i := range got {
2778 got[i].relevance = 0
2779 }
2780 if !reflect.DeepEqual(want, got) {
2781 t.Errorf("wanted results in order %v, got %v", want, got)
2782 }
2783 })
2784 }
2785
2786 func TestGetImportPaths(t *testing.T) {
2787 type res struct {
2788 relevance float64
2789 name, path string
2790 }
2791 want := []res{
2792 {0, "http", "net/http"},
2793 {0, "net", "net"},
2794 {0, "neta", "neta.com/neta"},
2795 }
2796
2797 testConfig{
2798 modules: []packagestest.Module{
2799 {
2800 Name: "neta.com",
2801 Files: fm{"neta/neta.go": "package neta\n"},
2802 },
2803 },
2804 }.test(t, func(t *goimportTest) {
2805 var mu sync.Mutex
2806 var got []res
2807 add := func(c ImportFix) {
2808 mu.Lock()
2809 defer mu.Unlock()
2810 for _, w := range want {
2811 if c.StmtInfo.ImportPath == w.path {
2812 got = append(got, res{c.Relevance, c.IdentName, c.StmtInfo.ImportPath})
2813 }
2814 }
2815 }
2816 if err := GetImportPaths(context.Background(), add, "ne", "x.go", "x", t.env); err != nil {
2817 t.Fatalf("GetImportPaths() = %v", err)
2818 }
2819 // Sort, then clear out relevance so it doesn't mess up the DeepEqual.
2820 sort.Slice(got, func(i, j int) bool {
2821 ri, rj := got[i], got[j]
2822 if ri.relevance != rj.relevance {
2823 return ri.relevance > rj.relevance // Highest first.
2824 }
2825 return ri.name < rj.name
2826 })
2827 for i := range got {
2828 got[i].relevance = 0
2829 }
2830 if !reflect.DeepEqual(want, got) {
2831 t.Errorf("wanted results in order %v, got %v", want, got)
2832 }
2833 })
2834 }
2835
2836 func TestGetPackageCompletions(t *testing.T) {
2837 type res struct {
2838 relevance float64
2839 name, path, symbol string
2840 }
2841 want := []res{
2842 {0, "rand", "math/rand", "Seed"},
2843 {0, "rand", "bar.com/rand", "Bar"},
2844 }
2845
2846 testConfig{
2847 modules: []packagestest.Module{
2848 {
2849 Name: "bar.com",
2850 Files: fm{"rand/bar.go": "package rand\nvar Bar int\n"},
2851 },
2852 },
2853 }.test(t, func(t *goimportTest) {
2854 var mu sync.Mutex
2855 var got []res
2856 add := func(c PackageExport) {
2857 mu.Lock()
2858 defer mu.Unlock()
2859 for _, csym := range c.Exports {
2860 for _, w := range want {
2861 if c.Fix.StmtInfo.ImportPath == w.path && csym.Name == w.symbol {
2862 got = append(got, res{c.Fix.Relevance, c.Fix.IdentName, c.Fix.StmtInfo.ImportPath, csym.Name})
2863 }
2864 }
2865 }
2866 }
2867 if err := GetPackageExports(context.Background(), add, "rand", "x.go", "x", t.env); err != nil {
2868 t.Fatalf("getPackageCompletions() = %v", err)
2869 }
2870 // Sort, then clear out relevance so it doesn't mess up the DeepEqual.
2871 sort.Slice(got, func(i, j int) bool {
2872 ri, rj := got[i], got[j]
2873 if ri.relevance != rj.relevance {
2874 return ri.relevance > rj.relevance // Highest first.
2875 }
2876 return ri.name < rj.name
2877 })
2878 for i := range got {
2879 got[i].relevance = 0
2880 }
2881 if !reflect.DeepEqual(want, got) {
2882 t.Errorf("wanted results in order %v, got %v", want, got)
2883 }
2884 })
2885 }
2886
2887 // Tests #34895: process should not panic on concurrent calls.
2888 func TestConcurrentProcess(t *testing.T) {
2889 testConfig{
2890 module: packagestest.Module{
2891 Name: "foo.com",
2892 Files: fm{
2893 "p/first.go": `package foo
2894
2895 func _() {
2896 fmt.Println()
2897 }
2898 `,
2899 "p/second.go": `package foo
2900
2901 import "fmt"
2902
2903 func _() {
2904 fmt.Println()
2905 imports.Bar() // not imported.
2906 }
2907 `,
2908 },
2909 },
2910 }.test(t, func(t *goimportTest) {
2911 var (
2912 n = 10
2913 wg sync.WaitGroup
2914 )
2915 wg.Add(n)
2916 for range n {
2917 go func() {
2918 defer wg.Done()
2919 _, err := t.process("foo.com", "p/first.go", nil, nil)
2920 if err != nil {
2921 t.Error(err)
2922 }
2923 }()
2924 }
2925 wg.Wait()
2926 })
2927 }
2928
2929 func TestNonlocalDot(t *testing.T) {
2930 const input = `package main
2931 import (
2932 "fmt"
2933 )
2934 var _, _ = fmt.Sprintf, dot.Dot
2935 `
2936 const want = `package main
2937
2938 import (
2939 "fmt"
2940 "noninternet/dot.v1/dot"
2941 )
2942
2943 var _, _ = fmt.Sprintf, dot.Dot
2944 `
2945 testConfig{
2946 modules: []packagestest.Module{
2947 {
2948 Name: "golang.org/fake",
2949 Files: fm{"x.go": input},
2950 },
2951 {
2952 Name: "noninternet/dot.v1",
2953 Files: fm{
2954 "dot/dot.go": "package dot\nfunc Dot(){}\n",
2955 },
2956 },
2957 },
2958 gopathOnly: true, // our modules testing setup doesn't allow modules without dots.
2959 }.processTest(t, "golang.org/fake", "x.go", nil, nil, want)
2960 }
2961
2962 func TestSymbolSearchStarvation(t *testing.T) {
2963 // This test verifies the fix for golang/go#67923: searching through
2964 // candidates should not starve when the context is cancelled.
2965 //
2966 // To reproduce the conditions that led to starvation, cancel the context
2967 // half way through the search, by leveraging the loadExports callback.
2968 const candCount = 100
2969 var loaded atomic.Int32
2970 ctx, cancel := context.WithCancel(context.Background())
2971 searcher := symbolSearcher{
2972 logf: t.Logf,
2973 srcDir: "/path/to/foo",
2974 loadExports: func(ctx context.Context, pkg *pkg, includeTest bool) (string, []stdlib.Symbol, error) {
2975 if loaded.Add(1) > candCount/2 {
2976 cancel()
2977 }
2978 return "bar", []stdlib.Symbol{
2979 {Name: "A", Kind: stdlib.Var},
2980 {Name: "B", Kind: stdlib.Var},
2981 // Missing: "C", so that none of these packages match.
2982 }, nil
2983 },
2984 }
2985
2986 var candidates []pkgDistance
2987 for i := range candCount {
2988 name := fmt.Sprintf("bar%d", i)
2989 candidates = append(candidates, pkgDistance{
2990 pkg: &pkg{
2991 dir: path.Join(searcher.srcDir, name),
2992 importPathShort: "foo/" + name,
2993 packageName: name,
2994 relevance: 1,
2995 },
2996 distance: 1,
2997 })
2998 }
2999
3000 // We don't actually care what happens, as long as it doesn't deadlock!
3001 _, err := searcher.search(ctx, candidates, "bar", map[string]bool{"A": true, "B": true, "C": true})
3002 t.Logf("search completed with err: %v", err)
3003 }
3004
3005 func TestMatchesPath(t *testing.T) {
3006 tests := []struct {
3007 ident string
3008 path string
3009 want bool
3010 }{
3011 // degenerate cases
3012 {"", "", true},
3013 {"", "x", false},
3014 {"x", "", false},
3015
3016 // full segment matching
3017 {"x", "x", true},
3018 {"x", "y", false},
3019 {"x", "wx", false},
3020 {"x", "path/to/x", true},
3021 {"mypkg", "path/to/mypkg", true},
3022 {"x", "path/to/xy", false},
3023 {"x", "path/to/x/y", true},
3024 {"mypkg", "path/to/mypkg/y", true},
3025 {"x", "path/to/x/v3", true},
3026
3027 // subsegment matching
3028 {"x", "path/to/x-go", true},
3029 {"foo", "path/to/go-foo", true},
3030 {"go", "path/to/go-foo", true},
3031 {"gofoo", "path/to/go-foo", true},
3032 {"gofoo", "path/to/go-foo-bar", false},
3033 {"foo", "path/to/go-foo-bar", true},
3034 {"bar", "path/to/go-foo-bar", true},
3035 {"gofoobar", "path/to/go-foo-bar", true},
3036 {"x", "path/to/x.v3", true},
3037 {"x", "path/to/xy.v3", false},
3038 {"x", "path/to/wx.v3", false},
3039
3040 // case insensitivity
3041 {"MyPkg", "path/to/mypkg", true},
3042 {"myPkg", "path/to/MyPkg", true},
3043
3044 // multi-byte runes
3045 {"世界", "path/to/世界", true},
3046 {"世界", "path/to/世界/foo", true},
3047 {"世界", "path/to/go-世界/foo", true},
3048 {"世界", "path/to/世/foo", false},
3049 }
3050
3051 for _, test := range tests {
3052 if got := matchesPath(test.ident, test.path); got != test.want {
3053 t.Errorf("matchesPath(%q, %q) = %v, want %v", test.ident, test.path, got, test.want)
3054 }
3055 }
3056 }
3057
3058 func BenchmarkMatchesPath(b *testing.B) {
3059 // A collection of calls that exercise different kinds of matching.
3060 tests := map[string][]struct {
3061 ident string
3062 path string
3063 want bool
3064 }{
3065 "easy": { // lower case ascii
3066 {"mypkg", "path/to/mypkg/y", true},
3067 {"foo", "path/to/go-foo-bar", true},
3068 {"gofoo", "path/to/go-foo-bar-baz", false},
3069 },
3070 "hard": {
3071 {"MyPkg", "path/to/mypkg", true},
3072 {"世界", "path/to/go-世界-pkg/foo", true},
3073 {"longpkgname", "cloud.google.com/Go/Spanner/Admin/Database/longpkgname", true},
3074 },
3075 }
3076
3077 for name, tests := range tests {
3078 b.Run(name, func(b *testing.B) {
3079 for b.Loop() {
3080 for _, test := range tests {
3081 if got := matchesPath(test.ident, test.path); got != test.want {
3082 b.Errorf("matchesPath(%q, %q) = %v, want %v", test.ident, test.path, got, test.want)
3083 }
3084 }
3085 }
3086 })
3087 }
3088 }