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
|
package main
import (
"flag"
"fmt"
"go/importer"
"go/token"
"go/types"
"os"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
"unicode"
"unicode/utf8"
)
const (
usageTemplate = "Usage: %s [-benchmarks] [-examples] [-tests] import-path\n"
)
func findObjectByName(pkg *types.Package, re *regexp.Regexp, name string) types.Object {
if pkg != nil && re != nil && len(name) > 0 {
if obj := pkg.Scope().Lookup(name); obj != nil {
if re.MatchString(obj.Type().String()) {
return obj
}
}
}
return nil
}
func isTestName(name, prefix string) bool {
ok := false
if strings.HasPrefix(name, prefix) {
if len(name) == len(prefix) {
ok = true
} else {
rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
ok = !unicode.IsLower(rune)
}
}
return ok
}
func main() {
testsPtr := flag.Bool("tests", false, "report tests")
benchmarksPtr := flag.Bool("benchmarks", false, "report benchmarks")
examplesPtr := flag.Bool("examples", false, "report examples")
flag.Usage = func() {
_, _ = fmt.Fprintf(flag.CommandLine.Output(), usageTemplate, filepath.Base(os.Args[0]))
flag.PrintDefaults()
}
flag.Parse()
// Check if the number of positional parameters matches
args := flag.Args()
argsCount := len(args)
if argsCount != 1 {
exitCode := 0
if argsCount > 1 {
fmt.Println("Error: invalid number of parameters...")
exitCode = 1
}
flag.Usage()
os.Exit(exitCode)
}
importPath := args[0]
var fset token.FileSet
imp := importer.ForCompiler(&fset, runtime.Compiler, nil)
pkg, err := imp.Import(importPath)
if err != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(1)
}
if !*testsPtr && !*benchmarksPtr && !*examplesPtr {
// Nothing to do, just exit normally
os.Exit(0)
}
// // First approach: just dump the package scope as a string
// // package "junk/snermolaev/libmath" scope 0xc0000df540 {
// // . func junk/snermolaev/libmath.Abs(a int) int
// // . func junk/snermolaev/libmath.AbsReport(s string)
// // . func junk/snermolaev/libmath.Sum(a int, b int) int
// // . func junk/snermolaev/libmath.TestAbs(t *testing.T)
// // . func junk/snermolaev/libmath.TestSum(t *testing.T)
// // . func junk/snermolaev/libmath.init()
// // }
// // and then collect all functions that match test function signature
// pkgPath := pkg.Path()
// scopeContent := strings.Split(pkg.Scope().String(), "\n")
// re := regexp.MustCompile("^\\.\\s*func\\s*" + pkgPath + "\\.(Test\\w*)\\(\\s*\\w*\\s*\\*\\s*testing\\.T\\s*\\)$")
// for _, name := range scopeContent {
// match := re.FindAllStringSubmatch(name, -1)
// if len(match) > 0 {
// fmt.Println(match[0][1])
// }
// }
// Second approach: look through all names defined in the pkg scope
// and collect those functions that match test function signature
// Unfortunately I failed to employ reflection mechinary for signature
// comparison for unknown reasons (this needs additional investigation
// I am going to use regexp as workaround for a while)
// testFunc := func (*testing.T) {}
// for ...
// ...
// if reflect.DeepEqual(obj.Type(), reflect.TypeOf(testFunc)) {
// // this condition doesn't work
// }
reBenchmark := regexp.MustCompile(`^func\(\w*\s*\*testing\.B\)$`)
reExample := regexp.MustCompile(`^func\(\s*\)$`)
reTest := regexp.MustCompile(`^func\(\w*\s*\*testing\.T\)$`)
reTestMain := regexp.MustCompile(`^func\(\w*\s*\*testing\.M\)$`)
var re *regexp.Regexp
names := pkg.Scope().Names()
var testFns []types.Object
for _, name := range names {
if name == "TestMain" && findObjectByName(pkg, reTestMain, name) != nil {
fmt.Println("#TestMain")
continue
}
switch {
case *benchmarksPtr && isTestName(name, "Benchmark"):
re = reBenchmark
case *examplesPtr && isTestName(name, "Example"):
re = reExample
case *testsPtr && isTestName(name, "Test"):
re = reTest
default:
continue
}
if obj := findObjectByName(pkg, re, name); obj != nil {
testFns = append(testFns, obj)
}
}
sort.Slice(testFns, func(i, j int) bool {
iPos := testFns[i].Pos()
jPos := testFns[j].Pos()
if !iPos.IsValid() || !jPos.IsValid() {
return iPos < jPos
}
iPosition := fset.PositionFor(iPos, true)
jPosition := fset.PositionFor(jPos, true)
return iPosition.Filename < jPosition.Filename ||
(iPosition.Filename == jPosition.Filename && iPosition.Line < jPosition.Line)
})
for _, testFn := range testFns {
fmt.Println(testFn.Name())
}
}
|