This repository has been archived by the owner on Dec 31, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
go.go
300 lines (234 loc) · 5.92 KB
/
go.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
package main
import (
"bytes"
"fmt"
"go/ast"
"go/printer"
"go/token"
"path/filepath"
"regexp"
"strings"
"text/template"
"golang.org/x/tools/imports"
)
var (
defaultExpectTestFuncTmpl = "Test{{ title .Name }}"
defaultExpectTestFuncMethodTmpl = "Test{{ title .RecvName }}_{{ title .Name }}"
)
// defaultIgnoreFuncs is default function name to be ignored in Parse
var defaultIgnoreFuncs = []string{"init"}
var funcMap = template.FuncMap{
"title": strings.Title,
}
// Mode is diff mode to change function diff behavior
type Mode int
const (
Strict Mode = iota
)
type diffOpts struct {
Mode Mode
IgnoreFuncs []string
// IncludeUnexported include unexported function
// for test generating target. By default it's false.
IncludeUnexported bool
ExpectTestFuncTmpl string
ExpectTestFuncMethodTmpl string
}
// GoFile is .go source file
type GoFile struct {
PackageName string
FileName string
SrcBytes []byte
Funcs []string
Methods []*Method
FSet *token.FileSet
AstFile *ast.File
}
type Method struct {
RecvName string
Name string
}
func NewGoFile(filename, pkgName string) (*GoFile, error) {
code := fmt.Sprintf("package %s", pkgName)
rd := bytes.NewReader([]byte(code))
goFile, err := parse(filename, rd)
if err != nil {
return nil, err
}
// Src should be emtpy (it's used for diff)
goFile.SrcBytes = []byte{}
return goFile, nil
}
func (o *diffOpts) init() {
if o.ExpectTestFuncTmpl == "" {
o.ExpectTestFuncTmpl = defaultExpectTestFuncTmpl
}
if o.ExpectTestFuncMethodTmpl == "" {
o.ExpectTestFuncMethodTmpl = defaultExpectTestFuncMethodTmpl
}
if len(o.IgnoreFuncs) == 0 {
o.IgnoreFuncs = defaultIgnoreFuncs
}
}
func (gf *GoFile) Generate() ([]byte, error) {
var buf bytes.Buffer
if err := printer.Fprint(&buf, gf.FSet, gf.AstFile); err != nil {
return nil, err
}
return imports.Process(gf.FileName, buf.Bytes(), nil)
}
func (gf *GoFile) addFuncTestFuncs(funcs []string, funcTmpl string) error {
for _, fun := range funcs {
tmpl, err := template.New("testFunc").Funcs(funcMap).Parse(funcTmpl)
if err != nil {
return err
}
tmplData := struct {
Name string
}{
Name: fun,
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, tmplData); err != nil {
return err
}
testFunDecl := NewTestFuncDecl(buf.String())
gf.AstFile.Decls = append(gf.AstFile.Decls, testFunDecl)
}
return nil
}
func (gf *GoFile) addMethodTestFuncs(methods []*Method, funcTmpl string) error {
for _, method := range methods {
tmpl, err := template.New("testFunc").Funcs(funcMap).Parse(funcTmpl)
if err != nil {
return err
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, method); err != nil {
return err
}
testFunDecl := NewTestFuncDecl(buf.String())
gf.AstFile.Decls = append(gf.AstFile.Decls, testFunDecl)
}
return nil
}
func (goFile *GoFile) diffFuncs(goTestFile *GoFile, opts *diffOpts) ([]string, error) {
opts.init()
var diff []string
for _, fun := range goFile.Funcs {
if contains(opts.IgnoreFuncs, fun) {
continue
}
if !opts.IncludeUnexported && isUnExported(fun) {
continue
}
// exist indicate expected test function is exist on goTestFile
// function list.
exist := false
tmpl, err := template.New("testFunc").Funcs(funcMap).Parse(opts.ExpectTestFuncTmpl)
if err != nil {
return diff, err
}
tmplData := struct {
Name string
}{
Name: fun,
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, tmplData); err != nil {
return diff, err
}
Debugf("Expect TestFunc Name: %s", buf.String())
expectTestFun := buf.String()
for _, testFun := range goTestFile.Funcs {
switch mode := opts.Mode; mode {
case Strict:
if expectTestFun == testFun {
exist = true
}
default:
// Should not reach here...
return diff, fmt.Errorf("unknown diff mode is provided: %d", mode)
}
}
if !exist {
diff = append(diff, fun)
}
}
return diff, nil
}
func (goFile *GoFile) diffMethods(goTestFile *GoFile, opts *diffOpts) ([]*Method, error) {
opts.init()
var diff []*Method
for _, method := range goFile.Methods {
if !opts.IncludeUnexported && isUnExported(method.Name) {
continue
}
// exist indicate expected test function is exist on goTestFile
// function list.
exist := false
tmpl, err := template.New("testFunc").Funcs(funcMap).Parse(opts.ExpectTestFuncMethodTmpl)
if err != nil {
return diff, err
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, method); err != nil {
return diff, err
}
Debugf("Expect TestFunc Name: %s", buf.String())
expectTestFun := buf.String()
for _, testFun := range goTestFile.Funcs {
switch mode := opts.Mode; mode {
case Strict:
if expectTestFun == testFun {
exist = true
}
default:
// Should not reach here...
return diff, fmt.Errorf("unknown diff mode is provided: %d", mode)
}
}
if !exist {
diff = append(diff, method)
}
}
return diff, nil
}
var reLower = regexp.MustCompile("^[a-z]+")
// isUnexported checks the given function is unxported (
// Check name start with lower case).
func isUnExported(name string) bool {
return reLower.Match([]byte(name))
}
func contains(strs []string, s string) bool {
for _, str := range strs {
if s == str {
return true
}
}
return false
}
// TestFilePath returns go test file of given source file.
func TestFilePath(path string) (string, error) {
path, err := filepath.Abs(path)
if err != nil {
return "", nil
}
if !strings.HasSuffix(path, ".go") {
return "", fmt.Errorf("%s is not go file", path)
}
if strings.HasSuffix(path, "_test.go") {
return "", fmt.Errorf("%s is go test file", path)
}
return strings.Replace(path, ".go", "_test.go", -1), nil
}
func SrcFilePath(path string) (string, error) {
path, err := filepath.Abs(path)
if err != nil {
return "", nil
}
if !strings.HasSuffix(path, "_test.go") {
return "", fmt.Errorf("%s is not go test file", path)
}
return strings.Replace(path, "_test.go", ".go", -1), nil
}