-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathassist.go
305 lines (251 loc) · 8.36 KB
/
assist.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
package assistdog
import (
"fmt"
"reflect"
"strings"
"sync"
"time"
"github.com/cucumber/godog"
"github.com/rdumont/assistdog/defaults"
)
var defaultParsers = map[interface{}]ParseFunc{
"": defaults.ParseString,
0: defaults.ParseInt,
time.Time{}: defaults.ParseTime,
}
var defaultComparers = map[interface{}]CompareFunc{
"": defaults.CompareString,
0: defaults.CompareInt,
time.Time{}: defaults.CompareTime,
}
// ParseFunc parses a raw string value from a table into a given type.
// If it succeeds, it should return the parsed typed value. Otherwise, it should return an error
// describing why the value could not be parsed.
type ParseFunc func(raw string) (interface{}, error)
// CompareFunc compares a raw string value from a table to an actual typed value.
// If the values are considered a match, no error should be returned. Otherwise, an error that
// describes the differences should be returned.
type CompareFunc func(raw string, actual interface{}) error
// NewDefault creates a new Assist instance with all the default parsers and comparers.
func NewDefault() *Assist {
a := new(Assist)
for tp, p := range defaultParsers {
a.RegisterParser(tp, p)
}
for tp, c := range defaultComparers {
a.RegisterComparer(tp, c)
}
return a
}
// Assist provides utility methods to deal with Gherkin tables.
type Assist struct {
lock sync.RWMutex
parsers map[reflect.Type]ParseFunc
comparers map[reflect.Type]CompareFunc
}
// RegisterParser registers a new value parser for a type.
// If a previous parser already exists for the given type, it will be replaced.
func (a *Assist) RegisterParser(i interface{}, parser ParseFunc) {
a.lock.Lock()
defer a.lock.Unlock()
a.assertInit()
a.parsers[reflect.TypeOf(i)] = parser
}
// RegisterComparer registers a new value comparer for a type.
// If a previous comparer already exists for the given type, it will be replaced.
func (a *Assist) RegisterComparer(i interface{}, comparer CompareFunc) {
a.lock.Lock()
defer a.lock.Unlock()
a.assertInit()
a.comparers[reflect.TypeOf(i)] = comparer
}
// RemoveParser removes the value parser for a type.
func (a *Assist) RemoveParser(i interface{}) {
a.lock.Lock()
defer a.lock.Unlock()
a.assertInit()
delete(a.parsers, reflect.TypeOf(i))
}
// RemoveComparer removes the value comparer for a type.
func (a *Assist) RemoveComparer(i interface{}) {
a.lock.Lock()
defer a.lock.Unlock()
a.assertInit()
delete(a.comparers, reflect.TypeOf(i))
}
// ParseMap takes a Gherkin table and returns a map that represents it.
// The table must have exactly two columns, where the first represents
// the key and the second represents the value.
func (a *Assist) ParseMap(table *godog.Table) (map[string]string, error) {
if len(table.Rows) == 0 {
return nil, fmt.Errorf("expected table to have at least one row")
}
if len(table.Rows[0].Cells) != 2 {
return nil, fmt.Errorf("expected table to have exactly two columns")
}
result := map[string]string{}
for _, row := range table.Rows {
result[row.Cells[0].Value] = row.Cells[1].Value
}
return result, nil
}
// ParseSlice takes a Gherkin table and returns a slice of maps representing each row.
// The first row acts as a header and provides the keys.
func (a *Assist) ParseSlice(table *godog.Table) ([]map[string]string, error) {
if len(table.Rows) < 2 {
return nil, fmt.Errorf("expected table to have at least two rows")
}
if len(table.Rows[0].Cells) == 0 {
return nil, fmt.Errorf("expected table to have at least one column")
}
fieldCells := table.Rows[0].Cells
result := make([]map[string]string, len(table.Rows)-1)
for i := 1; i < len(table.Rows); i++ {
parsed := map[string]string{}
for j := 0; j < len(fieldCells); j++ {
parsed[fieldCells[j].Value] = table.Rows[i].Cells[j].Value
}
result[i-1] = parsed
}
return result, nil
}
// CreateInstance takes a type and a Gherkin table and returns an instance of
// that type filled with the table's parsed values.
// The table must have exactly two columns, where the first represents the field names
// and the second represents the values.
func (a *Assist) CreateInstance(tp interface{}, table *godog.Table) (interface{}, error) {
tableMap, err := a.ParseMap(table)
if err != nil {
return nil, err
}
instance, errs := a.createInstance(tp, tableMap)
if len(errs) != 0 {
return nil, fmt.Errorf("failed to parse table as %v:\n- %v", reflect.TypeOf(tp), strings.Join(errs, "\n- "))
}
return instance.Interface(), nil
}
// CreateSlice takes a type and a Gherkin table and returns a slice of that type
// filled with each row as an instance.
// The first row acts as a header and provides the field names for each column.
func (a *Assist) CreateSlice(tp interface{}, table *godog.Table) (interface{}, error) {
maps, err := a.ParseSlice(table)
if err != nil {
return nil, err
}
errs := []string{}
slice := reflect.MakeSlice(reflect.SliceOf(reflect.TypeOf(tp)), 0, len(maps))
for i, row := range maps {
instance, fieldErrors := a.createInstance(tp, row)
if len(fieldErrors) > 0 {
errs = append(errs, fmt.Sprintf("row %v:\n - %v", i, strings.Join(fieldErrors, "\n - ")))
continue
}
slice = reflect.Append(slice, instance)
}
if len(errs) > 0 {
return nil, fmt.Errorf("failed to parse table as slice of %v:\n%v", reflect.TypeOf(tp), strings.Join(errs, "\n"))
}
return slice.Interface(), nil
}
// CompareToInstance compares an actual value to the expected fields from a Gherkin table.
func (a *Assist) CompareToInstance(actual interface{}, table *godog.Table) error {
tableMap, err := a.ParseMap(table)
if err != nil {
return err
}
errs := a.compareToInstance(actual, tableMap)
if len(errs) != 0 {
return fmt.Errorf("comparison failed:\n- %v", strings.Join(errs, "\n- "))
}
return nil
}
// CompareToSlice compares an actual slice of values to the expected rows from a Gherkin table.
func (a *Assist) CompareToSlice(actual interface{}, table *godog.Table) error {
maps, err := a.ParseSlice(table)
if err != nil {
return err
}
actualValue := reflect.ValueOf(actual)
if actualValue.Kind() != reflect.Slice {
return fmt.Errorf("actual value is not a slice")
}
errs := []string{}
for i, row := range maps {
rowErrs := a.compareToInstance(actualValue.Index(i).Interface(), row)
if len(rowErrs) > 0 {
errs = append(errs, fmt.Sprintf("row %v:\n - %v", i, strings.Join(rowErrs, "\n - ")))
}
}
if len(errs) > 0 {
return fmt.Errorf("comparison failed:\n%v", strings.Join(errs, "\n"))
}
return nil
}
func (a *Assist) createInstance(tp interface{}, table map[string]string) (reflect.Value, []string) {
errs := []string{}
result := reflect.New(reflect.TypeOf(tp).Elem())
sv := result.Elem()
for fieldName, rawValue := range table {
fv := sv.FieldByName(fieldName)
if !fv.IsValid() {
errs = append(errs, fmt.Sprintf("%v: field not found", fieldName))
continue
}
if !fv.CanSet() {
errs = append(errs, fmt.Sprintf("%v: cannot set value", fieldName))
continue
}
parseField, ok := a.findParser(fv.Type())
if !ok {
errs = append(errs, fmt.Sprintf("%v: unrecognized type %v", fieldName, fv.Type()))
continue
}
parsed, err := parseField(rawValue)
if err != nil {
errs = append(errs, fmt.Sprintf("%v: %v", fieldName, err.Error()))
continue
}
fv.Set(reflect.ValueOf(parsed))
}
return result, errs
}
func (a *Assist) compareToInstance(actual interface{}, table map[string]string) []string {
errs := []string{}
sv := reflect.ValueOf(actual).Elem()
for fieldName, rawExpectedValue := range table {
fv := sv.FieldByName(fieldName)
if !fv.IsValid() {
errs = append(errs, fmt.Sprintf("%v: field not found", fieldName))
continue
}
compare, ok := a.findComparer(fv.Type())
if !ok {
errs = append(errs, fmt.Sprintf("%v: unrecognized type %v", fieldName, fv.Type()))
continue
}
if err := compare(rawExpectedValue, fv.Interface()); err != nil {
errs = append(errs, fmt.Sprintf("%v: %v", fieldName, err))
}
}
return errs
}
func (a *Assist) findParser(tp reflect.Type) (ParseFunc, bool) {
a.lock.RLock()
defer a.lock.RUnlock()
p, ok := a.parsers[tp]
return p, ok
}
func (a *Assist) findComparer(tp reflect.Type) (CompareFunc, bool) {
a.lock.RLock()
defer a.lock.RUnlock()
c, ok := a.comparers[tp]
return c, ok
}
func (a *Assist) assertInit() {
if a.parsers == nil {
a.parsers = map[reflect.Type]ParseFunc{}
}
if a.comparers == nil {
a.comparers = map[reflect.Type]CompareFunc{}
}
}