/
mockgen.go
180 lines (157 loc) · 5.58 KB
/
mockgen.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
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package codegen
import (
"bytes"
"go/token"
"os/exec"
"path"
"sort"
"strconv"
"strings"
"github.com/golang/mock/mockgen/model"
"github.com/pkg/errors"
)
const (
mockgenPkg = "github.com/golang/mock/mockgen"
)
// MockgenBin is a struct abstracts the mockgen binary built from mockgen package in vendor
type MockgenBin struct {
pkgHelper *PackageHelper
tmpl *Template
}
// NewMockgenBin builds the mockgen binary from vendor directory
func NewMockgenBin(h *PackageHelper, t *Template) (*MockgenBin, error) {
return &MockgenBin{
pkgHelper: h,
tmpl: t,
}, nil
}
// GenMock generates mocks for given module instance, pkg is the package name of the generated mocks,
// and intf is the interface name to generate mock for
func (m MockgenBin) GenMock(importPath, pkg, intf string) ([]byte, error) {
cmd := exec.Command("mockgen", "-package", pkg, importPath, intf)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return nil, errors.Wrapf(
err,
"error running command %q: %s",
strings.Join(cmd.Args, " "),
stderr.String(),
)
}
return stdout.Bytes(), nil
}
// byMethodName implements sort.Interface for []*modelMethod based on the Name field
type byMethodName []*model.Method
func (b byMethodName) Len() int { return len(b) }
func (b byMethodName) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b byMethodName) Less(i, j int) bool { return b[i].Name < b[j].Name }
// AugmentMockWithFixture generates mocks with fixture for the interface in the given package
func (m MockgenBin) AugmentMockWithFixture(pkg *model.Package, f *Fixture, intf string) ([]byte, []byte, error) {
methodsMap := make(map[string]*model.Method, len(pkg.Interfaces[0].Methods))
validationMap := make(map[string]interface{}, len(pkg.Interfaces[0].Methods))
for _, m := range pkg.Interfaces[0].Methods {
methodsMap[m.Name] = m
validationMap[m.Name] = struct{}{}
}
if err := f.Validate(validationMap); err != nil {
return nil, nil, errors.Wrap(err, "invalid fixture config")
}
exposedMethods := make([]*model.Method, 0, len(f.Scenarios))
for name := range f.Scenarios {
exposedMethods = append(exposedMethods, methodsMap[name])
}
// sort methods in given fixture config for predictable fixture type generation
sort.Sort(byMethodName(exposedMethods))
pkgPathToAlias := uniqueAlias(pkg.Imports())
methods := make([]*reflectMethod, 0, len(exposedMethods))
for _, m := range exposedMethods {
numIn := len(m.In)
in := make(map[string]string, numIn)
inString := make([]string, 0, numIn)
for i, param := range m.In {
arg := "arg" + strconv.Itoa(i)
in[arg] = param.Type.String(pkgPathToAlias, "")
inString = append(inString, arg)
}
numOut := len(m.Out)
out := make(map[string]string, numOut)
outString := make([]string, 0, numOut)
for i, param := range m.Out {
ret := "ret" + strconv.Itoa(i)
out[ret] = param.Type.String(pkgPathToAlias, "")
outString = append(outString, ret)
}
method := &reflectMethod{
Name: m.Name,
In: in,
Out: out,
InString: strings.Join(inString, " ,"),
OutString: strings.Join(outString, " ,"),
}
if m.Variadic != nil {
method.Variadic = "arg" + strconv.Itoa(len(m.In))
method.VariadicType = m.Variadic.Type.String(pkgPathToAlias, "")
}
methods = append(methods, method)
}
data := map[string]interface{}{
"Imports": pkgPathToAlias,
"Methods": methods,
"Fixture": f,
"ClientInterface": intf,
}
types, err := m.tmpl.ExecTemplate("fixture_types.tmpl", data, m.pkgHelper)
if err != nil {
return nil, nil, err
}
mock, err := m.tmpl.ExecTemplate("augmented_mock.tmpl", data, m.pkgHelper)
if err != nil {
return nil, nil, err
}
return types, mock, nil
}
type reflectMethod struct {
Name string
In, Out map[string]string
Variadic string
VariadicType string
InString, OutString string
}
// uniqueAlias returns a map of import path to alias where the aliases are unique
func uniqueAlias(importPaths map[string]bool) map[string]string {
pkgPathToAlias := make(map[string]string, len(importPaths))
usedAliases := make(map[string]bool, len(importPaths))
for pkgPath := range importPaths {
base := CamelCase(path.Base(pkgPath))
pkgAlias := base
i := 0
for usedAliases[pkgAlias] || token.Lookup(pkgAlias).IsKeyword() {
pkgAlias = base + strconv.Itoa(i)
i++
}
pkgPathToAlias[pkgPath] = pkgAlias
usedAliases[pkgAlias] = true
}
return pkgPathToAlias
}