/
td_array.go
436 lines (379 loc) · 12.1 KB
/
td_array.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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
// Copyright (c) 2018-2021, Maxime Soulé
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
package td
import (
"bytes"
"fmt"
"reflect"
"sort"
"github.com/maxatome/go-testdeep/internal/ctxerr"
"github.com/maxatome/go-testdeep/internal/types"
"github.com/maxatome/go-testdeep/internal/util"
)
type tdArray struct {
tdExpectedType
expectedEntries []reflect.Value
onlyIndexes []int // only used by SuperSliceOf, nil otherwise
}
var _ TestDeep = &tdArray{}
// ArrayEntries allows to pass array or slice entries to check in
// functions [Array], [Slice] and [SuperSliceOf]. It is a map whose
// each key is the item index and the corresponding value the expected
// item value (which can be a [TestDeep] operator as well as a zero
// value).
type ArrayEntries map[int]any
const (
arrayArray uint = iota
arraySlice
arraySuper
)
func newArray(kind uint, model any, expectedEntries ArrayEntries) *tdArray {
vmodel := reflect.ValueOf(model)
a := tdArray{
tdExpectedType: tdExpectedType{
base: newBase(4),
},
}
if kind == arraySuper {
a.onlyIndexes = make([]int, 0, len(expectedEntries))
}
kindIsOK := func(k reflect.Kind) bool {
switch kind {
case arrayArray:
return k == reflect.Array
case arraySlice:
return k == reflect.Slice
default: // arraySuper
return k == reflect.Slice || k == reflect.Array
}
}
switch vk := vmodel.Kind(); {
case vk == reflect.Ptr:
if !kindIsOK(vmodel.Type().Elem().Kind()) {
break
}
a.isPtr = true
if vmodel.IsNil() {
a.expectedType = vmodel.Type().Elem()
a.populateExpectedEntries(expectedEntries, reflect.Value{})
return &a
}
vmodel = vmodel.Elem()
fallthrough
case kindIsOK(vk):
a.expectedType = vmodel.Type()
a.populateExpectedEntries(expectedEntries, vmodel)
return &a
}
switch kind {
case arrayArray:
a.err = ctxerr.OpBadUsage("Array",
"(ARRAY|&ARRAY, EXPECTED_ENTRIES)", model, 1, true)
case arraySlice:
a.err = ctxerr.OpBadUsage("Slice",
"(SLICE|&SLICE, EXPECTED_ENTRIES)", model, 1, true)
default: // arraySuper
a.err = ctxerr.OpBadUsage("SuperSliceOf",
"(ARRAY|&ARRAY|SLICE|&SLICE, EXPECTED_ENTRIES)", model, 1, true)
}
return &a
}
// summary(Array): compares the contents of an array or a pointer on an array
// input(Array): array,ptr(ptr on array)
// Array operator compares the contents of an array or a pointer on an
// array against the values of model and the values of
// expectedEntries. Entries with zero values of model are ignored
// if the same entry is present in expectedEntries, otherwise they
// are taken into account. An entry cannot be present in both model
// and expectedEntries, except if it is a zero-value in model. At
// the end, all entries are checked. To check only some entries of an
// array, see [SuperSliceOf] operator.
//
// model must be the same type as compared data.
//
// expectedEntries can be nil, if no zero entries are expected and
// no [TestDeep] operators are involved.
//
// got := [3]int{12, 14, 17}
// td.Cmp(t, got, td.Array([3]int{0, 14}, td.ArrayEntries{0: 12, 2: 17})) // succeeds
// td.Cmp(t, &got,
// td.Array(&[3]int{0, 14}, td.ArrayEntries{0: td.Gt(10), 2: td.Gt(15)})) // succeeds
//
// TypeBehind method returns the [reflect.Type] of model.
//
// See also [Slice] and [SuperSliceOf].
func Array(model any, expectedEntries ArrayEntries) TestDeep {
return newArray(arrayArray, model, expectedEntries)
}
// summary(Slice): compares the contents of a slice or a pointer on a slice
// input(Slice): slice,ptr(ptr on slice)
// Slice operator compares the contents of a slice or a pointer on a
// slice against the values of model and the values of
// expectedEntries. Entries with zero values of model are ignored
// if the same entry is present in expectedEntries, otherwise they
// are taken into account. An entry cannot be present in both model
// and expectedEntries, except if it is a zero-value in model. At
// the end, all entries are checked. To check only some entries of a
// slice, see [SuperSliceOf] operator.
//
// model must be the same type as compared data.
//
// expectedEntries can be nil, if no zero entries are expected and
// no [TestDeep] operators are involved.
//
// got := []int{12, 14, 17}
// td.Cmp(t, got, td.Slice([]int{0, 14}, td.ArrayEntries{0: 12, 2: 17})) // succeeds
// td.Cmp(t, &got,
// td.Slice(&[]int{0, 14}, td.ArrayEntries{0: td.Gt(10), 2: td.Gt(15)})) // succeeds
//
// TypeBehind method returns the [reflect.Type] of model.
//
// See also [Array] and [SuperSliceOf].
func Slice(model any, expectedEntries ArrayEntries) TestDeep {
return newArray(arraySlice, model, expectedEntries)
}
// summary(SuperSliceOf): compares the contents of a slice, a pointer
// on a slice, an array or a pointer on an array but with potentially
// some extra entries
// input(SuperSliceOf): array,slice,ptr(ptr on array/slice)
// SuperSliceOf operator compares the contents of an array, a pointer
// on an array, a slice or a pointer on a slice against the non-zero
// values of model (if any) and the values of expectedEntries. So
// entries with zero value of model are always ignored. If a zero
// value check is needed, this zero value has to be set in
// expectedEntries. An entry cannot be present in both model and
// expectedEntries, except if it is a zero-value in model. At the
// end, only entries present in expectedEntries and non-zero ones
// present in model are checked. To check all entries of an array
// see [Array] operator. To check all entries of a slice see [Slice]
// operator.
//
// model must be the same type as compared data.
//
// expectedEntries can be nil, if no zero entries are expected and
// no [TestDeep] operators are involved.
//
// Works with slices:
//
// got := []int{12, 14, 17}
// td.Cmp(t, got, td.SuperSliceOf([]int{12}, nil)) // succeeds
// td.Cmp(t, got, td.SuperSliceOf([]int{12}, td.ArrayEntries{2: 17})) // succeeds
// td.Cmp(t, &got, td.SuperSliceOf(&[]int{0, 14}, td.ArrayEntries{2: td.Gt(16)})) // succeeds
//
// and arrays:
//
// got := [5]int{12, 14, 17, 26, 56}
// td.Cmp(t, got, td.SuperSliceOf([5]int{12}, nil)) // succeeds
// td.Cmp(t, got, td.SuperSliceOf([5]int{12}, td.ArrayEntries{2: 17})) // succeeds
// td.Cmp(t, &got, td.SuperSliceOf(&[5]int{0, 14}, td.ArrayEntries{2: td.Gt(16)})) // succeeds
//
// See also [Array] and [Slice].
func SuperSliceOf(model any, expectedEntries ArrayEntries) TestDeep {
return newArray(arraySuper, model, expectedEntries)
}
func (a *tdArray) populateExpectedEntries(expectedEntries ArrayEntries, expectedModel reflect.Value) {
// Compute highest expected index
maxExpectedIdx := -1
for index := range expectedEntries {
if index > maxExpectedIdx {
maxExpectedIdx = index
}
}
var numEntries int
array := a.expectedType.Kind() == reflect.Array
if array {
numEntries = a.expectedType.Len()
if numEntries <= maxExpectedIdx {
a.err = ctxerr.OpBad(
a.GetLocation().Func,
"array length is %d, so cannot have #%d expected index",
numEntries,
maxExpectedIdx)
return
}
} else {
numEntries = maxExpectedIdx + 1
// If slice is non-nil
if expectedModel.IsValid() {
if numEntries < expectedModel.Len() {
numEntries = expectedModel.Len()
}
}
}
a.expectedEntries = make([]reflect.Value, numEntries)
elemType := a.expectedType.Elem()
var vexpectedValue reflect.Value
for index, expectedValue := range expectedEntries {
if expectedValue == nil {
switch elemType.Kind() {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map,
reflect.Ptr, reflect.Slice:
vexpectedValue = reflect.Zero(elemType) // change to a typed nil
default:
a.err = ctxerr.OpBad(
a.GetLocation().Func,
"expected value of #%d cannot be nil as items type is %s",
index,
elemType)
return
}
} else {
vexpectedValue = reflect.ValueOf(expectedValue)
if _, ok := expectedValue.(TestDeep); !ok {
if !vexpectedValue.Type().AssignableTo(elemType) {
a.err = ctxerr.OpBad(
a.GetLocation().Func,
"type %s of #%d expected value differs from %s contents (%s)",
vexpectedValue.Type(),
index,
util.TernStr(array, "array", "slice"),
elemType)
return
}
}
}
a.expectedEntries[index] = vexpectedValue
// SuperSliceOf
if a.onlyIndexes != nil {
a.onlyIndexes = append(a.onlyIndexes, index)
}
}
vzero := reflect.Zero(elemType)
// Check initialized entries in model
if expectedModel.IsValid() {
zero := vzero.Interface()
for index := expectedModel.Len() - 1; index >= 0; index-- {
ventry := expectedModel.Index(index)
modelIsZero := reflect.DeepEqual(zero, ventry.Interface())
// Entry already expected
if _, ok := expectedEntries[index]; ok {
// If non-zero entry, consider it as an error (= 2 expected
// values for the same item)
if !modelIsZero {
a.err = ctxerr.OpBad(
a.GetLocation().Func,
"non zero #%d entry in model already exists in expectedEntries",
index)
return
}
continue
}
// Expect this entry except if not SuperSliceOf || not zero entry
if a.onlyIndexes == nil || !modelIsZero {
a.expectedEntries[index] = ventry
// SuperSliceOf
if a.onlyIndexes != nil {
a.onlyIndexes = append(a.onlyIndexes, index)
}
}
}
} else if a.expectedType.Kind() == reflect.Slice {
sort.Ints(a.onlyIndexes)
// nil slice
return
}
// For SuperSliceOf, we don't want to initialize missing entries
if a.onlyIndexes != nil {
sort.Ints(a.onlyIndexes)
return
}
var index int
// Array case, all is OK
if array {
// Non-nil array => a.expectedEntries already fully initialized
if expectedModel.IsValid() {
return
}
// nil array => a.expectedEntries must be initialized from index=0
// to numEntries - 1 below
} else {
// Non-nil slice => a.expectedEntries must be initialized from
// index=len(slice) to last entry index of expectedEntries
index = expectedModel.Len()
}
// Slice case, initialize missing expected items to zero
for ; index < numEntries; index++ {
if _, ok := expectedEntries[index]; !ok {
a.expectedEntries[index] = vzero
}
}
}
func (a *tdArray) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error {
if a.err != nil {
return ctx.CollectError(a.err)
}
err := a.checkPtr(ctx, &got, true)
if err != nil {
return ctx.CollectError(err)
}
err = a.checkType(ctx, got)
if err != nil {
return ctx.CollectError(err)
}
gotLen := got.Len()
check := func(index int, expectedValue reflect.Value) *ctxerr.Error {
curCtx := ctx.AddArrayIndex(index)
if index >= gotLen {
if curCtx.BooleanError {
return ctxerr.BooleanError
}
return curCtx.CollectError(&ctxerr.Error{
Message: "expected value out of range",
Got: types.RawString("<non-existent value>"),
Expected: expectedValue,
})
}
return deepValueEqual(curCtx, got.Index(index), expectedValue)
}
// SuperSliceOf, only check some indexes
if a.onlyIndexes != nil {
for _, index := range a.onlyIndexes {
err = check(index, a.expectedEntries[index])
if err != nil {
return err
}
}
return nil
}
// Array or Slice
for index, expectedValue := range a.expectedEntries {
err = check(index, expectedValue)
if err != nil {
return err
}
}
if gotLen > len(a.expectedEntries) {
if ctx.BooleanError {
return ctxerr.BooleanError
}
return ctx.AddArrayIndex(len(a.expectedEntries)).
CollectError(&ctxerr.Error{
Message: "got value out of range",
Got: got.Index(len(a.expectedEntries)),
Expected: types.RawString("<non-existent value>"),
})
}
return nil
}
func (a *tdArray) String() string {
if a.err != nil {
return a.stringError()
}
buf := bytes.NewBufferString(a.GetLocation().Func)
buf.WriteByte('(')
buf.WriteString(a.expectedTypeStr())
if len(a.expectedEntries) == 0 {
buf.WriteString("{})")
} else {
buf.WriteString("{\n")
for index, expectedValue := range a.expectedEntries {
fmt.Fprintf(buf, " %d: %s\n", //nolint: errcheck
index, util.ToString(expectedValue))
}
buf.WriteString("})")
}
return buf.String()
}