-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimplemock.go
372 lines (316 loc) · 8.55 KB
/
simplemock.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
package main
import (
"errors"
"flag"
"fmt"
"go/ast"
"go/types"
"os"
"path"
"runtime/debug"
"strings"
"text/template"
"golang.org/x/tools/go/packages"
)
const (
usageLine = `
Usage: simplemock [-help] [-version] -iface interface -out outfile
Options:
`
longHelp = `
simplemock generates mock implementations for interfaces and is designed to be
used with //go:generate directives to streamline usage and cohesiveness. Mocks
can be generated for any interface defined within the scope of the source file,
including interfaces that have been imported.
The required option -iface specifies the identifier of the interface for which
a mock is to be generated. This should match the interface name as it would
appear in the source file if it were to be used directly. For package-scoped
interfaces, this would simply be the interface name, e.g. 'MyInterface'. For
interfaces that have been imported, this would be its qualified identifier,
e.g. 'io.Reader'.
The required option -out specifies a relative file path where the generated
mock will be written. This path is relative to the source file. The special
value "os.Stdout" indicates that the generated mock should be printed to stdout
instead of written to disk.
Generated mocks will be defined in the test package corresponding to the
package of the source file. In the case the source file is within the main
package, the mock will also be defined in the main package.
Mock structs export members corresponding to each method of the interface,
named with a "Func" suffix. When the mocked method is invoked, the call is
forwarded to the corresponding member. If the member is not implemented, and
thus nil, the mocked method will panic.
`
)
type templData struct {
PackageName string
Imports []*packages.Package
InterfaceName string
MockName string
Methods []*types.Func
}
var (
templ = template.Must(template.New("MockSource").Funcs(template.FuncMap{
"typeString": typeString,
"signature": signature,
"args": defaultedArgs,
}).Parse(
`// Code generated by simplemock. DO NOT EDIT.
package {{ .PackageName }}
{{- with .Imports }}
import (
{{- range . }}
"{{ .PkgPath }}"
{{- end }}
)
{{- end }}
var _ {{ .InterfaceName }} = &{{ .MockName }}{}
{{- $mockName := .MockName }}
{{ with .Methods }}
type {{ $mockName }} struct {
{{- range . }}
{{ .Name }}Func {{ typeString .Type }}
{{- end }}
}
{{- else }}
type {{ $mockName }} struct {}
{{- end }}
{{- range .Methods }}
func (m *{{ $mockName }}) {{ .Name }}{{ signature .Signature }} {
if m.{{ .Name }}Func != nil {
return m.{{ .Name }}Func({{ args .Signature }})
}
panic("{{ .Name }} called with nil {{ .Name }}Func!")
}
{{- end }}
`,
))
)
func usage() {
f := flag.CommandLine.Output()
fmt.Fprint(f, usageLine[1:]) // trim newline
flag.PrintDefaults()
}
func helpExit(string) error {
flag.CommandLine.SetOutput(os.Stdout)
usage()
fmt.Fprint(os.Stdout, longHelp)
os.Exit(0)
return nil
}
func versionExit(string) error {
if info, ok := debug.ReadBuildInfo(); ok {
fmt.Printf("version: %s\n", info.Main.Version)
os.Exit(0)
}
fmt.Fprintln(os.Stderr, "Failed reading build info?")
os.Exit(1)
return nil
}
func main() {
flag.Usage = usage
var typeName, fname string
flag.StringVar(&typeName, "iface", "", "interface to generate a mock for")
flag.StringVar(&fname, "out", "", "relative output file")
flag.BoolFunc("version", "print version and exit", versionExit)
flag.BoolFunc("help", "print detailed help and exit", helpExit)
flag.Parse()
if typeName == "" {
fmt.Fprintln(os.Stderr, "option '-iface' is required")
usage()
os.Exit(1)
}
if fname == "" {
fmt.Fprintln(os.Stderr, "option '-out' is required")
usage()
os.Exit(1)
}
inputFile := os.Getenv("GOFILE")
if inputFile == "" {
fmt.Fprintln(os.Stderr, "Expected GOFILE environment variable to be set.")
fmt.Fprintln(os.Stderr, "You should be using a //go:generate directive.")
os.Exit(1)
}
cfg := packages.Config{
Mode: packages.NeedName |
packages.NeedFiles |
packages.NeedImports |
packages.NeedDeps |
packages.NeedTypes |
packages.NeedSyntax |
packages.NeedTypesInfo,
Tests: true,
}
pkgs, err := packages.Load(&cfg, "file="+inputFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to load input package and its dependencies: %v\n", err)
os.Exit(1)
}
obj := pkgs[0].Types.Scope().Lookup(typeName)
if obj == nil {
pkgName, typeName, found := strings.Cut(typeName, ".")
if !found {
pkgName, typeName = typeName, pkgName
}
for _, pkg := range pkgs[0].Imports {
if pkg.Name != pkgName {
continue
}
obj = pkg.Types.Scope().Lookup(typeName)
if obj != nil {
pkgs = append(pkgs, pkg)
break
}
}
if obj == nil {
fmt.Fprintf(os.Stderr, "Could not find type '%s'\n", typeName)
os.Exit(1)
}
}
if _, ok := obj.(*types.TypeName); !ok {
fmt.Fprintf(os.Stderr, "Type %v is not a named type\n", obj)
os.Exit(1)
}
if !types.IsInterface(obj.Type()) {
fmt.Fprintf(os.Stderr, "Type %v is not an interface\n", obj)
os.Exit(1)
}
if !obj.Exported() {
fmt.Fprintf(os.Stderr, "Interface %v is not exported\n", obj)
os.Exit(1)
}
imports, err := importsUsedBy(obj, pkgs)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed getting %v imports: %v\n", obj, err)
os.Exit(1)
}
iface := obj.Type().Underlying().(*types.Interface)
methods := make([]*types.Func, iface.NumMethods())
for i := range methods {
methods[i] = iface.Method(i)
}
pkgName := pkgs[0].Name
if pkgName != "main" {
pkgName = strings.TrimSuffix(pkgs[0].Name, "_test") + "_test"
}
file := os.Stdout
if fname != "os.Stdout" {
file, err = os.Create(path.Clean(path.Join(path.Dir(inputFile), fname)))
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create output file '%s': %v\n", fname, err)
os.Exit(1)
}
}
err = templ.Execute(file, templData{
PackageName: pkgName,
Imports: imports,
InterfaceName: types.TypeString(obj.Type(), relativeTo),
MockName: obj.Name() + "Mock",
Methods: methods,
})
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to generate mock from template: %v\n", err)
os.Exit(1)
}
}
func importsUsedBy(obj types.Object, pkgs []*packages.Package) ([]*packages.Package, error) {
var pkg *packages.Package = nil
for _, p := range pkgs {
if p.Types == obj.Pkg() {
pkg = p
}
}
if pkg == nil {
return nil, errors.New("owning package not found")
}
var id *ast.Ident = nil
for ident, object := range pkg.TypesInfo.Defs {
if object == obj {
id = ident
break
}
}
if id == nil {
return nil, errors.New("ast mapping not found")
}
typeSpec, ok := id.Obj.Decl.(*ast.TypeSpec)
if !ok {
return nil, errors.New("ast decl is not a type")
}
v := interfaceVisitor{info: pkg.TypesInfo, pkgs: make(map[*types.Package]struct{})}
ast.Walk(&v, typeSpec)
imports := make([]*packages.Package, 0, len(v.pkgs)+1)
if pkg.Name != "main" {
imports = append(imports, pkg)
}
for tPkg := range v.pkgs {
for _, pPkg := range pkg.Imports {
if tPkg == pPkg.Types {
imports = append(imports, pPkg)
}
}
}
return imports, nil
}
type interfaceVisitor struct {
info *types.Info
pkgs map[*types.Package]struct{}
}
func (v *interfaceVisitor) Visit(node ast.Node) ast.Visitor {
if id, ok := node.(*ast.Ident); ok {
obj := v.info.Uses[id]
if obj == nil {
obj = v.info.Defs[id]
}
if obj != nil && obj.Pkg() != nil {
v.pkgs[obj.Pkg()] = struct{}{}
}
}
return v
}
func typeString(typ types.Type) string {
return types.TypeString(typ, (*types.Package).Name)
}
func signature(sig *types.Signature) string {
params := sig.Params()
args := make([]string, params.Len())
for i := range args {
param := params.At(i)
if name := params.At(i).Name(); name == "" {
args[i] = fmt.Sprintf("arg%d", i)
} else {
args[i] = name
}
if i == params.Len() - 1 && sig.Variadic() {
args[i] += " ..." + strings.TrimPrefix(typeString(param.Type()), "[]")
} else {
args[i] += " " + typeString(param.Type())
}
}
argsStr := strings.Join(args, ", ")
if sig.Results().Len() != 0 {
return fmt.Sprintf("(%s) %s", argsStr, typeString(sig.Results()))
}
return fmt.Sprintf("(%s)", argsStr)
}
func defaultedArgs(sig *types.Signature) string {
params := sig.Params()
args := make([]string, params.Len())
for i := range args {
if name := params.At(i).Name(); name == "" {
args[i] = fmt.Sprintf("arg%d", i)
} else {
args[i] = name
}
}
ret := strings.Join(args, ", ")
if sig.Variadic() {
return ret + "..."
}
return ret
}
func relativeTo(pkg *types.Package) string {
if pkg.Name() == "main" {
return types.RelativeTo(pkg)(pkg)
}
return (*types.Package).Name(pkg)
}