Debian Codegraph @

td/td_any.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 "reflect"
11
12 "github.com/maxatome/go-testdeep/internal/ctxerr"
13 )
14
15 type tdAny struct {
16 tdListBase
17 }
18
19 var _ TestDeep = &tdAny{}
20
21 // summary(Any): at least one expected value have to match
22 // input(Any): all
23
24 // Any operator compares data against several expected values. During
25 // a match, at least one of them has to match to succeed. Consider it
26 // as a "OR" logical operator.
27 //
28 // td.Cmp(t, "foo", td.Any("bar", "foo", "zip")) // succeeds
29 // td.Cmp(t, "foo", td.Any(
30 // td.Len(4),
31 // td.HasPrefix("f"),
32 // td.HasSuffix("z"),
33 // )) // succeeds coz "f" prefix
34 //
35 // Note [Flatten] function can be used to group or reuse some values or
36 // operators and so avoid boring and inefficient copies:
37 //
38 // stringOps := td.Flatten([]td.TestDeep{td.HasPrefix("f"), td.HasSuffix("z")})
39 // td.Cmp(t, "foobar", td.All(
40 // td.Len(4),
41 // stringOps,
42 // )) // succeeds coz "f" prefix
43 //
44 // TypeBehind method can return a non-nil [reflect.Type] if all items
45 // known non-interface types are equal, or if only interface types
46 // are found (mostly issued from Isa()) and they are equal.
47 //
48 // See also [All] and [None].
49 func Any(expectedValues ...any) TestDeep {
50 return &tdAny{
51 tdListBase: newListBase(expectedValues...),
52 }
53 }
54
55 func (a *tdAny) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error {
56 for _, item := range a.items {
57 ok, err := deepValueEqualFinalOK(ctx, got, item)
58 if err != nil || ok {
59 return err
60 }
61 }
62
63 if ctx.BooleanError {
64 return ctxerr.BooleanError
65 }
66 return ctx.CollectError(&ctxerr.Error{
67 Message: "comparing with Any",
68 Got: got,
69 Expected: a,
70 })
71 }
72
73 func (a *tdAny) TypeBehind() reflect.Type {
74 return uniqTypeBehindSlice(a.items)
75 }