summaryrefslogtreecommitdiffstats
path: root/src/cmd/go/internal/imports/scan_test.go
blob: 56efa9023f19906154ec87178a0b04f30ce7b3ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package imports

import (
	"bytes"
	"internal/testenv"
	"os"
	"path"
	"path/filepath"
	"strings"
	"testing"
)

func TestScan(t *testing.T) {
	testenv.MustHaveGoBuild(t)

	imports, testImports, err := ScanDir(filepath.Join(testenv.GOROOT(t), "src/encoding/json"), Tags())
	if err != nil {
		t.Fatal(err)
	}
	foundBase64 := false
	for _, p := range imports {
		if p == "encoding/base64" {
			foundBase64 = true
		}
		if p == "encoding/binary" {
			// A dependency but not an import
			t.Errorf("json reported as importing encoding/binary but does not")
		}
		if p == "net/http" {
			// A test import but not an import
			t.Errorf("json reported as importing net/http but does not")
		}
	}
	if !foundBase64 {
		t.Errorf("json missing import encoding/base64 (%q)", imports)
	}

	foundHTTP := false
	for _, p := range testImports {
		if p == "net/http" {
			foundHTTP = true
		}
		if p == "unicode/utf16" {
			// A package import but not a test import
			t.Errorf("json reported as test-importing unicode/utf16  but does not")
		}
	}
	if !foundHTTP {
		t.Errorf("json missing test import net/http (%q)", testImports)
	}
}
func TestScanDir(t *testing.T) {
	testenv.MustHaveGoBuild(t)

	dirs, err := os.ReadDir("testdata")
	if err != nil {
		t.Fatal(err)
	}
	for _, dir := range dirs {
		if !dir.IsDir() || strings.HasPrefix(dir.Name(), ".") {
			continue
		}
		t.Run(dir.Name(), func(t *testing.T) {
			tagsData, err := os.ReadFile(filepath.Join("testdata", dir.Name(), "tags.txt"))
			if err != nil {
				t.Fatalf("error reading tags: %v", err)
			}
			tags := make(map[string]bool)
			for _, t := range strings.Fields(string(tagsData)) {
				tags[t] = true
			}

			wantData, err := os.ReadFile(filepath.Join("testdata", dir.Name(), "want.txt"))
			if err != nil {
				t.Fatalf("error reading want: %v", err)
			}
			want := string(bytes.TrimSpace(wantData))

			imports, _, err := ScanDir(path.Join("testdata", dir.Name()), tags)
			if err != nil {
				t.Fatal(err)
			}
			got := strings.Join(imports, "\n")
			if got != want {
				t.Errorf("ScanDir: got imports:\n%s\n\nwant:\n%s", got, want)
			}
		})
	}
}