Debian Codegraph @

td/td_map.go

raw
1 // Copyright (c) 2018, 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 "fmt"
11 "reflect"
12 "strings"
13
14 "github.com/maxatome/go-testdeep/helpers/tdutil"
15 "github.com/maxatome/go-testdeep/internal/ctxerr"
16 "github.com/maxatome/go-testdeep/internal/dark"
17 "github.com/maxatome/go-testdeep/internal/util"
18 )
19
20 type mapKind uint8
21
22 const (
23 allMap mapKind = iota
24 subMap
25 superMap
26 )
27
28 type tdMap struct {
29 tdExpectedType
30 expectedEntries []mapEntryInfo
31 kind mapKind
32 }
33
34 var _ TestDeep = &tdMap{}
35
36 type mapEntryInfo struct {
37 key reflect.Value
38 expected reflect.Value
39 }
40
41 // MapEntries allows to pass map entries to check in functions [Map],
42 // [SubMapOf] and [SuperMapOf]. It is a map whose each key is the
43 // expected entry key and the corresponding value the expected entry
44 // value (which can be a [TestDeep] operator as well as a zero value.)
45 type MapEntries map[any]any
46
47 func mergeMapEntries(mes ...MapEntries) MapEntries {
48 switch len(mes) {
49 case 0:
50 return nil
51 case 1:
52 return mes[0]
53 }
54
55 ret := make(MapEntries, len(mes[0]))
56 for _, me := range mes {
57 for k, v := range me {
58 ret[k] = v
59 }
60 }
61 return ret
62 }
63
64 func newMap(model any, kind mapKind, mes ...MapEntries) *tdMap {
65 vmodel := reflect.ValueOf(model)
66
67 m := tdMap{
68 tdExpectedType: tdExpectedType{
69 base: newBase(4),
70 },
71 kind: kind,
72 }
73
74 switch vmodel.Kind() {
75 case reflect.Ptr:
76 if vmodel.Type().Elem().Kind() != reflect.Map {
77 break
78 }
79
80 m.isPtr = true
81
82 if vmodel.IsNil() {
83 m.expectedType = vmodel.Type().Elem()
84 m.populateExpectedEntries(mergeMapEntries(mes...), reflect.Value{})
85 return &m
86 }
87
88 vmodel = vmodel.Elem()
89 fallthrough
90
91 case reflect.Map:
92 m.expectedType = vmodel.Type()
93 m.populateExpectedEntries(mergeMapEntries(mes...), vmodel)
94 return &m
95 }
96
97 m.err = ctxerr.OpBadUsage(
98 m.GetLocation().Func, "(MAP|&MAP, EXPECTED_ENTRIES)",
99 model, 1, true)
100 return &m
101 }
102
103 func (m *tdMap) populateExpectedEntries(entries MapEntries, expectedModel reflect.Value) {
104 var keysInModel int
105 if expectedModel.IsValid() {
106 keysInModel = expectedModel.Len()
107 }
108
109 m.expectedEntries = make([]mapEntryInfo, 0, keysInModel+len(entries))
110 checkedEntries := make(map[any]bool, len(entries))
111
112 keyType := m.expectedType.Key()
113 valueType := m.expectedType.Elem()
114
115 var entryInfo mapEntryInfo
116
117 for key, expectedValue := range entries {
118 vkey := reflect.ValueOf(key)
119 if !vkey.Type().AssignableTo(keyType) {
120 m.err = ctxerr.OpBad(
121 m.GetLocation().Func,
122 "expected key %s type mismatch: %s != model key type (%s)",
123 util.ToString(key),
124 vkey.Type(),
125 keyType)
126 return
127 }
128
129 if expectedValue == nil {
130 switch valueType.Kind() {
131 case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map,
132 reflect.Ptr, reflect.Slice:
133 entryInfo.expected = reflect.Zero(valueType) // change to a typed nil
134 default:
135 entryInfo.expected = reflect.Value{}
136 // Don't raise an error if map value cannot be nil as a
137 // smuggle hook can change it at fly during the comparison
138 }
139 } else {
140 entryInfo.expected = reflect.ValueOf(expectedValue)
141 // Don't check vexpectedValue type against map value one as a
142 // smuggle hook can change it at fly during the comparison
143 }
144
145 entryInfo.key = vkey
146 m.expectedEntries = append(m.expectedEntries, entryInfo)
147 checkedEntries[dark.MustGetInterface(vkey)] = true
148 }
149
150 // Check entries in model
151 if keysInModel == 0 {
152 return
153 }
154
155 tdutil.MapEach(expectedModel, func(k, v reflect.Value) bool {
156 entryInfo.expected = v
157
158 if checkedEntries[dark.MustGetInterface(k)] {
159 m.err = ctxerr.OpBad(
160 m.GetLocation().Func,
161 "%s entry exists in both model & expectedEntries",
162 util.ToString(k))
163 return false
164 }
165
166 entryInfo.key = k
167 m.expectedEntries = append(m.expectedEntries, entryInfo)
168 return true
169 })
170 }
171
172 // summary(Map): compares the contents of a map
173 // input(Map): map,ptr(ptr on map)
174
175 // Map operator compares the contents of a map against the non-zero
176 // values of model (if any) and the values of expectedEntries.
177 //
178 // model must be the same type as compared data.
179 //
180 // expectedEntries can be omitted, if no [TestDeep] operators are
181 // involved. If expectedEntries contains more than one item, all items
182 // are merged before their use, from left to right.
183 //
184 // During a match, all expected entries must be found and all data
185 // entries must be expected to succeed.
186 //
187 // got := map[string]string{
188 // "foo": "test",
189 // "bar": "wizz",
190 // "zip": "buzz",
191 // }
192 // td.Cmp(t, got, td.Map(
193 // map[string]string{
194 // "foo": "test",
195 // "bar": "wizz",
196 // },
197 // td.MapEntries{
198 // "zip": td.HasSuffix("zz"),
199 // }),
200 // ) // succeeds
201 //
202 // TypeBehind method returns the [reflect.Type] of model.
203 //
204 // See also [SubMapOf] and [SuperMapOf].
205 func Map(model any, expectedEntries ...MapEntries) TestDeep {
206 return newMap(model, allMap, expectedEntries...)
207 }
208
209 // summary(SubMapOf): compares the contents of a map but with
210 // potentially some exclusions
211 // input(SubMapOf): map,ptr(ptr on map)
212
213 // SubMapOf operator compares the contents of a map against the non-zero
214 // values of model (if any) and the values of expectedEntries.
215 //
216 // model must be the same type as compared data.
217 //
218 // expectedEntries can be omitted, if no [TestDeep] operators are
219 // involved. If expectedEntries contains more than one item, all items
220 // are merged before their use, from left to right.
221 //
222 // During a match, each map entry should be matched by an expected
223 // entry to succeed. But some expected entries can be missing from the
224 // compared map.
225 //
226 // got := map[string]string{
227 // "foo": "test",
228 // "zip": "buzz",
229 // }
230 // td.Cmp(t, got, td.SubMapOf(
231 // map[string]string{
232 // "foo": "test",
233 // "bar": "wizz",
234 // },
235 // td.MapEntries{
236 // "zip": td.HasSuffix("zz"),
237 // }),
238 // ) // succeeds
239 //
240 // td.Cmp(t, got, td.SubMapOf(
241 // map[string]string{
242 // "bar": "wizz",
243 // },
244 // td.MapEntries{
245 // "zip": td.HasSuffix("zz"),
246 // }),
247 // ) // fails, extra {"foo": "test"} in got
248 //
249 // TypeBehind method returns the [reflect.Type] of model.
250 //
251 // See also [Map] and [SuperMapOf].
252 func SubMapOf(model any, expectedEntries ...MapEntries) TestDeep {
253 return newMap(model, subMap, expectedEntries...)
254 }
255
256 // summary(SuperMapOf): compares the contents of a map but with
257 // potentially some extra entries
258 // input(SuperMapOf): map,ptr(ptr on map)
259
260 // SuperMapOf operator compares the contents of a map against the non-zero
261 // values of model (if any) and the values of expectedEntries.
262 //
263 // model must be the same type as compared data.
264 //
265 // expectedEntries can be omitted, if no [TestDeep] operators are
266 // involved. If expectedEntries contains more than one item, all items
267 // are merged before their use, from left to right.
268 //
269 // During a match, each expected entry should match in the compared
270 // map. But some entries in the compared map may not be expected.
271 //
272 // got := map[string]string{
273 // "foo": "test",
274 // "bar": "wizz",
275 // "zip": "buzz",
276 // }
277 // td.Cmp(t, got, td.SuperMapOf(
278 // map[string]string{
279 // "foo": "test",
280 // },
281 // td.MapEntries{
282 // "zip": td.HasSuffix("zz"),
283 // }),
284 // ) // succeeds
285 //
286 // td.Cmp(t, got, td.SuperMapOf(
287 // map[string]string{
288 // "foo": "test",
289 // },
290 // td.MapEntries{
291 // "biz": td.HasSuffix("zz"),
292 // }),
293 // ) // fails, missing {"biz": …} in got
294 //
295 // TypeBehind method returns the [reflect.Type] of model.
296 //
297 // See also [SuperMapOf] and [SubMapOf].
298 func SuperMapOf(model any, expectedEntries ...MapEntries) TestDeep {
299 return newMap(model, superMap, expectedEntries...)
300 }
301
302 func (m *tdMap) Match(ctx ctxerr.Context, got reflect.Value) (err *ctxerr.Error) {
303 if m.err != nil {
304 return ctx.CollectError(m.err)
305 }
306
307 err = m.checkPtr(ctx, &got, true)
308 if err != nil {
309 return ctx.CollectError(err)
310 }
311
312 return m.match(ctx, got)
313 }
314
315 func (m *tdMap) match(ctx ctxerr.Context, got reflect.Value) (err *ctxerr.Error) {
316 err = m.checkType(ctx, got)
317 if err != nil {
318 return ctx.CollectError(err)
319 }
320
321 var notFoundKeys []reflect.Value
322 foundKeys := map[any]bool{}
323
324 for _, entryInfo := range m.expectedEntries {
325 gotValue := got.MapIndex(entryInfo.key)
326 if !gotValue.IsValid() {
327 notFoundKeys = append(notFoundKeys, entryInfo.key)
328 continue
329 }
330
331 err = deepValueEqual(ctx.AddMapKey(entryInfo.key),
332 gotValue, entryInfo.expected)
333 if err != nil {
334 return err
335 }
336 foundKeys[dark.MustGetInterface(entryInfo.key)] = true
337 }
338
339 const errorMessage = "comparing hash keys of %%"
340
341 // For SuperMapOf we don't care about extra keys
342 if m.kind == superMap {
343 if len(notFoundKeys) == 0 {
344 return nil
345 }
346
347 if ctx.BooleanError {
348 return ctxerr.BooleanError
349 }
350 return ctx.CollectError(&ctxerr.Error{
351 Message: errorMessage,
352 Summary: (tdSetResult{
353 Kind: keysSetResult,
354 Missing: notFoundKeys,
355 Sort: true,
356 }).Summary(),
357 })
358 }
359
360 // No extra key to search, all got keys have been found
361 if got.Len() == len(foundKeys) {
362 if m.kind == subMap {
363 return nil
364 }
365 // allMap
366
367 if len(notFoundKeys) == 0 {
368 return nil
369 }
370
371 if ctx.BooleanError {
372 return ctxerr.BooleanError
373 }
374 return ctx.CollectError(&ctxerr.Error{
375 Message: errorMessage,
376 Summary: (tdSetResult{
377 Kind: keysSetResult,
378 Missing: notFoundKeys,
379 Sort: true,
380 }).Summary(),
381 })
382 }
383
384 if ctx.BooleanError {
385 return ctxerr.BooleanError
386 }
387
388 // Retrieve extra keys
389 res := tdSetResult{
390 Kind: keysSetResult,
391 Missing: notFoundKeys,
392 Extra: make([]reflect.Value, 0, got.Len()-len(foundKeys)),
393 Sort: true,
394 }
395
396 for _, k := range tdutil.MapSortedKeys(got) {
397 if !foundKeys[dark.MustGetInterface(k)] {
398 res.Extra = append(res.Extra, k)
399 }
400 }
401
402 return ctx.CollectError(&ctxerr.Error{
403 Message: errorMessage,
404 Summary: res.Summary(),
405 })
406 }
407
408 func (m *tdMap) String() string {
409 if m.err != nil {
410 return m.stringError()
411 }
412
413 var buf strings.Builder
414
415 if m.kind != allMap {
416 buf.WriteString(m.GetLocation().Func)
417 buf.WriteByte('(')
418 }
419
420 buf.WriteString(m.expectedTypeStr())
421
422 if len(m.expectedEntries) == 0 {
423 buf.WriteString("{}")
424 } else {
425 buf.WriteString("{\n")
426
427 for _, entryInfo := range m.expectedEntries {
428 fmt.Fprintf(&buf, " %s: %s,\n", //nolint: errcheck
429 util.ToString(entryInfo.key),
430 util.ToString(entryInfo.expected))
431 }
432
433 buf.WriteByte('}')
434 }
435
436 if m.kind != allMap {
437 buf.WriteByte(')')
438 }
439
440 return buf.String()
441 }