| 1 |
// Copyright (c) 2024-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 |
"errors" |
| 11 |
"fmt" |
| 12 |
"reflect" |
| 13 |
"sort" |
| 14 |
"strings" |
| 15 |
|
| 16 |
"github.com/maxatome/go-testdeep/internal/compare" |
| 17 |
"github.com/maxatome/go-testdeep/internal/ctxerr" |
| 18 |
"github.com/maxatome/go-testdeep/internal/dark" |
| 19 |
"github.com/maxatome/go-testdeep/internal/types" |
| 20 |
"github.com/maxatome/go-testdeep/internal/util" |
| 21 |
"github.com/maxatome/go-testdeep/internal/visited" |
| 22 |
) |
| 23 |
|
| 24 |
type tdSortBase struct { |
| 25 |
mkSortFn func(reflect.Type) (reflect.Value, error) |
| 26 |
} |
| 27 |
|
| 28 |
func (sb *tdSortBase) initSortBase(how ...any) error { |
| 29 |
switch l := len(how); l { |
| 30 |
case 0: |
| 31 |
how = []any{1} |
| 32 |
case 1: |
| 33 |
default: // list of fields-paths used by Sorted only |
| 34 |
fieldsPaths := make([]string, l) |
| 35 |
for i, si := range how { |
| 36 |
s, ok := si.(string) |
| 37 |
if !ok { |
| 38 |
return errors.New("string... expected " + util.BadParam(si, i+1, true)) |
| 39 |
} |
| 40 |
fieldsPaths[i] = s |
| 41 |
} |
| 42 |
how = []any{fieldsPaths} |
| 43 |
} |
| 44 |
|
| 45 |
switch v := how[0].(type) { |
| 46 |
case nil: |
| 47 |
sb.mkSortFn = mkSortAsc |
| 48 |
case int: |
| 49 |
sb.mkSortFn = mkSortAscDesc(v >= 0) |
| 50 |
case float64: // to be used in JSON, SubJSONOf & SuperJSONOf |
| 51 |
sb.mkSortFn = mkSortAscDesc(v >= 0) |
| 52 |
case string: // one fields-path |
| 53 |
sb.mkSortFn = func(typ reflect.Type) (reflect.Value, error) { |
| 54 |
return mkSortFieldsPaths(typ, []string{v}) |
| 55 |
} |
| 56 |
case []any: // fields-paths list in JSON context |
| 57 |
ss := make([]string, len(v)) |
| 58 |
var ok bool |
| 59 |
for i, s := range v { |
| 60 |
ss[i], ok = s.(string) |
| 61 |
if !ok { |
| 62 |
return fmt.Errorf( |
| 63 |
"slice of strings expected as how, %T encountered at pos %d", s, i) |
| 64 |
} |
| 65 |
} |
| 66 |
sb.mkSortFn = func(typ reflect.Type) (reflect.Value, error) { |
| 67 |
return mkSortFieldsPaths(typ, ss) |
| 68 |
} |
| 69 |
case []string: // fields-paths list |
| 70 |
sb.mkSortFn = func(typ reflect.Type) (reflect.Value, error) { |
| 71 |
return mkSortFieldsPaths(typ, v) |
| 72 |
} |
| 73 |
default: |
| 74 |
vv := reflect.ValueOf(v) |
| 75 |
if vv.Kind() != reflect.Func { |
| 76 |
return errors.New(util.BadParam(v, 1, true)) |
| 77 |
} |
| 78 |
ft := vv.Type() |
| 79 |
if ft.IsVariadic() || ft.NumIn() != 2 || ft.In(0) != ft.In(1) || |
| 80 |
ft.NumOut() != 1 || ft.Out(0) != types.Bool { |
| 81 |
return fmt.Errorf("SORT_FUNC must match func(T, T) bool signature, not %T", v) |
| 82 |
} |
| 83 |
sb.mkSortFn = func(typ reflect.Type) (reflect.Value, error) { |
| 84 |
if !typ.AssignableTo(ft.In(0)) { |
| 85 |
return reflect.Value{}, fmt.Errorf("%s is not assignable to %s", typ, ft.In(0)) |
| 86 |
} |
| 87 |
return vv, nil |
| 88 |
} |
| 89 |
} |
| 90 |
return nil |
| 91 |
} |
| 92 |
|
| 93 |
func mkSortAscDesc(asc bool) func(reflect.Type) (reflect.Value, error) { |
| 94 |
if asc { |
| 95 |
return mkSortAsc |
| 96 |
} |
| 97 |
return mkSortDesc |
| 98 |
} |
| 99 |
|
| 100 |
func mkSortAsc(typ reflect.Type) (reflect.Value, error) { |
| 101 |
v := visited.NewVisited() |
| 102 |
return reflect.MakeFunc( |
| 103 |
reflect.FuncOf([]reflect.Type{typ, typ}, []reflect.Type{types.Bool}, false), |
| 104 |
func(args []reflect.Value) []reflect.Value { |
| 105 |
less := compare.Compare(v, args[0], args[1]) < 0 |
| 106 |
return []reflect.Value{reflect.ValueOf(less)} |
| 107 |
}), nil |
| 108 |
} |
| 109 |
|
| 110 |
func mkSortDesc(typ reflect.Type) (reflect.Value, error) { |
| 111 |
v := visited.NewVisited() |
| 112 |
return reflect.MakeFunc( |
| 113 |
reflect.FuncOf([]reflect.Type{typ, typ}, []reflect.Type{types.Bool}, false), |
| 114 |
func(args []reflect.Value) []reflect.Value { |
| 115 |
less := compare.Compare(v, args[1], args[0]) < 0 |
| 116 |
return []reflect.Value{reflect.ValueOf(less)} |
| 117 |
}), nil |
| 118 |
} |
| 119 |
|
| 120 |
func mkSortFieldsPaths(typ reflect.Type, fieldsPaths []string) (reflect.Value, error) { |
| 121 |
type sortFP struct { |
| 122 |
fn func(any) (smuggleValue, error) |
| 123 |
asc bool |
| 124 |
} |
| 125 |
fns := make([]sortFP, len(fieldsPaths)) |
| 126 |
for i, fp := range fieldsPaths { |
| 127 |
var sfp sortFP |
| 128 |
if strings.HasPrefix(fp, "-") { |
| 129 |
fp = fp[1:] |
| 130 |
} else { |
| 131 |
sfp.asc = true |
| 132 |
fp = strings.TrimPrefix(fp, "+") // optional |
| 133 |
} |
| 134 |
fn, err := getFieldsPathFn(fp) |
| 135 |
if err != nil { |
| 136 |
return reflect.Value{}, err |
| 137 |
} |
| 138 |
sfp.fn = fn.Interface().(func(any) (smuggleValue, error)) |
| 139 |
fns[i] = sfp |
| 140 |
} |
| 141 |
|
| 142 |
v := visited.NewVisited() |
| 143 |
return reflect.MakeFunc( |
| 144 |
reflect.FuncOf([]reflect.Type{typ, typ}, []reflect.Type{types.Bool}, false), |
| 145 |
func(args []reflect.Value) []reflect.Value { |
| 146 |
a, aOK := dark.GetInterface(args[0], true) |
| 147 |
b, bOK := dark.GetInterface(args[1], true) |
| 148 |
if aOK && bOK { |
| 149 |
for _, fn := range fns { |
| 150 |
va, aErr := fn.fn(a) |
| 151 |
vb, bErr := fn.fn(b) |
| 152 |
if aErr != nil || bErr != nil { |
| 153 |
if aErr == nil || bErr == nil { |
| 154 |
// nonexistent field is greater |
| 155 |
return []reflect.Value{reflect.ValueOf(aErr == nil)} |
| 156 |
} |
| 157 |
break // both nonexistent fields, use Compare |
| 158 |
} |
| 159 |
cmp := compare.Compare(v, va.Value, vb.Value) |
| 160 |
if cmp == 0 { |
| 161 |
continue |
| 162 |
} |
| 163 |
return []reflect.Value{reflect.ValueOf(cmp < 0 == fn.asc)} |
| 164 |
} |
| 165 |
} |
| 166 |
less := compare.Compare(v, args[0], args[1]) < 0 |
| 167 |
return []reflect.Value{reflect.ValueOf(less)} |
| 168 |
}), nil |
| 169 |
} |
| 170 |
|
| 171 |
const sortUsage = "(SORT_FUNC|int|string|[]string, TESTDEEP_OPERATOR|EXPECTED_VALUE)" |
| 172 |
|
| 173 |
type tdSort struct { |
| 174 |
tdSmugglerBase |
| 175 |
tdSortBase |
| 176 |
how any |
| 177 |
} |
| 178 |
|
| 179 |
var _ TestDeep = &tdSort{} |
| 180 |
|
| 181 |
// summary(Sort): sorts a slice or an array before comparing its content |
| 182 |
// input(Sort): array,slice,ptr(ptr on array/slice) |
| 183 |
|
| 184 |
// Sort is a smuggler operator. It takes an array, a slice or a |
| 185 |
// pointer on array/slice, it sorts it using how and compares the |
| 186 |
// sorted result to expectedValue. It can be seen as an alternative to |
| 187 |
// [Bag]. |
| 188 |
// |
| 189 |
// how can be: |
| 190 |
// - nil or a float64/int >= 0 for a generic ascending order; |
| 191 |
// - a float64/int < 0 for a generic descending order; |
| 192 |
// - a string specifying a fields-path (optionally prefixed by "+" |
| 193 |
// or "-" for respectively an ascending or a descending order, |
| 194 |
// defaulting to ascending one); |
| 195 |
// - a []string containing a list of fields-paths (as above), second |
| 196 |
// and next fields-paths are checked when the previous ones are equal; |
| 197 |
// - a function matching func(a, b T) bool signature and returning |
| 198 |
// true if a is before b. |
| 199 |
// |
| 200 |
// A fields-path, also used by [Smuggle] and [Sorted] operators, |
| 201 |
// allows to access nested structs fields and maps & slices items. See |
| 202 |
// [Smuggle] for details on fields-path possibilities. |
| 203 |
// |
| 204 |
// type A struct{ props map[string]int } |
| 205 |
// p12 := A{props: map[string]int{"priority": 12}} |
| 206 |
// p23 := A{props: map[string]int{"priority": 23}} |
| 207 |
// p34 := A{props: map[string]int{"priority": 34}} |
| 208 |
// got := []A{p23, p12, p34} |
| 209 |
// td.Cmp(t, got, td.Sort("-props[priority]", []A{p34, p23, p12})) // succeeds |
| 210 |
// |
| 211 |
// how can be a float64 to allow Sort to be used in expected JSON of |
| 212 |
// [JSON], [SubJSONOf] & [SuperJSONOf] operators: |
| 213 |
// |
| 214 |
// got := map[string][]string{"labels": {"c", "a", "b"}} |
| 215 |
// td.Cmp(t, got, td.JSON(`{ "labels": Sort(1, ["a", "b", "c"]) }`)) // succeeds |
| 216 |
// |
| 217 |
// or using fields-path feature: |
| 218 |
// |
| 219 |
// type Person struct { |
| 220 |
// Name string `json:"name"` |
| 221 |
// Age int `json:"age"` |
| 222 |
// } |
| 223 |
// got := struct { |
| 224 |
// People []Person `json:"people"` |
| 225 |
// }{ |
| 226 |
// People: []Person{ |
| 227 |
// {"Brian", 22}, |
| 228 |
// {"Bob", 19}, |
| 229 |
// {"Stephen", 19}, |
| 230 |
// {"Alice", 20}, |
| 231 |
// {"Marcel", 25}, |
| 232 |
// }, |
| 233 |
// } |
| 234 |
// td.Cmp(t, got, td.JSON(`{ |
| 235 |
// "people": Sort("name", [ // sort by name ascending |
| 236 |
// {"name": "Alice", "age": 20}, |
| 237 |
// {"name": "Bob", "age": 19}, |
| 238 |
// {"name": "Brian", "age": 22}, |
| 239 |
// {"name": "Marcel", "age": 25}, |
| 240 |
// {"name": "Stephen", "age": 19}, |
| 241 |
// ]) |
| 242 |
// }`)) // succeeds |
| 243 |
// td.Cmp(t, got, td.JSON(`{ |
| 244 |
// "people": Sort([ "-age", "name" ], [ // sort by age desc, then by name asc |
| 245 |
// {"name": "Marcel", "age": 25}, |
| 246 |
// {"name": "Brian", "age": 22}, |
| 247 |
// {"name": "Alice", "age": 20}, |
| 248 |
// {"name": "Bob", "age": 19}, |
| 249 |
// {"name": "Stephen", "age": 19}, |
| 250 |
// ]) |
| 251 |
// }`)) // succeeds |
| 252 |
// |
| 253 |
// See also [Sorted], [Smuggle] and [Bag]. |
| 254 |
func Sort(how any, expectedValue any) TestDeep { |
| 255 |
s := tdSort{how: how} |
| 256 |
s.tdSmugglerBase = newSmugglerBase(expectedValue, 0) |
| 257 |
if !s.isTestDeeper { |
| 258 |
s.expectedValue = reflect.ValueOf(expectedValue) |
| 259 |
} |
| 260 |
|
| 261 |
err := s.initSortBase(how) |
| 262 |
if err != nil { |
| 263 |
s.err = ctxerr.OpBad("Sort", "usage: Sort%s, %s", sortUsage, err) |
| 264 |
} else if !s.isTestDeeper { |
| 265 |
switch s.expectedValue.Kind() { |
| 266 |
case reflect.Slice, reflect.Array: |
| 267 |
default: |
| 268 |
s.err = ctxerr.OpBad("Sort", |
| 269 |
"usage: Sort%s, EXPECTED_VALUE must be a slice or an array not a %s", |
| 270 |
sortUsage, types.KindType(s.expectedValue)) |
| 271 |
} |
| 272 |
} |
| 273 |
return &s |
| 274 |
} |
| 275 |
|
| 276 |
func (s *tdSort) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error { |
| 277 |
if s.err != nil { |
| 278 |
return ctx.CollectError(s.err) |
| 279 |
} |
| 280 |
|
| 281 |
if rErr := grepResolvePtr(ctx, &got); rErr != nil { |
| 282 |
return ctx.CollectError(rErr) |
| 283 |
} |
| 284 |
|
| 285 |
switch got.Kind() { |
| 286 |
case reflect.Slice, reflect.Array: |
| 287 |
default: |
| 288 |
return grepBadKind(ctx, got) |
| 289 |
} |
| 290 |
|
| 291 |
const sorted = "<sorted>" |
| 292 |
|
| 293 |
itemType := got.Type().Elem() |
| 294 |
fn, err := s.mkSortFn(itemType) |
| 295 |
if err != nil { |
| 296 |
if ctx.BooleanError { |
| 297 |
return ctxerr.BooleanError |
| 298 |
} |
| 299 |
return ctx.CollectError(&ctxerr.Error{ |
| 300 |
Message: "cannot sort items", |
| 301 |
Summary: ctxerr.NewSummary(err.Error()), |
| 302 |
}) |
| 303 |
} |
| 304 |
|
| 305 |
l := got.Len() |
| 306 |
if l <= 1 { |
| 307 |
return deepValueEqual(ctx.AddCustomLevel(sorted), got, s.expectedValue) |
| 308 |
} |
| 309 |
|
| 310 |
var out reflect.Value |
| 311 |
if got.Kind() == reflect.Slice { |
| 312 |
out = reflect.MakeSlice(reflect.SliceOf(itemType), l, l) |
| 313 |
} else { |
| 314 |
out = reflect.New(got.Type()).Elem() |
| 315 |
} |
| 316 |
reflect.Copy(out, got) |
| 317 |
|
| 318 |
sort.SliceStable(out.Slice(0, out.Len()).Interface(), func(i, j int) bool { |
| 319 |
return fn.Call([]reflect.Value{out.Index(i), out.Index(j)})[0].Bool() |
| 320 |
}) |
| 321 |
return deepValueEqual(ctx.AddCustomLevel(sorted), out, s.expectedValue) |
| 322 |
} |
| 323 |
|
| 324 |
func (s *tdSort) String() string { |
| 325 |
if s.err != nil { |
| 326 |
return s.stringError() |
| 327 |
} |
| 328 |
how, typ := s.how, reflect.TypeOf(s.how) |
| 329 |
if typ != nil && typ.Kind() == reflect.Func { |
| 330 |
how = typ.String() |
| 331 |
} |
| 332 |
return S("Sort(%v, %s)", how, util.ToString(s.expectedValue)) |
| 333 |
} |
| 334 |
|
| 335 |
type tdSorted struct { |
| 336 |
baseOKNil |
| 337 |
tdSortBase |
| 338 |
how []any |
| 339 |
} |
| 340 |
|
| 341 |
var _ TestDeep = &tdSorted{} |
| 342 |
|
| 343 |
const sortedUsage = "(SORT_FUNC|int|[]string|string...)" |
| 344 |
|
| 345 |
// summary(Sorted): checks a slice or an array is sorted |
| 346 |
// input(Sorted): array,slice,ptr(ptr on array/slice) |
| 347 |
|
| 348 |
// Sorted operator checks that data is an array, a slice or a pointer |
| 349 |
// on array/slice, and it is well sorted as how tells it should be. |
| 350 |
// |
| 351 |
// how... can be: |
| 352 |
// - empty to check a generic ascending order; |
| 353 |
// - nil or a float64/int >= 0 to check a generic ascending order; |
| 354 |
// - a float64/int < 0 to check a generic descending order; |
| 355 |
// - strings specifying fields-paths (each optionally prefixed by "+" |
| 356 |
// or "-" for respectively checking an ascending or a descending order, |
| 357 |
// defaulting to ascending one); |
| 358 |
// - a function matching func(a, b T) bool signature and returning |
| 359 |
// true if a is before b. |
| 360 |
// |
| 361 |
// A fields-path, also used by [Smuggle] and [Sort] operators, |
| 362 |
// allows to access nested structs fields and maps & slices items. See |
| 363 |
// [Smuggle] for details on fields-path possibilities. |
| 364 |
// |
| 365 |
// type A struct{ props map[string]int } |
| 366 |
// p12 := A{props: map[string]int{"priority": 12}} |
| 367 |
// p23 := A{props: map[string]int{"priority": 23}} |
| 368 |
// p34 := A{props: map[string]int{"priority": 34}} |
| 369 |
// got := []A{p34, p23, p12} |
| 370 |
// td.Cmp(t, got, td.Sorted("-props[priority]")) // succeeds |
| 371 |
// |
| 372 |
// how can be a float64 to allow Sort to be used in expected JSON of |
| 373 |
// [JSON], [SubJSONOf] & [SuperJSONOf] operators: |
| 374 |
// |
| 375 |
// got := map[string][]string{"labels": {"a", "b", "c"}} |
| 376 |
// td.Cmp(t, got, td.JSON(`{ "labels": Sorted }`)) // succeeds |
| 377 |
// |
| 378 |
// or using fields-path feature: |
| 379 |
// |
| 380 |
// type Person struct { |
| 381 |
// Name string `json:"name"` |
| 382 |
// Age int `json:"age"` |
| 383 |
// } |
| 384 |
// got := struct { |
| 385 |
// People []Person `json:"people"` |
| 386 |
// }{ |
| 387 |
// People: []Person{ |
| 388 |
// {"Marcel", 25}, |
| 389 |
// {"Brian", 22}, |
| 390 |
// {"Alice", 20}, |
| 391 |
// {"Bob", 19}, |
| 392 |
// {"Stephen", 19}, |
| 393 |
// }, |
| 394 |
// } |
| 395 |
// // sorted by age desc, then by name asc |
| 396 |
// td.Cmp(t, got, td.JSON(`{ "people": Sorted("-age", "name") }`)) // succeeds |
| 397 |
// |
| 398 |
// See also [Sort]. |
| 399 |
func Sorted(how ...any) TestDeep { |
| 400 |
s := tdSorted{ |
| 401 |
baseOKNil: newBaseOKNil(3), |
| 402 |
how: how, |
| 403 |
} |
| 404 |
|
| 405 |
err := s.initSortBase(how...) |
| 406 |
if err != nil { |
| 407 |
s.err = ctxerr.OpBad("Sorted", "usage: Sorted%s, %s", sortedUsage, err) |
| 408 |
} |
| 409 |
return &s |
| 410 |
} |
| 411 |
|
| 412 |
func (s *tdSorted) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error { |
| 413 |
if s.err != nil { |
| 414 |
return ctx.CollectError(s.err) |
| 415 |
} |
| 416 |
|
| 417 |
if rErr := grepResolvePtr(ctx, &got); rErr != nil { |
| 418 |
return ctx.CollectError(rErr) |
| 419 |
} |
| 420 |
|
| 421 |
switch got.Kind() { |
| 422 |
case reflect.Slice, reflect.Array: |
| 423 |
default: |
| 424 |
return grepBadKind(ctx, got) |
| 425 |
} |
| 426 |
|
| 427 |
itemType := got.Type().Elem() |
| 428 |
fn, err := s.mkSortFn(itemType) |
| 429 |
if err != nil { |
| 430 |
if ctx.BooleanError { |
| 431 |
return ctxerr.BooleanError |
| 432 |
} |
| 433 |
return ctx.CollectError(&ctxerr.Error{ |
| 434 |
Message: "cannot sort items", |
| 435 |
Summary: ctxerr.NewSummary(err.Error()), |
| 436 |
}) |
| 437 |
} |
| 438 |
|
| 439 |
for i, l := 1, got.Len(); i < l; i++ { |
| 440 |
if fn.Call([]reflect.Value{got.Index(i), got.Index(i - 1)})[0].Bool() { |
| 441 |
return ctx.CollectError(&ctxerr.Error{ |
| 442 |
Message: fmt.Sprintf("not sorted, item #%d value is before #%d one while it should not", i, i-1), |
| 443 |
Summary: ctxerr.ErrorSummaryItems{ |
| 444 |
{ |
| 445 |
Label: fmt.Sprintf("item #%d", i-1), |
| 446 |
Value: util.ToString(got.Index(i - 1)), |
| 447 |
}, |
| 448 |
{ |
| 449 |
Label: fmt.Sprintf("item #%d", i), |
| 450 |
Value: util.ToString(got.Index(i)), |
| 451 |
}, |
| 452 |
}, |
| 453 |
}) |
| 454 |
} |
| 455 |
} |
| 456 |
|
| 457 |
return nil |
| 458 |
} |
| 459 |
|
| 460 |
func (s *tdSorted) String() string { |
| 461 |
if s.err != nil { |
| 462 |
return s.stringError() |
| 463 |
} |
| 464 |
var b strings.Builder |
| 465 |
b.WriteString("Sorted(") |
| 466 |
for i, cur := range s.how { |
| 467 |
how, typ := cur, reflect.TypeOf(cur) |
| 468 |
if typ != nil && typ.Kind() == reflect.Func { |
| 469 |
how = typ.String() |
| 470 |
} |
| 471 |
if i > 0 { |
| 472 |
b.WriteString(", ") |
| 473 |
} |
| 474 |
fmt.Fprintf(&b, "%v", how) |
| 475 |
} |
| 476 |
b.WriteByte(')') |
| 477 |
return b.String() |
| 478 |
} |