| 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 |
"reflect" |
| 11 |
|
| 12 |
"github.com/maxatome/go-testdeep/internal/ctxerr" |
| 13 |
"github.com/maxatome/go-testdeep/internal/types" |
| 14 |
) |
| 15 |
|
| 16 |
type tdCode struct { |
| 17 |
base |
| 18 |
function reflect.Value |
| 19 |
argType reflect.Type |
| 20 |
tParams int |
| 21 |
} |
| 22 |
|
| 23 |
var _ TestDeep = &tdCode{} |
| 24 |
|
| 25 |
// summary(Code): checks using a custom function |
| 26 |
// input(Code): all |
| 27 |
|
| 28 |
// Code operator allows to check data using a custom function. So |
| 29 |
// fn is a function that must take one parameter whose type must be |
| 30 |
// the same as the type of the compared value. |
| 31 |
// |
| 32 |
// fn can return a single bool kind value, telling that yes or no |
| 33 |
// the custom test is successful: |
| 34 |
// |
| 35 |
// td.Cmp(t, gotTime, |
| 36 |
// td.Code(func(date time.Time) bool { |
| 37 |
// return date.Year() == 2018 |
| 38 |
// })) |
| 39 |
// |
| 40 |
// or two values (bool, string) kinds. The bool value has the same |
| 41 |
// meaning as above, and the string value is used to describe the |
| 42 |
// test when it fails: |
| 43 |
// |
| 44 |
// td.Cmp(t, gotTime, |
| 45 |
// td.Code(func(date time.Time) (bool, string) { |
| 46 |
// if date.Year() == 2018 { |
| 47 |
// return true, "" |
| 48 |
// } |
| 49 |
// return false, "year must be 2018" |
| 50 |
// })) |
| 51 |
// |
| 52 |
// or a single error value. If the returned error is nil, the test |
| 53 |
// succeeded, else the error contains the reason of failure: |
| 54 |
// |
| 55 |
// td.Cmp(t, gotJsonRawMesg, |
| 56 |
// td.Code(func(b json.RawMessage) error { |
| 57 |
// var c map[string]int |
| 58 |
// err := json.Unmarshal(b, &c) |
| 59 |
// if err != nil { |
| 60 |
// return err |
| 61 |
// } |
| 62 |
// if c["test"] != 42 { |
| 63 |
// return fmt.Errorf(`key "test" does not match 42`) |
| 64 |
// } |
| 65 |
// return nil |
| 66 |
// })) |
| 67 |
// |
| 68 |
// This operator allows to handle any specific comparison not handled |
| 69 |
// by standard operators. |
| 70 |
// |
| 71 |
// It is not recommended to call [Cmp] (or any other Cmp* |
| 72 |
// functions or [*T] methods) inside the body of fn, because of |
| 73 |
// confusion produced by output in case of failure. When the data |
| 74 |
// needs to be transformed before being compared again, [Smuggle] |
| 75 |
// operator should be used instead. |
| 76 |
// |
| 77 |
// But in some cases it can be better to handle yourself the |
| 78 |
// comparison than to chain [TestDeep] operators. In this case, fn can |
| 79 |
// be a function receiving one or two [*T] as first parameters and |
| 80 |
// returning no values. |
| 81 |
// |
| 82 |
// When fn expects one [*T] parameter, it is directly derived from the |
| 83 |
// [testing.TB] instance passed originally to [Cmp] (or its derivatives) |
| 84 |
// using [NewT]: |
| 85 |
// |
| 86 |
// td.Cmp(t, httpRequest, td.Code(func(t *td.T, r *http.Request) { |
| 87 |
// token, err := DecodeToken(r.Header.Get("X-Token-1")) |
| 88 |
// if t.CmpNoError(err) { |
| 89 |
// t.True(token.OK()) |
| 90 |
// } |
| 91 |
// })) |
| 92 |
// |
| 93 |
// When fn expects two [*T] parameters, they are directly derived from |
| 94 |
// the [testing.TB] instance passed originally to [Cmp] (or its derivatives) |
| 95 |
// using [AssertRequire]: |
| 96 |
// |
| 97 |
// td.Cmp(t, httpRequest, td.Code(func(assert, require *td.T, r *http.Request) { |
| 98 |
// token, err := DecodeToken(r.Header.Get("X-Token-1")) |
| 99 |
// require.CmpNoError(err) |
| 100 |
// assert.True(token.OK()) |
| 101 |
// })) |
| 102 |
// |
| 103 |
// Note that these forms do not work when there is no initial |
| 104 |
// [testing.TB] instance, like when using [EqDeeplyError] or |
| 105 |
// [EqDeeply] functions, or when the Code operator is called behind |
| 106 |
// the following operators, as they just check if a match occurs |
| 107 |
// without raising an error: [Any], [Bag], [Contains], [ContainsKey], |
| 108 |
// [None], [Not], [NotAny], [Set], [SubBagOf], [SubSetOf], |
| 109 |
// [SuperBagOf] and [SuperSetOf]. |
| 110 |
// |
| 111 |
// RootName is inherited but not the current path, but it can be |
| 112 |
// recovered if needed: |
| 113 |
// |
| 114 |
// got := map[string]int{"foo": 123} |
| 115 |
// td.NewT(t). |
| 116 |
// RootName("PIPO"). |
| 117 |
// Cmp(got, td.Map(map[string]int{}, td.MapEntries{ |
| 118 |
// "foo": td.Code(func(t *td.T, n int) { |
| 119 |
// t.Cmp(n, 124) // inherit only RootName |
| 120 |
// t.RootName(t.Config.OriginalPath()).Cmp(n, 125) // recover current path |
| 121 |
// t.RootName("").Cmp(n, 126) // undo RootName inheritance |
| 122 |
// }), |
| 123 |
// })) |
| 124 |
// |
| 125 |
// produces the following errors: |
| 126 |
// |
| 127 |
// --- FAIL: TestCodeCustom (0.00s) |
| 128 |
// td_code_test.go:339: Failed test |
| 129 |
// PIPO: values differ ← inherit only RootName |
| 130 |
// got: 123 |
| 131 |
// expected: 124 |
| 132 |
// td_code_test.go:338: Failed test |
| 133 |
// PIPO["foo"]: values differ ← recover current path |
| 134 |
// got: 123 |
| 135 |
// expected: 125 |
| 136 |
// td_code_test.go:342: Failed test |
| 137 |
// DATA: values differ ← undo RootName inheritance |
| 138 |
// got: 123 |
| 139 |
// expected: 126 |
| 140 |
// |
| 141 |
// TypeBehind method returns the [reflect.Type] of last parameter of fn. |
| 142 |
func Code(fn any) TestDeep { |
| 143 |
vfn := reflect.ValueOf(fn) |
| 144 |
|
| 145 |
c := tdCode{ |
| 146 |
base: newBase(3), |
| 147 |
function: vfn, |
| 148 |
} |
| 149 |
|
| 150 |
if vfn.Kind() != reflect.Func { |
| 151 |
c.err = ctxerr.OpBadUsage("Code", "(FUNC)", fn, 1, true) |
| 152 |
return &c |
| 153 |
} |
| 154 |
if vfn.IsNil() { |
| 155 |
c.err = ctxerr.OpBad("Code", "Code(FUNC): FUNC cannot be a nil function") |
| 156 |
return &c |
| 157 |
} |
| 158 |
|
| 159 |
fnType := vfn.Type() |
| 160 |
in := fnType.NumIn() |
| 161 |
|
| 162 |
// We accept only: |
| 163 |
// func (arg) bool |
| 164 |
// func (arg) error |
| 165 |
// func (arg) (bool, error) |
| 166 |
// func (*td.T, arg) // with arg ≠ *td.T, as it is certainly an error |
| 167 |
// func (assert, require *td.T, arg) |
| 168 |
if fnType.IsVariadic() || in == 0 || in > 3 || |
| 169 |
(in > 1 && (fnType.In(0) != tType)) || |
| 170 |
(in >= 2 && (in == 2) == (fnType.In(1) == tType)) { |
| 171 |
c.err = ctxerr.OpBad("Code", |
| 172 |
"Code(FUNC): FUNC must take only one non-variadic argument or (*td.T, arg) or (*td.T, *td.T, arg)") |
| 173 |
return &c |
| 174 |
} |
| 175 |
|
| 176 |
// func (arg) bool |
| 177 |
// func (arg) error |
| 178 |
// func (arg) (bool, error) |
| 179 |
if in == 1 { |
| 180 |
switch fnType.NumOut() { |
| 181 |
case 2: // (bool, *string*) |
| 182 |
if fnType.Out(1).Kind() != reflect.String { |
| 183 |
break |
| 184 |
} |
| 185 |
fallthrough |
| 186 |
|
| 187 |
case 1: |
| 188 |
// (*bool*) or (*bool*, string) |
| 189 |
if fnType.Out(0).Kind() == reflect.Bool || |
| 190 |
// (*error*) |
| 191 |
(fnType.NumOut() == 1 && fnType.Out(0) == types.Error) { |
| 192 |
c.argType = fnType.In(0) |
| 193 |
return &c |
| 194 |
} |
| 195 |
} |
| 196 |
|
| 197 |
c.err = ctxerr.OpBad("Code", |
| 198 |
"Code(FUNC): FUNC must return bool or (bool, string) or error") |
| 199 |
return &c |
| 200 |
} |
| 201 |
|
| 202 |
// in == 2 || in == 3 |
| 203 |
// func (*td.T, arg) (with arg ≠ *td.T) |
| 204 |
// func (assert, require *td.T, arg) |
| 205 |
|
| 206 |
if fnType.NumOut() != 0 { |
| 207 |
c.err = ctxerr.OpBad("Code", "Code(FUNC): FUNC must return nothing") |
| 208 |
return &c |
| 209 |
} |
| 210 |
|
| 211 |
c.tParams = in - 1 |
| 212 |
c.argType = fnType.In(c.tParams) |
| 213 |
return &c |
| 214 |
} |
| 215 |
|
| 216 |
func (c *tdCode) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error { |
| 217 |
if c.err != nil { |
| 218 |
return ctx.CollectError(c.err) |
| 219 |
} |
| 220 |
|
| 221 |
if !got.Type().AssignableTo(c.argType) { |
| 222 |
if !ctx.BeLax || !types.IsConvertible(got, c.argType) { |
| 223 |
if ctx.BooleanError { |
| 224 |
return ctxerr.BooleanError |
| 225 |
} |
| 226 |
return ctx.CollectError(&ctxerr.Error{ |
| 227 |
Message: "incompatible parameter type", |
| 228 |
Got: types.RawString(got.Type().String()), |
| 229 |
Expected: types.RawString(c.argType.String()), |
| 230 |
}) |
| 231 |
} |
| 232 |
got = got.Convert(c.argType) |
| 233 |
} |
| 234 |
|
| 235 |
// Refuse to override unexported fields access in this case. It is a |
| 236 |
// choice, as we think it is better to use Code() on surrounding |
| 237 |
// struct instead. |
| 238 |
if !got.CanInterface() { |
| 239 |
if ctx.BooleanError { |
| 240 |
return ctxerr.BooleanError |
| 241 |
} |
| 242 |
return ctx.CollectError(&ctxerr.Error{ |
| 243 |
Message: "cannot compare unexported field", |
| 244 |
Summary: ctxerr.NewSummary("use Code() on surrounding struct instead"), |
| 245 |
}) |
| 246 |
} |
| 247 |
|
| 248 |
if c.tParams == 0 { |
| 249 |
ret := c.function.Call([]reflect.Value{got}) |
| 250 |
if ret[0].Kind() == reflect.Bool { |
| 251 |
if ret[0].Bool() { |
| 252 |
return nil |
| 253 |
} |
| 254 |
} else if ret[0].IsNil() { // reflect.Interface |
| 255 |
return nil |
| 256 |
} |
| 257 |
|
| 258 |
if ctx.BooleanError { |
| 259 |
return ctxerr.BooleanError |
| 260 |
} |
| 261 |
|
| 262 |
var reason string |
| 263 |
if len(ret) > 1 { // (bool, string) |
| 264 |
reason = ret[1].String() |
| 265 |
} else if ret[0].Kind() == reflect.Interface { // (error) |
| 266 |
// For internal use only |
| 267 |
if cErr, ok := ret[0].Interface().(*ctxerr.Error); ok { |
| 268 |
return ctx.CollectError(cErr) |
| 269 |
} |
| 270 |
reason = ret[0].Interface().(error).Error() |
| 271 |
} |
| 272 |
// else (bool) so no reason to report |
| 273 |
|
| 274 |
return ctx.CollectError(&ctxerr.Error{ |
| 275 |
Message: "ran code with %% as argument", |
| 276 |
Summary: ctxerr.NewSummaryReason(got, reason), |
| 277 |
}) |
| 278 |
} |
| 279 |
|
| 280 |
if ctx.OriginalTB == nil { |
| 281 |
return ctx.CollectError(&ctxerr.Error{ |
| 282 |
Message: "cannot build *td.T instance", |
| 283 |
Summary: ctxerr.NewSummary("original testing.TB instance is missing"), |
| 284 |
}) |
| 285 |
} |
| 286 |
|
| 287 |
t := NewT(ctx.OriginalTB) |
| 288 |
t.Config.forkedFromCtx = &ctx |
| 289 |
|
| 290 |
// func(*td.T, arg) |
| 291 |
if c.tParams == 1 { |
| 292 |
c.function.Call([]reflect.Value{ |
| 293 |
reflect.ValueOf(t), |
| 294 |
got, |
| 295 |
}) |
| 296 |
return nil |
| 297 |
} |
| 298 |
|
| 299 |
// func(assert, require *td.T, arg) |
| 300 |
assert, require := AssertRequire(t) |
| 301 |
c.function.Call([]reflect.Value{ |
| 302 |
reflect.ValueOf(assert), |
| 303 |
reflect.ValueOf(require), |
| 304 |
got, |
| 305 |
}) |
| 306 |
return nil |
| 307 |
} |
| 308 |
|
| 309 |
func (c *tdCode) String() string { |
| 310 |
if c.err != nil { |
| 311 |
return c.stringError() |
| 312 |
} |
| 313 |
return "Code(" + c.function.Type().String() + ")" |
| 314 |
} |
| 315 |
|
| 316 |
func (c *tdCode) TypeBehind() reflect.Type { |
| 317 |
if c.err != nil { |
| 318 |
return nil |
| 319 |
} |
| 320 |
return c.argType |
| 321 |
} |