| 1 |
// Copyright (c) 2018-2024, 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 |
"io" |
| 13 |
"reflect" |
| 14 |
"strconv" |
| 15 |
"strings" |
| 16 |
"sync" |
| 17 |
"unicode" |
| 18 |
"unicode/utf8" |
| 19 |
|
| 20 |
"github.com/maxatome/go-testdeep/internal/ctxerr" |
| 21 |
"github.com/maxatome/go-testdeep/internal/types" |
| 22 |
"github.com/maxatome/go-testdeep/internal/util" |
| 23 |
) |
| 24 |
|
| 25 |
// SmuggledGot can be returned by a [Smuggle] function to name the |
| 26 |
// transformed / returned value. |
| 27 |
type SmuggledGot struct { |
| 28 |
Name string |
| 29 |
Got any |
| 30 |
} |
| 31 |
|
| 32 |
const smuggled = "<smuggled>" |
| 33 |
|
| 34 |
var ( |
| 35 |
smuggleFnsMu sync.Mutex |
| 36 |
smuggleFns = map[any]reflect.Value{} |
| 37 |
|
| 38 |
nilError = reflect.New(types.Error).Elem() |
| 39 |
) |
| 40 |
|
| 41 |
func (s SmuggledGot) contextAndGot(ctx ctxerr.Context) (ctxerr.Context, reflect.Value) { |
| 42 |
// If the Name starts with a Letter, prefix it by a "." |
| 43 |
var name string |
| 44 |
if s.Name != "" { |
| 45 |
first, _ := utf8.DecodeRuneInString(s.Name) |
| 46 |
if unicode.IsLetter(first) { |
| 47 |
name = "." |
| 48 |
} |
| 49 |
name += s.Name |
| 50 |
} else { |
| 51 |
name = smuggled |
| 52 |
} |
| 53 |
return ctx.AddCustomLevel(name), reflect.ValueOf(s.Got) |
| 54 |
} |
| 55 |
|
| 56 |
type tdSmuggle struct { |
| 57 |
tdSmugglerBase |
| 58 |
function reflect.Value |
| 59 |
argType reflect.Type |
| 60 |
str string |
| 61 |
} |
| 62 |
|
| 63 |
var _ TestDeep = &tdSmuggle{} |
| 64 |
|
| 65 |
type smuggleValue struct { |
| 66 |
Path string |
| 67 |
Value reflect.Value |
| 68 |
} |
| 69 |
|
| 70 |
var smuggleValueType = reflect.TypeOf(smuggleValue{}) |
| 71 |
|
| 72 |
type smuggleField struct { |
| 73 |
Name string |
| 74 |
Indexed bool |
| 75 |
Method bool |
| 76 |
} |
| 77 |
|
| 78 |
func joinFieldsPath(path []smuggleField) string { |
| 79 |
var buf strings.Builder |
| 80 |
for i, part := range path { |
| 81 |
if part.Indexed { |
| 82 |
fmt.Fprintf(&buf, "[%s]", part.Name) |
| 83 |
} else { |
| 84 |
if i > 0 { |
| 85 |
buf.WriteByte('.') |
| 86 |
} |
| 87 |
buf.WriteString(part.Name) |
| 88 |
if part.Method { |
| 89 |
buf.WriteString("()") |
| 90 |
} |
| 91 |
} |
| 92 |
} |
| 93 |
return buf.String() |
| 94 |
} |
| 95 |
|
| 96 |
func splitFieldsPath(origPath string) ([]smuggleField, error) { |
| 97 |
if origPath == "" { |
| 98 |
return nil, fmt.Errorf("FIELDS_PATH cannot be empty") |
| 99 |
} |
| 100 |
|
| 101 |
privateField := "" |
| 102 |
var res []smuggleField |
| 103 |
for path := origPath; len(path) > 0; { |
| 104 |
r, _ := utf8.DecodeRuneInString(path) |
| 105 |
switch r { |
| 106 |
case '[': |
| 107 |
path = path[1:] |
| 108 |
end := strings.IndexByte(path, ']') |
| 109 |
if end < 0 { |
| 110 |
return nil, fmt.Errorf("cannot find final ']' in FIELDS_PATH %q", origPath) |
| 111 |
} |
| 112 |
res = append(res, smuggleField{Name: path[:end], Indexed: true}) |
| 113 |
path = path[end+1:] |
| 114 |
|
| 115 |
case '.': |
| 116 |
if len(res) == 0 { |
| 117 |
return nil, fmt.Errorf("'.' cannot be the first rune in FIELDS_PATH %q", origPath) |
| 118 |
} |
| 119 |
path = path[1:] |
| 120 |
if path == "" { |
| 121 |
return nil, fmt.Errorf("final '.' in FIELDS_PATH %q is not allowed", origPath) |
| 122 |
} |
| 123 |
r, _ = utf8.DecodeRuneInString(path) |
| 124 |
if r == '.' || r == '[' { |
| 125 |
return nil, fmt.Errorf("unexpected %q after '.' in FIELDS_PATH %q", r, origPath) |
| 126 |
} |
| 127 |
fallthrough |
| 128 |
|
| 129 |
default: |
| 130 |
var field string |
| 131 |
end := strings.IndexAny(path, ".[") |
| 132 |
if end < 0 { |
| 133 |
field, path = path, "" |
| 134 |
} else { |
| 135 |
field, path = path[:end], path[end:] |
| 136 |
} |
| 137 |
|
| 138 |
if strings.HasSuffix(field, "()") { |
| 139 |
if len(field) == 2 { |
| 140 |
return nil, fmt.Errorf("missing method name before () in FIELDS_PATH %q", origPath) |
| 141 |
} |
| 142 |
for j, r := range field[:len(field)-2] { |
| 143 |
if j == 0 && !unicode.IsUpper(r) { |
| 144 |
return nil, fmt.Errorf("method name %q is not public in FIELDS_PATH %q", field, origPath) |
| 145 |
} |
| 146 |
if !unicode.IsLetter(r) && !unicode.IsNumber(r) { |
| 147 |
return nil, fmt.Errorf("unexpected %q in method name %q in FIELDS_PATH %q", r, field, origPath) |
| 148 |
} |
| 149 |
} |
| 150 |
if privateField != "" { |
| 151 |
return nil, fmt.Errorf("cannot call method %s as it is based on an unexported field %q in FIELDS_PATH %q", field, privateField, origPath) |
| 152 |
} |
| 153 |
res = append(res, smuggleField{Name: field[:len(field)-2], Method: true}) |
| 154 |
} else { |
| 155 |
for j, r := range field { |
| 156 |
if privateField == "" && j == 0 && !unicode.IsUpper(r) { |
| 157 |
privateField = field |
| 158 |
} |
| 159 |
if !unicode.IsLetter(r) && (j == 0 || !unicode.IsNumber(r)) { |
| 160 |
return nil, fmt.Errorf("unexpected %q in field name %q in FIELDS_PATH %q", r, field, origPath) |
| 161 |
} |
| 162 |
} |
| 163 |
res = append(res, smuggleField{Name: field}) |
| 164 |
} |
| 165 |
} |
| 166 |
} |
| 167 |
return res, nil |
| 168 |
} |
| 169 |
|
| 170 |
func nilFieldErr(path []smuggleField) error { |
| 171 |
return fmt.Errorf("field %q is nil", joinFieldsPath(path)) |
| 172 |
} |
| 173 |
|
| 174 |
func buildFieldsPathFn(path string) (func(any) (smuggleValue, error), error) { |
| 175 |
parts, err := splitFieldsPath(path) |
| 176 |
if err != nil { |
| 177 |
return nil, err |
| 178 |
} |
| 179 |
|
| 180 |
return func(got any) (smuggleValue, error) { |
| 181 |
vgot := reflect.ValueOf(got) |
| 182 |
|
| 183 |
for idxPart, field := range parts { |
| 184 |
if field.Method { |
| 185 |
var method reflect.Value |
| 186 |
for { |
| 187 |
method = vgot.MethodByName(field.Name) |
| 188 |
if !method.IsValid() { |
| 189 |
switch vgot.Kind() { |
| 190 |
case reflect.Interface, reflect.Ptr: |
| 191 |
if !vgot.IsNil() { |
| 192 |
vgot = vgot.Elem() |
| 193 |
continue |
| 194 |
} |
| 195 |
return smuggleValue{}, nilFieldErr(parts[:idxPart]) |
| 196 |
} |
| 197 |
if idxPart > 0 { |
| 198 |
return smuggleValue{}, fmt.Errorf( |
| 199 |
"field %s (type %s) does not implement %s() method", |
| 200 |
joinFieldsPath(parts[:idxPart]), |
| 201 |
vgot.Type(), |
| 202 |
field.Name) |
| 203 |
} |
| 204 |
return smuggleValue{}, fmt.Errorf( |
| 205 |
"type %s has no method %s()", vgot.Type(), field.Name) |
| 206 |
} |
| 207 |
break |
| 208 |
} |
| 209 |
mt := method.Type() |
| 210 |
if mt.NumIn() != 0 || |
| 211 |
(mt.NumOut() != 1 && (mt.NumOut() != 2 || mt.Out(1) != types.Error)) { |
| 212 |
return smuggleValue{}, fmt.Errorf( |
| 213 |
"cannot call %s, signature %s not handled, only func() A or func() (A, error) allowed", |
| 214 |
joinFieldsPath(parts[:idxPart+1]), |
| 215 |
method.Type()) |
| 216 |
} |
| 217 |
var ret []reflect.Value |
| 218 |
var panicked any |
| 219 |
func() { |
| 220 |
defer func() { panicked = recover() }() |
| 221 |
ret = method.Call(nil) |
| 222 |
}() |
| 223 |
if panicked != nil { |
| 224 |
return smuggleValue{}, fmt.Errorf( |
| 225 |
"method %s panicked: %v", |
| 226 |
joinFieldsPath(parts[:idxPart+1]), |
| 227 |
panicked) |
| 228 |
} |
| 229 |
if len(ret) == 2 && !ret[1].IsNil() { |
| 230 |
return smuggleValue{}, fmt.Errorf( |
| 231 |
"method %s returned an error: %w", |
| 232 |
joinFieldsPath(parts[:idxPart+1]), |
| 233 |
ret[1].Interface().(error)) |
| 234 |
} |
| 235 |
vgot = ret[0] |
| 236 |
continue |
| 237 |
} |
| 238 |
|
| 239 |
// Resolve all interface and pointer dereferences |
| 240 |
origKind := vgot.Kind() |
| 241 |
for { |
| 242 |
switch vgot.Kind() { |
| 243 |
case reflect.Interface, reflect.Ptr: |
| 244 |
if vgot.IsNil() { |
| 245 |
return smuggleValue{}, nilFieldErr(parts[:idxPart]) |
| 246 |
} |
| 247 |
vgot = vgot.Elem() |
| 248 |
continue |
| 249 |
} |
| 250 |
break |
| 251 |
} |
| 252 |
|
| 253 |
if !field.Indexed { |
| 254 |
if vgot.Kind() == reflect.Struct { |
| 255 |
vgot = vgot.FieldByName(field.Name) |
| 256 |
if !vgot.IsValid() { |
| 257 |
return smuggleValue{}, fmt.Errorf( |
| 258 |
"field %q not found", |
| 259 |
joinFieldsPath(parts[:idxPart+1])) |
| 260 |
} |
| 261 |
continue |
| 262 |
} |
| 263 |
// Accept map but only map[string]… |
| 264 |
if vgot.Kind() != reflect.Map || |
| 265 |
vgot.Type().Key().Kind() != reflect.String { |
| 266 |
deref := "" |
| 267 |
if origKind != vgot.Kind() { |
| 268 |
deref = " (after dereferencing)" |
| 269 |
} |
| 270 |
if idxPart == 0 { |
| 271 |
return smuggleValue{}, fmt.Errorf( |
| 272 |
"it is a %s%s and should be a struct or a map[string]…", |
| 273 |
vgot.Kind(), deref) |
| 274 |
} |
| 275 |
if parts[idxPart-1].Method { |
| 276 |
return smuggleValue{}, fmt.Errorf( |
| 277 |
"method %s returned a %s%s and should be a struct or a map[string]…", |
| 278 |
joinFieldsPath(parts[:idxPart]), vgot.Kind(), deref) |
| 279 |
} |
| 280 |
return smuggleValue{}, fmt.Errorf( |
| 281 |
"field %q is a %s%s and should be a struct or a map[string]…", |
| 282 |
joinFieldsPath(parts[:idxPart]), vgot.Kind(), deref) |
| 283 |
} |
| 284 |
} |
| 285 |
|
| 286 |
switch vgot.Kind() { |
| 287 |
case reflect.Map: |
| 288 |
tkey := vgot.Type().Key() |
| 289 |
var vkey reflect.Value |
| 290 |
switch tkey.Kind() { |
| 291 |
case reflect.String: |
| 292 |
vkey = reflect.ValueOf(field.Name) |
| 293 |
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
| 294 |
i, err := strconv.ParseInt(field.Name, 10, 64) |
| 295 |
if err != nil { |
| 296 |
return smuggleValue{}, fmt.Errorf( |
| 297 |
"field %q, %q is not an integer and so cannot match %s map key type", |
| 298 |
joinFieldsPath(parts[:idxPart+1]), field.Name, tkey) |
| 299 |
} |
| 300 |
vkey = reflect.ValueOf(i).Convert(tkey) |
| 301 |
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: |
| 302 |
i, err := strconv.ParseUint(field.Name, 10, 64) |
| 303 |
if err != nil { |
| 304 |
return smuggleValue{}, fmt.Errorf( |
| 305 |
"field %q, %q is not an unsigned integer and so cannot match %s map key type", |
| 306 |
joinFieldsPath(parts[:idxPart+1]), field.Name, tkey) |
| 307 |
} |
| 308 |
vkey = reflect.ValueOf(i).Convert(tkey) |
| 309 |
case reflect.Float32, reflect.Float64: |
| 310 |
f, err := strconv.ParseFloat(field.Name, 64) |
| 311 |
if err != nil { |
| 312 |
return smuggleValue{}, fmt.Errorf( |
| 313 |
"field %q, %q is not a float and so cannot match %s map key type", |
| 314 |
joinFieldsPath(parts[:idxPart+1]), field.Name, tkey) |
| 315 |
} |
| 316 |
vkey = reflect.ValueOf(f).Convert(tkey) |
| 317 |
case reflect.Complex64, reflect.Complex128: |
| 318 |
c, err := strconv.ParseComplex(field.Name, 128) |
| 319 |
if err != nil { |
| 320 |
return smuggleValue{}, fmt.Errorf( |
| 321 |
"field %q, %q is not a complex number and so cannot match %s map key type", |
| 322 |
joinFieldsPath(parts[:idxPart+1]), field.Name, tkey) |
| 323 |
} |
| 324 |
vkey = reflect.ValueOf(c).Convert(tkey) |
| 325 |
default: |
| 326 |
return smuggleValue{}, fmt.Errorf( |
| 327 |
"field %q, %q cannot match unsupported %s map key type", |
| 328 |
joinFieldsPath(parts[:idxPart+1]), field.Name, tkey) |
| 329 |
} |
| 330 |
vgot = vgot.MapIndex(vkey) |
| 331 |
if !vgot.IsValid() { |
| 332 |
return smuggleValue{}, fmt.Errorf("field %q, %q map key not found", |
| 333 |
joinFieldsPath(parts[:idxPart+1]), field.Name) |
| 334 |
} |
| 335 |
|
| 336 |
case reflect.Slice, reflect.Array: |
| 337 |
i, err := strconv.ParseInt(field.Name, 10, 64) |
| 338 |
if err != nil { |
| 339 |
return smuggleValue{}, fmt.Errorf( |
| 340 |
"field %q, %q is not a slice/array index", |
| 341 |
joinFieldsPath(parts[:idxPart+1]), field.Name) |
| 342 |
} |
| 343 |
if i < 0 { |
| 344 |
i = int64(vgot.Len()) + i |
| 345 |
} |
| 346 |
if i < 0 || i >= int64(vgot.Len()) { |
| 347 |
return smuggleValue{}, fmt.Errorf( |
| 348 |
"field %q, %d is out of slice/array range (len %d)", |
| 349 |
joinFieldsPath(parts[:idxPart+1]), i, vgot.Len()) |
| 350 |
} |
| 351 |
vgot = vgot.Index(int(i)) |
| 352 |
|
| 353 |
default: |
| 354 |
if idxPart == 0 { |
| 355 |
return smuggleValue{}, |
| 356 |
fmt.Errorf("it is a %s, but a map, array or slice is expected", |
| 357 |
vgot.Kind()) |
| 358 |
} |
| 359 |
return smuggleValue{}, fmt.Errorf( |
| 360 |
"field %q is a %s, but a map, array or slice is expected", |
| 361 |
joinFieldsPath(parts[:idxPart]), vgot.Kind()) |
| 362 |
} |
| 363 |
} |
| 364 |
return smuggleValue{ |
| 365 |
Path: path, |
| 366 |
Value: vgot, |
| 367 |
}, nil |
| 368 |
}, nil |
| 369 |
} |
| 370 |
|
| 371 |
func getFieldsPathFn(fieldPath string) (reflect.Value, error) { |
| 372 |
smuggleFnsMu.Lock() |
| 373 |
defer smuggleFnsMu.Unlock() |
| 374 |
|
| 375 |
if vfn, ok := smuggleFns[fieldPath]; ok { |
| 376 |
return vfn, nil |
| 377 |
} |
| 378 |
|
| 379 |
fn, err := buildFieldsPathFn(fieldPath) |
| 380 |
if err != nil { |
| 381 |
return reflect.Value{}, err |
| 382 |
} |
| 383 |
|
| 384 |
vfn := reflect.ValueOf(fn) |
| 385 |
smuggleFns[fieldPath] = vfn |
| 386 |
return vfn, err |
| 387 |
} |
| 388 |
|
| 389 |
func getCaster(outType reflect.Type) reflect.Value { |
| 390 |
smuggleFnsMu.Lock() |
| 391 |
defer smuggleFnsMu.Unlock() |
| 392 |
|
| 393 |
if vfn, ok := smuggleFns[outType]; ok { |
| 394 |
return vfn |
| 395 |
} |
| 396 |
|
| 397 |
var fn reflect.Value |
| 398 |
|
| 399 |
switch outType.Kind() { |
| 400 |
case reflect.String: |
| 401 |
fn = buildCaster(outType, true) |
| 402 |
|
| 403 |
case reflect.Slice: |
| 404 |
if outType.Elem().Kind() == reflect.Uint8 { |
| 405 |
// Special case for slices of bytes: falls back on io.Reader if not []byte |
| 406 |
fn = buildCaster(outType, false) |
| 407 |
break |
| 408 |
} |
| 409 |
fallthrough |
| 410 |
|
| 411 |
default: |
| 412 |
// For all other types, take the received param and return |
| 413 |
// it. Smuggle already converted got to the type of param, so the |
| 414 |
// work is done. |
| 415 |
inOut := []reflect.Type{outType} |
| 416 |
fn = reflect.MakeFunc( |
| 417 |
reflect.FuncOf(inOut, inOut, false), |
| 418 |
func(args []reflect.Value) []reflect.Value { return args }, |
| 419 |
) |
| 420 |
} |
| 421 |
|
| 422 |
smuggleFns[outType] = fn |
| 423 |
return fn |
| 424 |
} |
| 425 |
|
| 426 |
// buildCaster returns a function: |
| 427 |
// |
| 428 |
// func(in any) (out outType, err error) |
| 429 |
// |
| 430 |
// dynamically checks… |
| 431 |
// - if useString is false, as outType is a slice of bytes: |
| 432 |
// 1. in is a []byte or convertible to []byte |
| 433 |
// 2. in implements io.Reader |
| 434 |
// - if useString is true, as outType is a string: |
| 435 |
// 1. in is a []byte or convertible to string |
| 436 |
// 2. in implements io.Reader |
| 437 |
func buildCaster(outType reflect.Type, useString bool) reflect.Value { |
| 438 |
zeroRet := reflect.New(outType).Elem() |
| 439 |
|
| 440 |
return reflect.MakeFunc( |
| 441 |
reflect.FuncOf( |
| 442 |
[]reflect.Type{types.Interface}, |
| 443 |
[]reflect.Type{outType, types.Error}, |
| 444 |
false, |
| 445 |
), |
| 446 |
func(args []reflect.Value) []reflect.Value { |
| 447 |
if args[0].IsNil() { |
| 448 |
return []reflect.Value{ |
| 449 |
zeroRet, |
| 450 |
reflect.ValueOf(&ctxerr.Error{ |
| 451 |
Message: "incompatible parameter type", |
| 452 |
Got: types.RawString("nil"), |
| 453 |
Expected: types.RawString(outType.String() + " or convertible or io.Reader"), |
| 454 |
}), |
| 455 |
} |
| 456 |
} |
| 457 |
|
| 458 |
// 1st & only arg is always an interface |
| 459 |
args[0] = args[0].Elem() |
| 460 |
|
| 461 |
if ok, convertible := types.IsTypeOrConvertible(args[0], outType); ok { |
| 462 |
if convertible { |
| 463 |
return []reflect.Value{args[0].Convert(outType), nilError} |
| 464 |
} |
| 465 |
return []reflect.Value{args[0], nilError} |
| 466 |
} |
| 467 |
|
| 468 |
// Our caller encures Interface() can be called safely |
| 469 |
switch ta := args[0].Interface().(type) { |
| 470 |
case io.Reader: |
| 471 |
var b bytes.Buffer |
| 472 |
if _, err := b.ReadFrom(ta); err != nil { |
| 473 |
return []reflect.Value{ |
| 474 |
zeroRet, |
| 475 |
reflect.ValueOf(&ctxerr.Error{ |
| 476 |
Message: "an error occurred while reading from io.Reader", |
| 477 |
Summary: ctxerr.NewSummary(err.Error()), |
| 478 |
}), |
| 479 |
} |
| 480 |
} |
| 481 |
var buf any |
| 482 |
if useString { |
| 483 |
buf = b.String() |
| 484 |
} else { |
| 485 |
buf = b.Bytes() |
| 486 |
} |
| 487 |
return []reflect.Value{ |
| 488 |
reflect.ValueOf(buf).Convert(outType), |
| 489 |
nilError, |
| 490 |
} |
| 491 |
|
| 492 |
default: |
| 493 |
return []reflect.Value{ |
| 494 |
zeroRet, |
| 495 |
reflect.ValueOf(&ctxerr.Error{ |
| 496 |
Message: "incompatible parameter type", |
| 497 |
Got: types.RawString(args[0].Type().String()), |
| 498 |
Expected: types.RawString(outType.String() + " or convertible or io.Reader"), |
| 499 |
}), |
| 500 |
} |
| 501 |
} |
| 502 |
}) |
| 503 |
} |
| 504 |
|
| 505 |
func smuggleParamInfo(depth, lenFnsThenExpectedValue int) string { |
| 506 |
if depth == 1 && lenFnsThenExpectedValue <= 1 { |
| 507 |
return "" |
| 508 |
} |
| 509 |
return util.AsNthParam(depth) |
| 510 |
} |
| 511 |
|
| 512 |
func smuggle(depth int, fn any, fnsThenExpectedValue []any) TestDeep { |
| 513 |
const usage = "(FUNC|FIELDS_PATH|ANY_TYPE[, FUNC|FIELDS_PATH|ANY_TYPE, ...], TESTDEEP_OPERATOR|EXPECTED_VALUE)" |
| 514 |
const fullUsage = "Smuggle" + usage |
| 515 |
|
| 516 |
var expectedValue any |
| 517 |
switch len(fnsThenExpectedValue) { |
| 518 |
case 0: |
| 519 |
s := tdSmuggle{ |
| 520 |
tdSmugglerBase: newSmugglerBase(nil, depth), |
| 521 |
} |
| 522 |
s.err = ctxerr.OpTooFewParams("Smuggle", usage) |
| 523 |
return &s |
| 524 |
|
| 525 |
case 1: |
| 526 |
expectedValue = fnsThenExpectedValue[0] |
| 527 |
|
| 528 |
default: |
| 529 |
expectedValue = smuggle(depth+1, fnsThenExpectedValue[0], fnsThenExpectedValue[1:]) |
| 530 |
} |
| 531 |
|
| 532 |
s := tdSmuggle{ |
| 533 |
tdSmugglerBase: newSmugglerBase(expectedValue, depth), |
| 534 |
} |
| 535 |
|
| 536 |
var vfn reflect.Value |
| 537 |
|
| 538 |
switch rfn := fn.(type) { |
| 539 |
case reflect.Type: |
| 540 |
switch rfn.Kind() { |
| 541 |
case reflect.Func, reflect.Invalid, reflect.Interface: |
| 542 |
s.err = ctxerr.OpBad("Smuggle", |
| 543 |
"usage: Smuggle%s, ANY_TYPE reflect.Type cannot be %s%s", |
| 544 |
usage, rfn.Kind(), smuggleParamInfo(depth, len(fnsThenExpectedValue))) |
| 545 |
return &s |
| 546 |
|
| 547 |
default: |
| 548 |
vfn = getCaster(rfn) |
| 549 |
s.str = "type:" + rfn.String() |
| 550 |
} |
| 551 |
|
| 552 |
case string: |
| 553 |
if rfn == "" { |
| 554 |
vfn = getCaster(reflect.TypeOf(fn)) |
| 555 |
s.str = "type:string" |
| 556 |
break |
| 557 |
} |
| 558 |
var err error |
| 559 |
vfn, err = getFieldsPathFn(rfn) |
| 560 |
if err != nil { |
| 561 |
s.err = ctxerr.OpBad("Smuggle", "Smuggle%s: %s%s", |
| 562 |
usage, err, smuggleParamInfo(depth, len(fnsThenExpectedValue))) |
| 563 |
return &s |
| 564 |
} |
| 565 |
s.str = strconv.Quote(rfn) |
| 566 |
|
| 567 |
default: |
| 568 |
vfn = reflect.ValueOf(fn) |
| 569 |
switch vfn.Kind() { |
| 570 |
case reflect.Func: |
| 571 |
s.str = vfn.Type().String() |
| 572 |
// nothing to check |
| 573 |
|
| 574 |
case reflect.Invalid, reflect.Interface: |
| 575 |
s.err = ctxerr.OpBad("Smuggle", |
| 576 |
"usage: Smuggle%s, ANY_TYPE cannot be nil nor interface%s", |
| 577 |
usage, smuggleParamInfo(depth, len(fnsThenExpectedValue))) |
| 578 |
return &s |
| 579 |
|
| 580 |
default: |
| 581 |
typ := vfn.Type() |
| 582 |
vfn = getCaster(typ) |
| 583 |
s.str = "type:" + typ.String() |
| 584 |
} |
| 585 |
} |
| 586 |
|
| 587 |
fnType := vfn.Type() |
| 588 |
if fnType.IsVariadic() || fnType.NumIn() != 1 { |
| 589 |
s.err = ctxerr.OpBad("Smuggle", |
| 590 |
fullUsage+": FUNC must take only one non-variadic argument"+ |
| 591 |
smuggleParamInfo(depth, len(fnsThenExpectedValue))) |
| 592 |
return &s |
| 593 |
} |
| 594 |
|
| 595 |
switch fnType.NumOut() { |
| 596 |
case 3: // (value, bool, string) |
| 597 |
if fnType.Out(2).Kind() != reflect.String { |
| 598 |
break |
| 599 |
} |
| 600 |
fallthrough |
| 601 |
|
| 602 |
case 2: |
| 603 |
// (value, *bool*) or (value, *bool*, string) |
| 604 |
if fnType.Out(1).Kind() != reflect.Bool && |
| 605 |
// (value, *error*) |
| 606 |
(fnType.NumOut() > 2 || |
| 607 |
fnType.Out(1) != types.Error) { |
| 608 |
break |
| 609 |
} |
| 610 |
fallthrough |
| 611 |
|
| 612 |
case 1: // (value) |
| 613 |
if vfn.IsNil() { |
| 614 |
s.err = ctxerr.OpBad("Smuggle", |
| 615 |
"Smuggle(FUNC): FUNC cannot be a nil function"+ |
| 616 |
smuggleParamInfo(depth, len(fnsThenExpectedValue))) |
| 617 |
return &s |
| 618 |
} |
| 619 |
|
| 620 |
s.argType = fnType.In(0) |
| 621 |
s.function = vfn |
| 622 |
|
| 623 |
if !s.isTestDeeper { |
| 624 |
s.expectedValue = reflect.ValueOf(expectedValue) |
| 625 |
} |
| 626 |
return &s |
| 627 |
} |
| 628 |
|
| 629 |
s.err = ctxerr.OpBad("Smuggle", |
| 630 |
fullUsage+": FUNC must return value or (value, bool) or (value, bool, string) or (value, error)") |
| 631 |
return &s |
| 632 |
} |
| 633 |
|
| 634 |
// summary(Smuggle): changes data contents or mutates it into another |
| 635 |
// type via a custom function or a struct fields-path before stepping |
| 636 |
// down in favor of generic comparison process |
| 637 |
// input(Smuggle): all |
| 638 |
|
| 639 |
// Smuggle operator allows to change data contents or mutate it into |
| 640 |
// another type before stepping down in favor of generic comparison |
| 641 |
// process. Of course it is a smuggler operator. So fn is a function |
| 642 |
// that must take one parameter whose type must be convertible to the |
| 643 |
// type of the compared value. |
| 644 |
// |
| 645 |
// As convenient shortcuts, fn can be a string specifying a |
| 646 |
// fields-path through structs, maps & slices, or any other type, in |
| 647 |
// this case a simple cast is done (see below for details). |
| 648 |
// |
| 649 |
// fnsThenExpectedValue must have a length of 1 or more items. Its |
| 650 |
// last item corresponds to the expectedValue. The previous items, if |
| 651 |
// any, are like fn and are used sequentially after fn allowing to |
| 652 |
// implicitly chain Smuggle calls, so the following [Cmp] calls are |
| 653 |
// strictly equivalent: |
| 654 |
// |
| 655 |
// td.Cmp(t, "+28", td.Smuggle(FN1, td.Smuggle(FN2, td.Smuggle(FN3, "28")))) |
| 656 |
// td.Cmp(t, "+28", td.Smuggle(FN1, FN2, FN3, "28")) |
| 657 |
// |
| 658 |
// Each fn must return at least one value. These value will be |
| 659 |
// compared as is to expectedValue, here integer 28: |
| 660 |
// |
| 661 |
// td.Cmp(t, "0028", |
| 662 |
// td.Smuggle(func(value string) int { |
| 663 |
// num, _ := strconv.Atoi(value) |
| 664 |
// return num |
| 665 |
// }, 28), |
| 666 |
// ) |
| 667 |
// |
| 668 |
// or using an other [TestDeep] operator, here [Between](28, 30): |
| 669 |
// |
| 670 |
// td.Cmp(t, "0029", |
| 671 |
// td.Smuggle(func(value string) int { |
| 672 |
// num, _ := strconv.Atoi(value) |
| 673 |
// return num |
| 674 |
// }, td.Between(28, 30)), |
| 675 |
// ) |
| 676 |
// |
| 677 |
// Each fn can return a second boolean value, used to tell that a |
| 678 |
// problem occurred and so stop the comparison: |
| 679 |
// |
| 680 |
// td.Cmp(t, "0029", |
| 681 |
// td.Smuggle(func(value string) (int, bool) { |
| 682 |
// num, err := strconv.Atoi(value) |
| 683 |
// return num, err == nil |
| 684 |
// }, td.Between(28, 30)), |
| 685 |
// ) |
| 686 |
// |
| 687 |
// Each fn can return a third string value which is used to describe |
| 688 |
// the test when a problem occurred (false second boolean value): |
| 689 |
// |
| 690 |
// td.Cmp(t, "0029", |
| 691 |
// td.Smuggle(func(value string) (int, bool, string) { |
| 692 |
// num, err := strconv.Atoi(value) |
| 693 |
// if err != nil { |
| 694 |
// return 0, false, "string must contain a number" |
| 695 |
// } |
| 696 |
// return num, true, "" |
| 697 |
// }, td.Between(28, 30)), |
| 698 |
// ) |
| 699 |
// |
| 700 |
// Instead of returning (X, bool) or (X, bool, string), each fn can |
| 701 |
// return (X, error). When a problem occurs, the returned error is |
| 702 |
// non-nil, as in: |
| 703 |
// |
| 704 |
// td.Cmp(t, "0029", |
| 705 |
// td.Smuggle(func(value string) (int, error) { |
| 706 |
// num, err := strconv.Atoi(value) |
| 707 |
// return num, err |
| 708 |
// }, td.Between(28, 30)), |
| 709 |
// ) |
| 710 |
// |
| 711 |
// Which can be simplified to: |
| 712 |
// |
| 713 |
// td.Cmp(t, "0029", td.Smuggle(strconv.Atoi, td.Between(28, 30))) |
| 714 |
// |
| 715 |
// Imagine you want to compare that the Year of a date is between 2010 |
| 716 |
// and 2020: |
| 717 |
// |
| 718 |
// td.Cmp(t, time.Date(2015, time.May, 1, 1, 2, 3, 0, time.UTC), |
| 719 |
// td.Smuggle(func(date time.Time) int { return date.Year() }, |
| 720 |
// td.Between(2010, 2020)), |
| 721 |
// ) |
| 722 |
// |
| 723 |
// In this case the data location forwarded to next test will be |
| 724 |
// something like "DATA.MyTimeField<smuggled>", but you can act on it |
| 725 |
// too by returning a [SmuggledGot] struct (by value or by address): |
| 726 |
// |
| 727 |
// td.Cmp(t, time.Date(2015, time.May, 1, 1, 2, 3, 0, time.UTC), |
| 728 |
// td.Smuggle(func(date time.Time) SmuggledGot { |
| 729 |
// return SmuggledGot{ |
| 730 |
// Name: "Year", |
| 731 |
// Got: date.Year(), |
| 732 |
// } |
| 733 |
// }, td.Between(2010, 2020)), |
| 734 |
// ) |
| 735 |
// |
| 736 |
// then the data location forwarded to next test will be something like |
| 737 |
// "DATA.MyTimeField.Year". The "." between the current path (here |
| 738 |
// "DATA.MyTimeField") and the returned Name "Year" is automatically |
| 739 |
// added when Name starts with a Letter. |
| 740 |
// |
| 741 |
// Note that [SmuggledGot] and [*SmuggledGot] returns are treated |
| 742 |
// equally, and they are only used when fn has only one returned value |
| 743 |
// or when the second boolean returned value is true. |
| 744 |
// |
| 745 |
// Of course, all cases can go together: |
| 746 |
// |
| 747 |
// // Accepts a "YYYY/mm/DD HH:MM:SS" string to produce a time.Time and tests |
| 748 |
// // whether this date is contained between 2 hours before now and now. |
| 749 |
// td.Cmp(t, "2020-01-25 12:13:14", |
| 750 |
// td.Smuggle(func(date string) (*SmuggledGot, bool, string) { |
| 751 |
// date, err := time.Parse("2006/01/02 15:04:05", date) |
| 752 |
// if err != nil { |
| 753 |
// return nil, false, `date must conform to "YYYY/mm/DD HH:MM:SS" format` |
| 754 |
// } |
| 755 |
// return &SmuggledGot{ |
| 756 |
// Name: "Date", |
| 757 |
// Got: date, |
| 758 |
// }, true, "" |
| 759 |
// }, td.Between(time.Now().Add(-2*time.Hour), time.Now())), |
| 760 |
// ) |
| 761 |
// |
| 762 |
// or: |
| 763 |
// |
| 764 |
// // Accepts a "YYYY/mm/DD HH:MM:SS" string to produce a time.Time and tests |
| 765 |
// // whether this date is contained between 2 hours before now and now. |
| 766 |
// td.Cmp(t, "2020-01-25 12:13:14", |
| 767 |
// td.Smuggle(func(date string) (*SmuggledGot, error) { |
| 768 |
// date, err := time.Parse("2006/01/02 15:04:05", date) |
| 769 |
// if err != nil { |
| 770 |
// return nil, err |
| 771 |
// } |
| 772 |
// return &SmuggledGot{ |
| 773 |
// Name: "Date", |
| 774 |
// Got: date, |
| 775 |
// }, nil |
| 776 |
// }, td.Between(time.Now().Add(-2*time.Hour), time.Now())), |
| 777 |
// ) |
| 778 |
// |
| 779 |
// Smuggle can also be used to access a struct field embedded in |
| 780 |
// several struct layers. |
| 781 |
// |
| 782 |
// type A struct{ Num int } |
| 783 |
// // func (a *A) String() string { return fmt.Sprintf("Num is %d", a.Num) } |
| 784 |
// type B struct{ As map[string]*A } |
| 785 |
// type C struct{ B B } |
| 786 |
// got := C{B: B{As: map[string]*A{"foo": {Num: 12}}}} |
| 787 |
// |
| 788 |
// // Tests that got.B.A.Num is 12 |
| 789 |
// td.Cmp(t, got, |
| 790 |
// td.Smuggle(func(c C) int { |
| 791 |
// return c.B.As["foo"].Num |
| 792 |
// }, 12)) |
| 793 |
// |
| 794 |
// As brought up above, a fields-path can be passed as fn value |
| 795 |
// instead of a function pointer. Using this feature, the [Cmp] |
| 796 |
// call in the above example can be rewritten as follows: |
| 797 |
// |
| 798 |
// // Tests that got.B.As["foo"].Num is 12 |
| 799 |
// td.Cmp(t, got, td.Smuggle("B.As[foo].Num", 12)) |
| 800 |
// |
| 801 |
// For convenience, if a map[string]… is addressed, it can be done |
| 802 |
// like a struct field as "foo" key in: |
| 803 |
// |
| 804 |
// td.Cmp(t, got, td.Smuggle("B.As.foo.Num", 12)) |
| 805 |
// |
| 806 |
// In addition, simple public methods can also be called like in: |
| 807 |
// |
| 808 |
// td.Cmp(t, got, td.Smuggle("B.As[foo].String()", "Num is 12")) |
| 809 |
// |
| 810 |
// Allowed methods must not take any parameter and must return one |
| 811 |
// value or a value and an error. For the latter case, if the method |
| 812 |
// returns a non-nil error, the comparison fails. The comparison also |
| 813 |
// fails if a panic occurs or if a method cannot be called. No private |
| 814 |
// fields should be traversed before calling the method. For fun, |
| 815 |
// consider a more complex example involving [reflect] and chaining |
| 816 |
// method calls: |
| 817 |
// |
| 818 |
// got := reflect.Valueof(&C{B: B{As: map[string]*A{"foo": {Num: 12}}}}) |
| 819 |
// td.Cmp(t, got, td.Smuggle("Elem().Interface().B.As[foo].String()", "Num is 12")) |
| 820 |
// |
| 821 |
// Contrary to [JSONPointer] operator, private fields can be followed |
| 822 |
// and public methods on public fields can be called. Arrays, slices |
| 823 |
// and maps work using the index/key inside square brackets (e.g. [12] |
| 824 |
// or [foo]). Maps work only for simple key types (string or numbers), |
| 825 |
// without "" when using strings (e.g. [foo]). |
| 826 |
// |
| 827 |
// Behind the scenes, a temporary function is automatically created to |
| 828 |
// achieve the same goal, but adds some checks against nil values and |
| 829 |
// auto-dereferences interfaces and pointers, even on several levels, |
| 830 |
// like in: |
| 831 |
// |
| 832 |
// type A struct{ N any } |
| 833 |
// num := 12 |
| 834 |
// pnum := &num |
| 835 |
// td.Cmp(t, A{N: &pnum}, td.Smuggle("N", 12)) |
| 836 |
// |
| 837 |
// Last but not least, a simple type can be passed as fn to operate |
| 838 |
// a cast, handling specifically strings and slices of bytes: |
| 839 |
// |
| 840 |
// td.Cmp(t, `{"foo":1}`, td.Smuggle(json.RawMessage{}, td.JSON(`{"foo":1}`))) |
| 841 |
// // or equally |
| 842 |
// td.Cmp(t, `{"foo":1}`, td.Smuggle(json.RawMessage(nil), td.JSON(`{"foo":1}`))) |
| 843 |
// |
| 844 |
// converts on the fly a string to a [json.RawMessage] (alias to |
| 845 |
// [jsontext.Value] starting go1.27) so [JSON] operator can parse it |
| 846 |
// as JSON. This is mostly a shortcut for: |
| 847 |
// |
| 848 |
// td.Cmp(t, `{"foo":1}`, td.Smuggle( |
| 849 |
// func(r json.RawMessage) json.RawMessage { return r }, |
| 850 |
// td.JSON(`{"foo":1}`))) |
| 851 |
// |
| 852 |
// except that for strings and slices of bytes (like here), it accepts |
| 853 |
// [io.Reader] interface too: |
| 854 |
// |
| 855 |
// var body io.Reader |
| 856 |
// // … |
| 857 |
// td.Cmp(t, body, td.Smuggle(json.RawMessage{}, td.JSON(`{"foo":1}`))) |
| 858 |
// // or equally |
| 859 |
// td.Cmp(t, body, td.Smuggle(json.RawMessage(nil), td.JSON(`{"foo":1}`))) |
| 860 |
// |
| 861 |
// This last example allows to easily inject body content into JSON |
| 862 |
// operator. |
| 863 |
// |
| 864 |
// The difference between Smuggle and [Code] operators is that [Code] |
| 865 |
// is used to do a final comparison while Smuggle transforms the data |
| 866 |
// and then steps down in favor of generic comparison |
| 867 |
// process. Moreover, the type accepted as input for the function is |
| 868 |
// more lax to facilitate the writing of tests (e.g. the function can |
| 869 |
// accept a float64 and the got value be an int). See examples. On the |
| 870 |
// other hand, the output type is strict and must match exactly the |
| 871 |
// expected value type. The fields-path string fn shortcut and the |
| 872 |
// cast feature are not available with [Code] operator. |
| 873 |
// |
| 874 |
// TypeBehind method returns the [reflect.Type] of only parameter of |
| 875 |
// fn. For the case where fn is a fields-path, it is always |
| 876 |
// any, as the type can not be known in advance. |
| 877 |
// |
| 878 |
// See also [Code], [JSONPointer] and [Flatten]. |
| 879 |
// |
| 880 |
// [json.RawMessage]: https://pkg.go.dev/encoding/json#RawMessage |
| 881 |
// [jsontext.Value]: https://pkg.go.dev/encoding/json/jsontext#Value |
| 882 |
func Smuggle(fn any, fnsThenExpectedValue ...any) TestDeep { |
| 883 |
return smuggle(1, fn, fnsThenExpectedValue) |
| 884 |
} |
| 885 |
|
| 886 |
func (s *tdSmuggle) laxConvert(got reflect.Value) (reflect.Value, bool) { |
| 887 |
if got.IsValid() { |
| 888 |
if types.IsConvertible(got, s.argType) { |
| 889 |
return got.Convert(s.argType), true |
| 890 |
} |
| 891 |
} else if s.argType == types.Interface { |
| 892 |
// nil only accepted if any expected |
| 893 |
return reflect.New(types.Interface).Elem(), true |
| 894 |
} |
| 895 |
return got, false |
| 896 |
} |
| 897 |
|
| 898 |
func (s *tdSmuggle) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error { |
| 899 |
if s.err != nil { |
| 900 |
return ctx.CollectError(s.err) |
| 901 |
} |
| 902 |
|
| 903 |
got, ok := s.laxConvert(got) |
| 904 |
if !ok { |
| 905 |
if ctx.BooleanError { |
| 906 |
return ctxerr.BooleanError |
| 907 |
} |
| 908 |
err := ctxerr.Error{ |
| 909 |
Message: "incompatible parameter type", |
| 910 |
Expected: types.RawString(s.argType.String()), |
| 911 |
} |
| 912 |
if got.IsValid() { |
| 913 |
err.Got = types.RawString(got.Type().String()) |
| 914 |
} else { |
| 915 |
err.Got = types.RawString("nil") |
| 916 |
} |
| 917 |
return ctx.CollectError(&err) |
| 918 |
} |
| 919 |
|
| 920 |
// Refuse to override unexported fields access in this case. It is a |
| 921 |
// choice, as we think it is better to work on surrounding struct |
| 922 |
// instead. |
| 923 |
if !got.CanInterface() { |
| 924 |
if ctx.BooleanError { |
| 925 |
return ctxerr.BooleanError |
| 926 |
} |
| 927 |
return ctx.CollectError(&ctxerr.Error{ |
| 928 |
Message: "cannot smuggle unexported field", |
| 929 |
Summary: ctxerr.NewSummary("work on surrounding struct instead"), |
| 930 |
}) |
| 931 |
} |
| 932 |
|
| 933 |
ret := s.function.Call([]reflect.Value{got}) |
| 934 |
if len(ret) == 1 || |
| 935 |
(ret[1].Kind() == reflect.Bool && ret[1].Bool()) || |
| 936 |
(ret[1].Kind() == reflect.Interface && ret[1].IsNil()) { |
| 937 |
newGot := ret[0] |
| 938 |
|
| 939 |
var newCtx ctxerr.Context |
| 940 |
if newGot.IsValid() { |
| 941 |
switch newGot.Type() { |
| 942 |
case smuggledGotType: |
| 943 |
newCtx, newGot = newGot.Interface().(SmuggledGot).contextAndGot(ctx) |
| 944 |
|
| 945 |
case smuggledGotPtrType: |
| 946 |
if smGot := newGot.Interface().(*SmuggledGot); smGot == nil { |
| 947 |
newCtx, newGot = ctx, reflect.ValueOf(nil) |
| 948 |
} else { |
| 949 |
newCtx, newGot = smGot.contextAndGot(ctx) |
| 950 |
} |
| 951 |
|
| 952 |
case smuggleValueType: |
| 953 |
smv := newGot.Interface().(smuggleValue) |
| 954 |
newCtx, newGot = ctx.AddCustomLevel("."+smv.Path), smv.Value |
| 955 |
|
| 956 |
default: |
| 957 |
newCtx = ctx.AddCustomLevel(smuggled) |
| 958 |
} |
| 959 |
} |
| 960 |
return deepValueEqual(newCtx, newGot, s.expectedValue) |
| 961 |
} |
| 962 |
|
| 963 |
if ctx.BooleanError { |
| 964 |
return ctxerr.BooleanError |
| 965 |
} |
| 966 |
|
| 967 |
var reason string |
| 968 |
switch len(ret) { |
| 969 |
case 3: // (value, false, string) |
| 970 |
reason = ret[2].String() |
| 971 |
case 2: |
| 972 |
// (value, error) |
| 973 |
if ret[1].Kind() == reflect.Interface { |
| 974 |
// For internal use only |
| 975 |
if cErr, ok := ret[1].Interface().(*ctxerr.Error); ok { |
| 976 |
return ctx.CollectError(cErr) |
| 977 |
} |
| 978 |
reason = ret[1].Interface().(error).Error() |
| 979 |
} |
| 980 |
// (value, false) |
| 981 |
} |
| 982 |
return ctx.CollectError(&ctxerr.Error{ |
| 983 |
Message: "ran smuggle code with %% as argument", |
| 984 |
Summary: ctxerr.NewSummaryReason(got, reason), |
| 985 |
}) |
| 986 |
} |
| 987 |
|
| 988 |
func (s *tdSmuggle) HandleInvalid() bool { |
| 989 |
return true // Knows how to handle untyped nil values (aka invalid values) |
| 990 |
} |
| 991 |
|
| 992 |
func (s *tdSmuggle) String() string { |
| 993 |
if s.err != nil { |
| 994 |
return "Smuggle" + stringErrorParam |
| 995 |
} |
| 996 |
return "Smuggle(" + s.str + ", " + util.ToString(s.expectedValue) + ")" |
| 997 |
} |
| 998 |
|
| 999 |
func (s *tdSmuggle) TypeBehind() reflect.Type { |
| 1000 |
if s.err != nil { |
| 1001 |
return nil |
| 1002 |
} |
| 1003 |
return s.argType |
| 1004 |
} |