Debian Codegraph @

td/td_array.go

raw
1 // Copyright (c) 2018-2025, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package td
8
9 import (
10 "bytes"
11 "fmt"
12 "reflect"
13 "sort"
14
15 "github.com/maxatome/go-testdeep/internal/ctxerr"
16 "github.com/maxatome/go-testdeep/internal/types"
17 "github.com/maxatome/go-testdeep/internal/util"
18 )
19
20 type tdArray struct {
21 tdExpectedType
22 expectedEntries []reflect.Value
23 onlyIndexes []int // only used by SuperSliceOf, nil otherwise
24 }
25
26 var _ TestDeep = &tdArray{}
27
28 // ArrayEntries allows to pass array or slice entries to check in
29 // functions [Array], [Slice] and [SuperSliceOf]. It is a map whose
30 // each key is the item index and the corresponding value the expected
31 // item value (which can be a [TestDeep] operator as well as a zero
32 // value).
33 type ArrayEntries map[int]any
34
35 func mergeArrayEntries(aes ...ArrayEntries) ArrayEntries {
36 switch len(aes) {
37 case 0:
38 return nil
39 case 1:
40 return aes[0]
41 }
42
43 ret := make(ArrayEntries, len(aes[0]))
44 for _, me := range aes {
45 for k, v := range me {
46 ret[k] = v
47 }
48 }
49 return ret
50 }
51
52 const (
53 arrayArray uint = iota
54 arraySlice
55 arraySuper
56 )
57
58 func newArray(kind uint, model any, aes ...ArrayEntries) *tdArray {
59 vmodel := reflect.ValueOf(model)
60
61 a := tdArray{
62 tdExpectedType: tdExpectedType{
63 base: newBase(4),
64 },
65 }
66
67 expectedEntries := mergeArrayEntries(aes...)
68
69 if kind == arraySuper {
70 a.onlyIndexes = make([]int, 0, len(expectedEntries))
71 }
72
73 kindIsOK := func(k reflect.Kind) bool {
74 switch kind {
75 case arrayArray:
76 return k == reflect.Array
77 case arraySlice:
78 return k == reflect.Slice
79 default: // arraySuper
80 return k == reflect.Slice || k == reflect.Array
81 }
82 }
83
84 switch vk := vmodel.Kind(); {
85 case vk == reflect.Ptr:
86 if !kindIsOK(vmodel.Type().Elem().Kind()) {
87 break
88 }
89
90 a.isPtr = true
91
92 if vmodel.IsNil() {
93 a.expectedType = vmodel.Type().Elem()
94 a.populateExpectedEntries(expectedEntries, reflect.Value{})
95 return &a
96 }
97
98 vmodel = vmodel.Elem()
99 fallthrough
100
101 case kindIsOK(vk):
102 a.expectedType = vmodel.Type()
103 a.populateExpectedEntries(expectedEntries, vmodel)
104 return &a
105 }
106
107 switch kind {
108 case arrayArray:
109 a.err = ctxerr.OpBadUsage("Array",
110 "(ARRAY|&ARRAY, EXPECTED_ENTRIES)", model, 1, true)
111 case arraySlice:
112 a.err = ctxerr.OpBadUsage("Slice",
113 "(SLICE|&SLICE, EXPECTED_ENTRIES)", model, 1, true)
114 default: // arraySuper
115 a.err = ctxerr.OpBadUsage("SuperSliceOf",
116 "(ARRAY|&ARRAY|SLICE|&SLICE, EXPECTED_ENTRIES)", model, 1, true)
117 }
118 return &a
119 }
120
121 // summary(Array): compares the contents of an array or a pointer on an array
122 // input(Array): array,ptr(ptr on array)
123
124 // Array operator compares the contents of an array or a pointer on an
125 // array against the values of model and the values of
126 // expectedEntries. Entries with zero values of model are ignored
127 // if the same entry is present in expectedEntries, otherwise they
128 // are taken into account. An entry cannot be present in both model
129 // and expectedEntries, except if it is a zero-value in model. At
130 // the end, all entries are checked. To check only some entries of an
131 // array, see [SuperSliceOf] operator.
132 //
133 // model must be the same type as compared data.
134 //
135 // expectedEntries can be omitted, if no zero entries are expected and
136 // no [TestDeep] operators are involved. If expectedEntries contains
137 // more than one item, all items are merged before their use, from
138 // left to right.
139 //
140 // got := [3]int{12, 14, 17}
141 // td.Cmp(t, got, td.Array([3]int{0, 14}, td.ArrayEntries{0: 12, 2: 17})) // succeeds
142 // td.Cmp(t, &got,
143 // td.Array(&[3]int{0, 14}, td.ArrayEntries{0: td.Gt(10), 2: td.Gt(15)})) // succeeds
144 //
145 // TypeBehind method returns the [reflect.Type] of model.
146 //
147 // See also [List], [Slice] and [SuperSliceOf].
148 func Array(model any, expectedEntries ...ArrayEntries) TestDeep {
149 return newArray(arrayArray, model, expectedEntries...)
150 }
151
152 // summary(Slice): compares the contents of a slice or a pointer on a slice
153 // input(Slice): slice,ptr(ptr on slice)
154
155 // Slice operator compares the contents of a slice or a pointer on a
156 // slice against the values of model and the values of
157 // expectedEntries. Entries with zero values of model are ignored
158 // if the same entry is present in expectedEntries, otherwise they
159 // are taken into account. An entry cannot be present in both model
160 // and expectedEntries, except if it is a zero-value in model. At
161 // the end, all entries are checked. To check only some entries of a
162 // slice, see [SuperSliceOf] operator.
163 //
164 // model must be the same type as compared data.
165 //
166 // expectedEntries can be omitted, if no zero entries are expected and
167 // no [TestDeep] operators are involved. If expectedEntries contains
168 // more than one item, all items are merged before their use, from
169 // left to right.
170 //
171 // got := []int{12, 14, 17}
172 // td.Cmp(t, got, td.Slice([]int{0, 14}, td.ArrayEntries{0: 12, 2: 17})) // succeeds
173 // td.Cmp(t, &got,
174 // td.Slice(&[]int{0, 14}, td.ArrayEntries{0: td.Gt(10), 2: td.Gt(15)})) // succeeds
175 //
176 // TypeBehind method returns the [reflect.Type] of model.
177 //
178 // See also [Array], [List] and [SuperSliceOf].
179 func Slice(model any, expectedEntries ...ArrayEntries) TestDeep {
180 return newArray(arraySlice, model, expectedEntries...)
181 }
182
183 // summary(SuperSliceOf): compares the contents of a slice, a pointer
184 // on a slice, an array or a pointer on an array but with potentially
185 // some extra entries
186 // input(SuperSliceOf): array,slice,ptr(ptr on array/slice)
187
188 // SuperSliceOf operator compares the contents of an array, a pointer
189 // on an array, a slice or a pointer on a slice against the non-zero
190 // values of model (if any) and the values of expectedEntries. So
191 // entries with zero value of model are always ignored. If a zero
192 // value check is needed, this zero value has to be set in
193 // expectedEntries. An entry cannot be present in both model and
194 // expectedEntries, except if it is a zero-value in model. At the
195 // end, only entries present in expectedEntries and non-zero ones
196 // present in model are checked. To check all entries of an array
197 // see [Array] operator. To check all entries of a slice see [Slice]
198 // operator.
199 //
200 // model must be the same type as compared data.
201 //
202 // expectedEntries can be omitted, if no zero entries are expected and
203 // no [TestDeep] operators are involved. If expectedEntries contains
204 // more than one item, all items are merged before their use, from
205 // left to right.
206 //
207 // Works with slices:
208 //
209 // got := []int{12, 14, 17}
210 // td.Cmp(t, got, td.SuperSliceOf([]int{12})) // succeeds
211 // td.Cmp(t, got, td.SuperSliceOf([]int{12}, td.ArrayEntries{2: 17})) // succeeds
212 // td.Cmp(t, &got, td.SuperSliceOf(&[]int{0, 14}, td.ArrayEntries{2: td.Gt(16)})) // succeeds
213 //
214 // and arrays:
215 //
216 // got := [5]int{12, 14, 17, 26, 56}
217 // td.Cmp(t, got, td.SuperSliceOf([5]int{12})) // succeeds
218 // td.Cmp(t, got, td.SuperSliceOf([5]int{12}, td.ArrayEntries{2: 17})) // succeeds
219 // td.Cmp(t, &got, td.SuperSliceOf(&[5]int{0, 14}, td.ArrayEntries{2: td.Gt(16)})) // succeeds
220 //
221 // See also [Array] and [Slice].
222 func SuperSliceOf(model any, expectedEntries ...ArrayEntries) TestDeep {
223 return newArray(arraySuper, model, expectedEntries...)
224 }
225
226 func (a *tdArray) populateExpectedEntries(expectedEntries ArrayEntries, expectedModel reflect.Value) {
227 // Compute highest expected index
228 maxExpectedIdx := -1
229 for index := range expectedEntries {
230 if index > maxExpectedIdx {
231 maxExpectedIdx = index
232 }
233 }
234
235 var numEntries int
236 array := a.expectedType.Kind() == reflect.Array
237 if array {
238 numEntries = a.expectedType.Len()
239
240 if numEntries <= maxExpectedIdx {
241 a.err = ctxerr.OpBad(
242 a.GetLocation().Func,
243 "array length is %d, so cannot have #%d expected index",
244 numEntries,
245 maxExpectedIdx)
246 return
247 }
248 } else {
249 numEntries = maxExpectedIdx + 1
250
251 // If slice is non-nil
252 if expectedModel.IsValid() {
253 if numEntries < expectedModel.Len() {
254 numEntries = expectedModel.Len()
255 }
256 }
257 }
258
259 a.expectedEntries = make([]reflect.Value, numEntries)
260
261 elemType := a.expectedType.Elem()
262 var vexpectedValue reflect.Value
263 for index, expectedValue := range expectedEntries {
264 if expectedValue == nil {
265 switch elemType.Kind() {
266 case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map,
267 reflect.Ptr, reflect.Slice:
268 vexpectedValue = reflect.Zero(elemType) // change to a typed nil
269 default:
270 // Don't raise an error if item cannot be nil as a smuggle hook can
271 // change it at fly during the comparison
272 vexpectedValue = reflect.Value{}
273 }
274 } else {
275 vexpectedValue = reflect.ValueOf(expectedValue)
276 // Don't check vexpectedValue type against slice/array item one as a
277 // smuggle hook can change it at fly during the comparison
278 }
279
280 a.expectedEntries[index] = vexpectedValue
281
282 // SuperSliceOf
283 if a.onlyIndexes != nil {
284 a.onlyIndexes = append(a.onlyIndexes, index)
285 }
286 }
287
288 vzero := reflect.Zero(elemType)
289 // Check initialized entries in model
290 if expectedModel.IsValid() {
291 zero := vzero.Interface()
292 for index := expectedModel.Len() - 1; index >= 0; index-- {
293 ventry := expectedModel.Index(index)
294
295 modelIsZero := reflect.DeepEqual(zero, ventry.Interface())
296
297 // Entry already expected
298 if _, ok := expectedEntries[index]; ok {
299 // If non-zero entry, consider it as an error (= 2 expected
300 // values for the same item)
301 if !modelIsZero {
302 a.err = ctxerr.OpBad(
303 a.GetLocation().Func,
304 "non zero #%d entry in model already exists in expectedEntries",
305 index)
306 return
307 }
308 continue
309 }
310
311 // Expect this entry except if not SuperSliceOf || not zero entry
312 if a.onlyIndexes == nil || !modelIsZero {
313 a.expectedEntries[index] = ventry
314
315 // SuperSliceOf
316 if a.onlyIndexes != nil {
317 a.onlyIndexes = append(a.onlyIndexes, index)
318 }
319 }
320 }
321 } else if a.expectedType.Kind() == reflect.Slice {
322 sort.Ints(a.onlyIndexes)
323 // nil slice
324 return
325 }
326
327 // For SuperSliceOf, we don't want to initialize missing entries
328 if a.onlyIndexes != nil {
329 sort.Ints(a.onlyIndexes)
330 return
331 }
332
333 var index int
334
335 // Array case, all is OK
336 if array {
337 // Non-nil array => a.expectedEntries already fully initialized
338 if expectedModel.IsValid() {
339 return
340 }
341 // nil array => a.expectedEntries must be initialized from index=0
342 // to numEntries - 1 below
343 } else {
344 // Non-nil slice => a.expectedEntries must be initialized from
345 // index=len(slice) to last entry index of expectedEntries
346 index = expectedModel.Len()
347 }
348
349 // Slice case, initialize missing expected items to zero
350 for ; index < numEntries; index++ {
351 if _, ok := expectedEntries[index]; !ok {
352 a.expectedEntries[index] = vzero
353 }
354 }
355 }
356
357 func (a *tdArray) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error {
358 if a.err != nil {
359 return ctx.CollectError(a.err)
360 }
361
362 err := a.checkPtr(ctx, &got, true)
363 if err != nil {
364 return ctx.CollectError(err)
365 }
366
367 err = a.checkType(ctx, got)
368 if err != nil {
369 return ctx.CollectError(err)
370 }
371
372 gotLen := got.Len()
373
374 check := func(index int, expectedValue reflect.Value) *ctxerr.Error {
375 curCtx := ctx.AddArrayIndex(index)
376
377 if index >= gotLen {
378 if curCtx.BooleanError {
379 return ctxerr.BooleanError
380 }
381 return curCtx.CollectError(&ctxerr.Error{
382 Message: "expected value out of range",
383 Got: types.RawString("<non-existent value>"),
384 Expected: expectedValue,
385 })
386 }
387
388 return deepValueEqual(curCtx, got.Index(index), expectedValue)
389 }
390
391 // SuperSliceOf, only check some indexes
392 if a.onlyIndexes != nil {
393 for _, index := range a.onlyIndexes {
394 err = check(index, a.expectedEntries[index])
395 if err != nil {
396 return err
397 }
398 }
399 return nil
400 }
401
402 // Array or Slice
403 for index, expectedValue := range a.expectedEntries {
404 err = check(index, expectedValue)
405 if err != nil {
406 return err
407 }
408 }
409
410 if gotLen > len(a.expectedEntries) {
411 if ctx.BooleanError {
412 return ctxerr.BooleanError
413 }
414 return ctx.AddArrayIndex(len(a.expectedEntries)).
415 CollectError(&ctxerr.Error{
416 Message: "got value out of range",
417 Got: got.Index(len(a.expectedEntries)),
418 Expected: types.RawString("<non-existent value>"),
419 })
420 }
421
422 return nil
423 }
424
425 func (a *tdArray) String() string {
426 if a.err != nil {
427 return a.stringError()
428 }
429
430 buf := bytes.NewBufferString(a.GetLocation().Func)
431 buf.WriteByte('(')
432 buf.WriteString(a.expectedTypeStr())
433
434 if len(a.expectedEntries) == 0 {
435 buf.WriteString("{})")
436 } else {
437 buf.WriteString("{\n")
438
439 for index, expectedValue := range a.expectedEntries {
440 fmt.Fprintf(buf, " %d: %s\n", //nolint: errcheck
441 index, util.ToString(expectedValue))
442 }
443
444 buf.WriteString("})")
445 }
446 return buf.String()
447 }