forked from wallix/awless
/
acceptance_mocks.go
298 lines (259 loc) · 7.45 KB
/
acceptance_mocks.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
package main
import (
"bytes"
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"html/template"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/wallix/awless/gen/aws"
)
var AWS_SDK_PATH = filepath.Join(ROOT_DIR, "vendor", "github.com", "aws", "aws-sdk-go")
func generateAcceptanceMocks() {
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, SPEC_DIR, func(os.FileInfo) bool { return true }, 0)
if err != nil {
panic(err)
}
finder := &findStructs{}
for _, pkg := range pkgs {
for _, f := range pkg.Files {
ast.Walk(finder, f)
}
}
usedApis := make(map[string]string)
for _, cmd := range finder.result {
if cmd.API == "" {
continue
}
usedApis[cmd.API] = aws.ApiToInterface(cmd.API)
}
apis := make(map[string]apiInfo)
for api, ifaceName := range usedApis {
var functions []functionInfo
apiPath := filepath.Join(AWS_SDK_PATH, "service", api, api+"iface")
pkgs, err := parser.ParseDir(fset, apiPath, func(os.FileInfo) bool { return true }, 0)
if err != nil {
panic(err)
}
conf := types.Config{Importer: importer.Default()}
//ifaceFinder := &findIfaces{}
for _, pkg := range pkgs {
files := make([]*ast.File, len(pkg.Files))
i := 0
for _, file := range pkg.Files {
files[i] = file
i++
}
tpkg, err := conf.Check(api, fset, files, nil)
if err != nil {
panic(err)
}
iface := tpkg.Scope().Lookup(ifaceName)
if iface == nil {
panic(fmt.Sprintf("cannot find interface %s", ifaceName))
}
if !types.IsInterface(iface.Type()) {
panic(fmt.Sprintf("%s (%s) not an interface", ifaceName, iface.Type().String()))
}
isPointer := func(s string) bool { return len(s) > 0 && s[0] == '*' }
iiface := iface.Type().Underlying().(*types.Interface).Complete()
for i := 0; i < iiface.NumMethods(); i++ {
meth := iiface.Method(i)
sig := meth.Type().(*types.Signature)
if strings.HasSuffix(meth.Name(), "Pages") || strings.HasSuffix(meth.Name(), "PagesWithContext") {
continue
}
var paramBuff bytes.Buffer
var paramNames []string
for j := 0; j < sig.Params().Len(); j++ {
p := sig.Params().At(j)
paramName := fmt.Sprintf("param%d", j)
paramBuff.WriteString(paramName)
paramBuff.WriteRune(' ')
t := p.Type().String()
if found := strings.LastIndexByte(t, '/'); found != -1 {
t = t[found+1:]
}
if isPointer(p.Type().String()) {
t = "*" + t
}
if sig.Variadic() && j == sig.Params().Len()-1 {
t = "..." + t
paramName = paramName + "..."
}
paramNames = append(paramNames, paramName)
paramBuff.WriteString(t)
if j < sig.Params().Len()-1 {
paramBuff.WriteString(", ")
}
}
var returnsBuff bytes.Buffer
if sig.Results().Len() > 1 {
returnsBuff.WriteByte('(')
}
for j := 0; j < sig.Results().Len(); j++ {
p := sig.Results().At(j)
t := p.Type().String()
if found := strings.LastIndexByte(t, '/'); found != -1 {
t = t[found+1:]
}
if isPointer(p.Type().String()) {
t = "*" + t
}
if sig.Variadic() && j == sig.Params().Len()-1 {
t = "..." + t
}
returnsBuff.WriteString(t)
if j < sig.Results().Len()-1 {
returnsBuff.WriteString(", ")
}
}
if sig.Results().Len() > 1 {
returnsBuff.WriteByte(')')
}
functions = append(functions, functionInfo{
Name: meth.Name(),
Sig: fmt.Sprintf("func (m *%sMock) %s(%s) %s", api, meth.Name(), paramBuff.String(), returnsBuff.String()),
AnonymousSig: fmt.Sprintf("func (%s) %s", paramBuff.String(), returnsBuff.String()),
ParamNames: paramNames,
})
}
}
apis[api] = apiInfo{Name: api, IfaceName: ifaceName, Methods: functions}
}
templ, err := template.New("mocks").Funcs(
template.FuncMap{"Join": strings.Join},
).Parse(atMocksTemplate)
if err != nil {
panic(err)
}
var buff bytes.Buffer
err = templ.Execute(&buff, apis)
if err != nil {
panic(err)
}
if err = ioutil.WriteFile(filepath.Join(AWSAT_DIR, "gen_mocks.go"), buff.Bytes(), 0666); err != nil {
panic(err)
}
}
func generateAcceptanceFactory() {
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, SPEC_DIR, func(os.FileInfo) bool { return true }, 0)
if err != nil {
panic(err)
}
finder := &findStructs{}
for _, pkg := range pkgs {
for _, f := range pkg.Files {
ast.Walk(finder, f)
}
}
templ, err := template.New("acceptanceFactory").Funcs(
template.FuncMap{
"ApiToInterface": aws.ApiToInterface,
},
).Parse(atMocksCmdBuilders)
if err != nil {
panic(err)
}
var buff bytes.Buffer
err = templ.Execute(&buff, finder.result)
if err != nil {
panic(err)
}
if err = ioutil.WriteFile(filepath.Join(AWSAT_DIR, "gen_factory.go"), buff.Bytes(), 0666); err != nil {
panic(err)
}
}
type apiInfo struct {
Name string
IfaceName string
Methods []functionInfo
}
type functionInfo struct {
Name string
Sig string
AnonymousSig string
ParamNames []string
}
const atMocksCmdBuilders = `/* Copyright 2017 WALLIX
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// DO NOT EDIT
// This file was automatically generated with go generate
package awsat
import (
"github.com/wallix/awless/aws/spec"
)
type AcceptanceFactory struct {
Mock interface{}
Logger *logger.Logger
Graph cloud.GraphAPI
}
func NewAcceptanceFactory(mock interface{}, g cloud.GraphAPI, l ...*logger.Logger) *AcceptanceFactory {
logger := logger.DiscardLogger
if len(l) > 0 {
logger = l[0]
}
return &AcceptanceFactory{Mock: mock, Graph:g, Logger: logger}
}
func (f *AcceptanceFactory) Build(key string) func() interface{} {
switch key {
{{- range $cmdName, $cmd := . }}
case "{{ $cmd.Action }}{{ $cmd.Entity }}":
return func() interface{} {
cmd := awsspec.New{{ $cmdName }}(nil, f.Graph, f.Logger)
cmd.SetApi(f.Mock.({{$cmd.API}}iface.{{ ApiToInterface $cmd.API }}))
return cmd
}
{{- end}}
}
return nil
}
`
const atMocksTemplate = `/* Copyright 2017 WALLIX
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// DO NOT EDIT
// This file was automatically generated with go generate
package awsat
{{ range $api, $apiInfo := . }}
type {{ $api }}Mock struct {
basicMock
{{ $api }}iface.{{ $apiInfo.IfaceName }}
{{- range $, $method := $apiInfo.Methods }}
{{ $method.Name }}Func {{ $method.AnonymousSig }}
{{- end }}
}
{{- range $, $method := $apiInfo.Methods }}
{{ $method.Sig }} {
m.addCall("{{$method.Name}}")
m.verifyInput("{{$method.Name}}", param0)
return m.{{$method.Name}}Func({{Join $method.ParamNames ","}})
}
{{ end }}
{{- end }}
`