-
Notifications
You must be signed in to change notification settings - Fork 0
/
untested.go
107 lines (90 loc) · 2.22 KB
/
untested.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
package untested
import (
"go/ast"
"strings"
"unicode"
)
const (
NoTestDirective = "//notest"
TestPkgSuffix = "_test"
)
type Pkg struct {
Name string
Funcs []Func
Tests []Func
}
type Func struct {
Name string
VerboseName string
}
func IsExported(fn Func) bool {
return unicode.IsUpper([]rune(fn.Name)[0])
}
func Analyze(pkgs map[string]Pkg) (tested []Func, untested []Func) {
for pkgName, pkg := range pkgs {
if strings.HasSuffix(pkgName, TestPkgSuffix) {
continue
}
testPkg, testPkgExists := pkgs[pkgName+TestPkgSuffix]
for _, fn := range pkg.Funcs {
// test pkg can have tests only for exported funcs
if testPkgExists && IsExported(fn) && pkgHasTestsFor(testPkg, fn) {
tested = append(tested, fn)
} else if pkgHasTestsFor(pkg, fn) {
tested = append(tested, fn)
} else {
untested = append(untested, fn)
}
}
}
return tested, untested
}
func pkgHasTestsFor(pkg Pkg, fn Func) bool {
testPrefix := "Test" + fn.Name
if !IsExported(fn) {
// look for both TestprivateFunc and TestPrivateFunc
upperPrefix := "Test" + strings.ToUpper(fn.Name[:1]) + fn.Name[1:]
return hasFuncsWithPrefix(pkg.Tests, testPrefix, upperPrefix)
} else {
return hasFuncsWithPrefix(pkg.Tests, testPrefix)
}
}
func hasFuncsWithPrefix(funcs []Func, prefixes ...string) bool {
for _, fn := range funcs {
for _, prefix := range prefixes {
if strings.HasPrefix(fn.Name, prefix) {
return true
}
}
}
return false
}
// check if it's a generated file
func IsGeneratedFile(file *ast.File) bool {
const lookupStr1 = "code generated by" // keep this string lower-cased
const lookupStr2 = "do not edit" // and this one either
for _, commentsGroup := range file.Comments {
for _, comment := range commentsGroup.List {
if len(comment.Text) < len(lookupStr1) {
continue
}
lowerComment := strings.ToLower(comment.Text)
if strings.Contains(lowerComment, lookupStr1) &&
strings.Contains(lowerComment, lookupStr2) {
return true
}
}
}
return false
}
func HasNoTestComment(decl *ast.FuncDecl) bool {
if decl.Doc == nil {
return false
}
for _, comment := range decl.Doc.List {
if strings.Contains(comment.Text, NoTestDirective) {
return true
}
}
return false
}