| 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 |
"fmt" |
| 11 |
"reflect" |
| 12 |
|
| 13 |
"github.com/maxatome/go-testdeep/internal/ctxerr" |
| 14 |
) |
| 15 |
|
| 16 |
type tdNone struct { |
| 17 |
tdListBase |
| 18 |
} |
| 19 |
|
| 20 |
var _ TestDeep = &tdNone{} |
| 21 |
|
| 22 |
// summary(None): no values have to match |
| 23 |
// input(None): all |
| 24 |
|
| 25 |
// None operator compares data against several not expected |
| 26 |
// values. During a match, none of them have to match to succeed. |
| 27 |
// |
| 28 |
// td.Cmp(t, 12, td.None(8, 10, 14)) // succeeds |
| 29 |
// td.Cmp(t, 12, td.None(8, 10, 12, 14)) // fails |
| 30 |
// |
| 31 |
// Note [Flatten] function can be used to group or reuse some values or |
| 32 |
// operators and so avoid boring and inefficient copies: |
| 33 |
// |
| 34 |
// prime := td.Flatten([]int{1, 2, 3, 5, 7, 11, 13}) |
| 35 |
// even := td.Flatten([]int{2, 4, 6, 8, 10, 12, 14}) |
| 36 |
// td.Cmp(t, 9, td.None(prime, even)) // succeeds |
| 37 |
// |
| 38 |
// See also [All], [Any] and [Not]. |
| 39 |
func None(notExpectedValues ...any) TestDeep { |
| 40 |
return &tdNone{ |
| 41 |
tdListBase: newListBase(notExpectedValues...), |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
// summary(Not): value must not match |
| 46 |
// input(Not): all |
| 47 |
|
| 48 |
// Not operator compares data against the not expected value. During a |
| 49 |
// match, it must not match to succeed. |
| 50 |
// |
| 51 |
// Not is the same operator as [None] with only one argument. It is |
| 52 |
// provided as a more readable function when only one argument is |
| 53 |
// needed. |
| 54 |
// |
| 55 |
// td.Cmp(t, 12, td.Not(10)) // succeeds |
| 56 |
// td.Cmp(t, 12, td.Not(12)) // fails |
| 57 |
// |
| 58 |
// See also [None]. |
| 59 |
func Not(notExpected any) TestDeep { |
| 60 |
return &tdNone{ |
| 61 |
tdListBase: newListBase(notExpected), |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
func (n *tdNone) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error { |
| 66 |
for idx, item := range n.items { |
| 67 |
ok, err := deepValueEqualFinalOK(ctx, got, item) |
| 68 |
if err != nil { |
| 69 |
return err |
| 70 |
} |
| 71 |
if ok { |
| 72 |
if ctx.BooleanError { |
| 73 |
return ctxerr.BooleanError |
| 74 |
} |
| 75 |
|
| 76 |
var mesg string |
| 77 |
if n.GetLocation().Func == "Not" { |
| 78 |
mesg = "comparing with Not" |
| 79 |
} else { |
| 80 |
mesg = fmt.Sprintf("comparing with None (part %d of %d is OK)", |
| 81 |
idx+1, len(n.items)) |
| 82 |
} |
| 83 |
return ctx.CollectError(&ctxerr.Error{ |
| 84 |
Message: mesg, |
| 85 |
Got: got, |
| 86 |
Expected: n, |
| 87 |
}) |
| 88 |
} |
| 89 |
} |
| 90 |
return nil |
| 91 |
} |