/
errcheck_test.go
469 lines (410 loc) · 11.6 KB
/
errcheck_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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
package errcheck
import (
"fmt"
"io/ioutil"
"os"
"path"
"regexp"
"testing"
"golang.org/x/tools/go/packages"
)
const testPackage = "github.com/kisielk/errcheck/testdata"
var (
uncheckedMarkers map[marker]bool
blankMarkers map[marker]bool
assertMarkers map[marker]bool
)
type marker struct {
file string
line int
}
func newMarker(e UncheckedError) marker {
return marker{e.Pos.Filename, e.Pos.Line}
}
func (m marker) String() string {
return fmt.Sprintf("%s:%d", m.file, m.line)
}
func init() {
uncheckedMarkers = make(map[marker]bool)
blankMarkers = make(map[marker]bool)
assertMarkers = make(map[marker]bool)
cfg := &packages.Config{
Mode: packages.LoadSyntax,
Tests: true,
}
pkgs, err := packages.Load(cfg, testPackage)
if err != nil {
panic(fmt.Errorf("failed to import test package: %v", err))
}
for _, pkg := range pkgs {
for _, file := range pkg.Syntax {
for _, comment := range file.Comments {
text := comment.Text()
pos := pkg.Fset.Position(comment.Pos())
m := marker{pos.Filename, pos.Line}
switch text {
case "UNCHECKED\n":
uncheckedMarkers[m] = true
case "BLANK\n":
blankMarkers[m] = true
case "ASSERT\n":
assertMarkers[m] = true
}
}
}
}
}
type flags uint
const (
CheckAsserts flags = 1 << iota
CheckBlank
)
// TestUnchecked runs a test against the example files and ensures all unchecked errors are caught.
func TestUnchecked(t *testing.T) {
test(t, 0)
}
// TestBlank is like TestUnchecked but also ensures assignments to the blank identifier are caught.
func TestBlank(t *testing.T) {
test(t, CheckBlank)
}
func TestAll(t *testing.T) {
// TODO: CheckAsserts should work independently of CheckBlank
test(t, CheckAsserts|CheckBlank)
}
func TestBuildTags(t *testing.T) {
const (
// uses "custom1" build tag and contains 1 unchecked error
testBuildCustom1Tag = `
` + `// +build custom1
package custom
import "fmt"
func Print1() {
// returns an error that is not checked
fmt.Fprintln(nil)
}`
// uses "custom2" build tag and contains 1 unchecked error
testBuildCustom2Tag = `
` + `// +build custom2
package custom
import "fmt"
func Print2() {
// returns an error that is not checked
fmt.Fprintln(nil)
}`
// included so that package is not empty when built without specifying tags
testDoc = `
// Package custom contains code for testing build tags.
package custom
`
)
tmpGopath, err := ioutil.TempDir("", "testbuildtags")
if err != nil {
t.Fatalf("unable to create testbuildtags directory: %v", err)
}
testBuildTagsDir := path.Join(tmpGopath, "src", "github.com/testbuildtags")
if err := os.MkdirAll(testBuildTagsDir, 0755); err != nil {
t.Fatalf("MkdirAll failed: %v", err)
}
defer func() {
os.RemoveAll(tmpGopath)
}()
if err := ioutil.WriteFile(path.Join(testBuildTagsDir, "go.mod"), []byte("module github.com/testbuildtags"), 0644); err != nil {
t.Fatalf("Failed to write testbuildtags go.mod: %v", err)
}
if err := ioutil.WriteFile(path.Join(testBuildTagsDir, "custom1.go"), []byte(testBuildCustom1Tag), 0644); err != nil {
t.Fatalf("Failed to write testbuildtags custom1: %v", err)
}
if err := ioutil.WriteFile(path.Join(testBuildTagsDir, "custom2.go"), []byte(testBuildCustom2Tag), 0644); err != nil {
t.Fatalf("Failed to write testbuildtags custom2: %v", err)
}
if err := ioutil.WriteFile(path.Join(testBuildTagsDir, "doc.go"), []byte(testDoc), 0644); err != nil {
t.Fatalf("Failed to write testbuildtags doc: %v", err)
}
cases := []struct {
tags []string
numExpectedErrs int
}{
// with no tags specified, main is ignored and there are no errors
{
tags: nil,
numExpectedErrs: 0,
},
// specifying "custom1" tag includes file with 1 error
{
tags: []string{"custom1"},
numExpectedErrs: 1,
},
// specifying "custom1" and "custom2" tags includes 2 files with 1 error each
{
tags: []string{"custom1", "custom2"},
numExpectedErrs: 2,
},
}
for i, currCase := range cases {
checker := NewChecker()
checker.Tags = currCase.tags
loadPackages = func(cfg *packages.Config, paths ...string) ([]*packages.Package, error) {
cfg.Env = append(os.Environ(),
"GOPATH="+tmpGopath)
cfg.Dir = testBuildTagsDir
pkgs, err := packages.Load(cfg, paths...)
return pkgs, err
}
err := checker.CheckPackages("github.com/testbuildtags")
if currCase.numExpectedErrs == 0 {
if err != nil {
t.Errorf("Case %d: expected no errors, but got: %v", i, err)
}
continue
}
uerr, ok := err.(*UncheckedErrors)
if !ok {
t.Errorf("Case %d: wrong error type returned: %v", i, err)
continue
}
if currCase.numExpectedErrs != len(uerr.Errors) {
t.Errorf("Case %d:\nExpected: %d errors\nActual: %d errors", i, currCase.numExpectedErrs, len(uerr.Errors))
}
}
}
func TestWhitelist(t *testing.T) {
}
func TestIgnore(t *testing.T) {
const testVendorGoMod = `module github.com/testvendor
require github.com/testlog v0.0.0
`
const testVendorMain = `
package main
import "github.com/testlog"
func main() {
// returns an error that is not checked
testlog.Info()
}`
const testLog = `
package testlog
func Info() error {
return nil
}`
// copy testvendor directory into directory for test
tmpGopath, err := ioutil.TempDir("", "testvendor")
if err != nil {
t.Fatalf("unable to create testvendor directory: %v", err)
}
testVendorDir := path.Join(tmpGopath, "src", "github.com/testvendor")
if err := os.MkdirAll(testVendorDir, 0755); err != nil {
t.Fatalf("MkdirAll failed: %v", err)
}
defer func() {
os.RemoveAll(tmpGopath)
}()
if err := ioutil.WriteFile(path.Join(testVendorDir, "go.mod"), []byte(testVendorGoMod), 0755); err != nil {
t.Fatalf("Failed to write testvendor go.mod: %v", err)
}
if err := ioutil.WriteFile(path.Join(testVendorDir, "main.go"), []byte(testVendorMain), 0755); err != nil {
t.Fatalf("Failed to write testvendor main: %v", err)
}
if err := os.MkdirAll(path.Join(testVendorDir, "vendor/github.com/testlog"), 0755); err != nil {
t.Fatalf("MkdirAll failed: %v", err)
}
if err := ioutil.WriteFile(path.Join(testVendorDir, "vendor/github.com/testlog/testlog.go"), []byte(testLog), 0755); err != nil {
t.Fatalf("Failed to write testlog: %v", err)
}
cases := []struct {
ignore map[string]*regexp.Regexp
numExpectedErrs int
}{
// basic case has one error
{
ignore: nil,
numExpectedErrs: 1,
},
// ignoring vendored import works
{
ignore: map[string]*regexp.Regexp{
path.Join("github.com/testvendor/vendor/github.com/testlog"): regexp.MustCompile("Info"),
},
},
// non-vendored path ignores vendored import
{
ignore: map[string]*regexp.Regexp{
"github.com/testlog": regexp.MustCompile("Info"),
},
},
}
for i, currCase := range cases {
checker := NewChecker()
checker.Ignore = currCase.ignore
loadPackages = func(cfg *packages.Config, paths ...string) ([]*packages.Package, error) {
cfg.Env = append(os.Environ(),
"GOPATH="+tmpGopath,
"GOFLAGS=-mod=vendor")
cfg.Dir = testVendorDir
pkgs, err := packages.Load(cfg, paths...)
return pkgs, err
}
err := checker.CheckPackages("github.com/testvendor")
if currCase.numExpectedErrs == 0 {
if err != nil {
t.Errorf("Case %d: expected no errors, but got: %v", i, err)
}
continue
}
uerr, ok := err.(*UncheckedErrors)
if !ok {
t.Errorf("Case %d: wrong error type returned: %v", i, err)
continue
}
if currCase.numExpectedErrs != len(uerr.Errors) {
t.Errorf("Case %d:\nExpected: %d errors\nActual: %d errors", i, currCase.numExpectedErrs, len(uerr.Errors))
}
}
}
func TestWithoutGeneratedCode(t *testing.T) {
const testVendorGoMod = `module github.com/testvendor
require github.com/testlog v0.0.0
`
const testVendorMain = `
// Code generated by protoc-gen-go. DO NOT EDIT.
package main
import "github.com/testlog"
func main() {
// returns an error that is not checked
testlog.Info()
}`
const testLog = `
package testlog
func Info() error {
return nil
}`
// copy testvendor directory into directory for test
tmpGopath, err := ioutil.TempDir("", "testvendor")
if err != nil {
t.Fatalf("unable to create testvendor directory: %v", err)
}
testVendorDir := path.Join(tmpGopath, "src", "github.com/testvendor")
if err := os.MkdirAll(testVendorDir, 0755); err != nil {
t.Fatalf("MkdirAll failed: %v", err)
}
defer func() {
os.RemoveAll(tmpGopath)
}()
if err := ioutil.WriteFile(path.Join(testVendorDir, "go.mod"), []byte(testVendorGoMod), 0755); err != nil {
t.Fatalf("Failed to write testvendor go.mod: %v", err)
}
if err := ioutil.WriteFile(path.Join(testVendorDir, "main.go"), []byte(testVendorMain), 0755); err != nil {
t.Fatalf("Failed to write testvendor main: %v", err)
}
if err := os.MkdirAll(path.Join(testVendorDir, "vendor/github.com/testlog"), 0755); err != nil {
t.Fatalf("MkdirAll failed: %v", err)
}
if err := ioutil.WriteFile(path.Join(testVendorDir, "vendor/github.com/testlog/testlog.go"), []byte(testLog), 0755); err != nil {
t.Fatalf("Failed to write testlog: %v", err)
}
cases := []struct {
withoutGeneratedCode bool
numExpectedErrs int
}{
// basic case has one error
{
withoutGeneratedCode: false,
numExpectedErrs: 1,
},
// ignoring generated code works
{
withoutGeneratedCode: true,
numExpectedErrs: 0,
},
}
for i, currCase := range cases {
checker := NewChecker()
checker.WithoutGeneratedCode = currCase.withoutGeneratedCode
loadPackages = func(cfg *packages.Config, paths ...string) ([]*packages.Package, error) {
cfg.Env = append(os.Environ(),
"GOPATH="+tmpGopath,
"GOFLAGS=-mod=vendor")
cfg.Dir = testVendorDir
pkgs, err := packages.Load(cfg, paths...)
return pkgs, err
}
err := checker.CheckPackages(path.Join("github.com/testvendor"))
if currCase.numExpectedErrs == 0 {
if err != nil {
t.Errorf("Case %d: expected no errors, but got: %v", i, err)
}
continue
}
uerr, ok := err.(*UncheckedErrors)
if !ok {
t.Errorf("Case %d: wrong error type returned: %v", i, err)
continue
}
if currCase.numExpectedErrs != len(uerr.Errors) {
t.Errorf("Case %d:\nExpected: %d errors\nActual: %d errors", i, currCase.numExpectedErrs, len(uerr.Errors))
}
}
}
func test(t *testing.T, f flags) {
var (
asserts bool = f&CheckAsserts != 0
blank bool = f&CheckBlank != 0
)
checker := NewChecker()
checker.Asserts = asserts
checker.Blank = blank
checker.AddExcludes(DefaultExcludes)
checker.AddExcludes([]string{
fmt.Sprintf("(%s.ErrorMakerInterface).MakeNilError", testPackage),
})
err := checker.CheckPackages(testPackage)
uerr, ok := err.(*UncheckedErrors)
if !ok {
t.Fatalf("wrong error type returned: %v", err)
}
numErrors := len(uncheckedMarkers)
if blank {
numErrors += len(blankMarkers)
}
if asserts {
numErrors += len(assertMarkers)
}
if len(uerr.Errors) != numErrors {
t.Errorf("got %d errors, want %d", len(uerr.Errors), numErrors)
unchecked_loop:
for k := range uncheckedMarkers {
for _, e := range uerr.Errors {
if newMarker(e) == k {
continue unchecked_loop
}
}
t.Errorf("Expected unchecked at %s", k)
}
if blank {
blank_loop:
for k := range blankMarkers {
for _, e := range uerr.Errors {
if newMarker(e) == k {
continue blank_loop
}
}
t.Errorf("Expected blank at %s", k)
}
}
if asserts {
assert_loop:
for k := range assertMarkers {
for _, e := range uerr.Errors {
if newMarker(e) == k {
continue assert_loop
}
}
t.Errorf("Expected assert at %s", k)
}
}
}
for i, err := range uerr.Errors {
m := marker{err.Pos.Filename, err.Pos.Line}
if !uncheckedMarkers[m] && !blankMarkers[m] && !assertMarkers[m] {
t.Errorf("%d: unexpected error: %v", i, err)
}
}
}