-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathdeadcode_test.go
190 lines (176 loc) · 4.63 KB
/
deadcode_test.go
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
// Copyright 2023 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.
//go:build go1.20
package main_test
import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"testing"
"golang.org/x/tools/internal/testenv"
"golang.org/x/tools/txtar"
)
// Test runs the deadcode command on each scenario
// described by a testdata/*.txtar file.
func Test(t *testing.T) {
testenv.NeedsTool(t, "go")
if runtime.GOOS == "android" {
t.Skipf("the dependencies are not available on android")
}
exe := buildDeadcode(t)
matches, err := filepath.Glob("testdata/*.txtar")
if err != nil {
t.Fatal(err)
}
for _, filename := range matches {
filename := filename
t.Run(filename, func(t *testing.T) {
t.Parallel()
ar, err := txtar.ParseFile(filename)
if err != nil {
t.Fatal(err)
}
// Write the archive files to the temp directory.
tmpdir := t.TempDir()
for _, f := range ar.Files {
filename := filepath.Join(tmpdir, f.Name)
if err := os.MkdirAll(filepath.Dir(filename), 0777); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filename, f.Data, 0666); err != nil {
t.Fatal(err)
}
}
// Parse archive comment as directives of these forms:
//
// [!]deadcode args... command-line arguments
// [!]want arg expected/unwanted string in output (or stderr)
//
// Args may be Go-quoted strings.
type testcase struct {
linenum int
args []string
wantErr bool
want map[string]bool // string -> sense
}
var cases []*testcase
var current *testcase
for i, line := range strings.Split(string(ar.Comment), "\n") {
line = strings.TrimSpace(line)
if line == "" || line[0] == '#' {
continue // skip blanks and comments
}
words, err := words(line)
if err != nil {
t.Fatalf("cannot break line into words: %v (%s)", err, line)
}
switch kind := words[0]; kind {
case "deadcode", "!deadcode":
current = &testcase{
linenum: i + 1,
want: make(map[string]bool),
args: words[1:],
wantErr: kind[0] == '!',
}
cases = append(cases, current)
case "want", "!want":
if current == nil {
t.Fatalf("'want' directive must be after 'deadcode'")
}
if len(words) != 2 {
t.Fatalf("'want' directive needs argument <<%s>>", line)
}
current.want[words[1]] = kind[0] != '!'
default:
t.Fatalf("%s: invalid directive %q", filename, kind)
}
}
for _, tc := range cases {
t.Run(fmt.Sprintf("L%d", tc.linenum), func(t *testing.T) {
// Run the command.
cmd := exec.Command(exe, tc.args...)
cmd.Stdout = new(bytes.Buffer)
cmd.Stderr = new(bytes.Buffer)
cmd.Dir = tmpdir
cmd.Env = append(os.Environ(), "GOPROXY=", "GO111MODULE=on")
var got string
if err := cmd.Run(); err != nil {
switch err.(type) {
case *exec.ExitError:
if tc.wantErr {
got = fmt.Sprint(cmd.Stderr)
} else {
// If an unreachable code is detected, exit code 1 is notified
if cmd.ProcessState.ExitCode() != 1 {
t.Fatalf("deadcode failed: %v", err)
}
got = fmt.Sprint(cmd.Stdout)
}
default:
t.Fatalf("deadcode failed: %v", err)
}
} else {
got = fmt.Sprint(cmd.Stdout)
}
// Check each want directive.
for str, sense := range tc.want {
ok := true
if strings.Contains(got, str) != sense {
if sense {
t.Errorf("missing %q", str)
} else {
t.Errorf("unwanted %q", str)
}
ok = false
}
if !ok {
t.Errorf("got: <<%s>>", got)
}
}
})
}
})
}
}
// buildDeadcode builds the deadcode executable.
// It returns its path, and a cleanup function.
func buildDeadcode(t *testing.T) string {
bin := filepath.Join(t.TempDir(), "deadcode")
if runtime.GOOS == "windows" {
bin += ".exe"
}
cmd := exec.Command("go", "build", "-o", bin)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("Building deadcode: %v\n%s", err, out)
}
return bin
}
// words breaks a string into words, respecting
// Go string quotations around words with spaces.
func words(s string) ([]string, error) {
var words []string
for s != "" {
s = strings.TrimSpace(s)
var word string
if s[0] == '"' || s[0] == '`' {
prefix, err := strconv.QuotedPrefix(s)
if err != nil {
return nil, err
}
s = s[len(prefix):]
word, _ = strconv.Unquote(prefix)
} else {
prefix, rest, _ := strings.Cut(s, " ")
s = rest
word = prefix
}
words = append(words, word)
}
return words, nil
}