...
1
2
3
4
5 package imports
6
7 import (
8 "bytes"
9 "internal/testenv"
10 "os"
11 "path"
12 "path/filepath"
13 "strings"
14 "testing"
15 )
16
17 func TestScan(t *testing.T) {
18 testenv.MustHaveGoBuild(t)
19
20 imports, testImports, err := ScanDir(filepath.Join(testenv.GOROOT(t), "src/encoding/json"), Tags())
21 if err != nil {
22 t.Fatal(err)
23 }
24 foundBase64 := false
25 for _, p := range imports {
26 if p == "encoding/base64" {
27 foundBase64 = true
28 }
29 if p == "encoding/binary" {
30
31 t.Errorf("json reported as importing encoding/binary but does not")
32 }
33 if p == "net/http" {
34
35 t.Errorf("json reported as importing net/http but does not")
36 }
37 }
38 if !foundBase64 {
39 t.Errorf("json missing import encoding/base64 (%q)", imports)
40 }
41
42 foundHTTP := false
43 for _, p := range testImports {
44 if p == "net/http" {
45 foundHTTP = true
46 }
47 if p == "unicode/utf16" {
48
49 t.Errorf("json reported as test-importing unicode/utf16 but does not")
50 }
51 }
52 if !foundHTTP {
53 t.Errorf("json missing test import net/http (%q)", testImports)
54 }
55 }
56 func TestScanDir(t *testing.T) {
57 testenv.MustHaveGoBuild(t)
58
59 dirs, err := os.ReadDir("testdata")
60 if err != nil {
61 t.Fatal(err)
62 }
63 for _, dir := range dirs {
64 if !dir.IsDir() || strings.HasPrefix(dir.Name(), ".") {
65 continue
66 }
67 t.Run(dir.Name(), func(t *testing.T) {
68 tagsData, err := os.ReadFile(filepath.Join("testdata", dir.Name(), "tags.txt"))
69 if err != nil {
70 t.Fatalf("error reading tags: %v", err)
71 }
72 tags := make(map[string]bool)
73 for _, t := range strings.Fields(string(tagsData)) {
74 tags[t] = true
75 }
76
77 wantData, err := os.ReadFile(filepath.Join("testdata", dir.Name(), "want.txt"))
78 if err != nil {
79 t.Fatalf("error reading want: %v", err)
80 }
81 want := string(bytes.TrimSpace(wantData))
82
83 imports, _, err := ScanDir(path.Join("testdata", dir.Name()), tags)
84 if err != nil {
85 t.Fatal(err)
86 }
87 got := strings.Join(imports, "\n")
88 if got != want {
89 t.Errorf("ScanDir: got imports:\n%s\n\nwant:\n%s", got, want)
90 }
91 })
92 }
93 }
94
View as plain text