Debian Codegraph @

td/td_sort_test.go

raw
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_test
8
9 import (
10 "encoding/json"
11 "fmt"
12 "reflect"
13 "testing"
14
15 "github.com/maxatome/go-testdeep/internal/test"
16 "github.com/maxatome/go-testdeep/td"
17 )
18
19 func TestSort(t *testing.T) {
20 type sortTest1 struct {
21 s string
22 a int
23 b int
24 }
25 type sortTest2 struct{ a, b, c int }
26 testCases := []struct {
27 name string
28 how any
29 got any
30 expected any
31 expectedErr expectedError
32 }{
33 {
34 name: "slice",
35 how: 1,
36 got: []int{1, -2, -3, 0, -1, 3, 2},
37 expected: []int{-3, -2, -1, 0, 1, 2, 3},
38 },
39 {
40 name: "*slice",
41 how: 1,
42 got: &[]int{1, -2, -3, 0, -1, 3, 2},
43 expected: []int{-3, -2, -1, 0, 1, 2, 3},
44 },
45 {
46 name: "array",
47 how: 1,
48 got: [...]int{1, -2, -3, 0, -1, 3, 2},
49 expected: [...]int{-3, -2, -1, 0, 1, 2, 3},
50 },
51 {
52 name: "*array",
53 how: 1,
54 got: &[...]int{1, -2, -3, 0, -1, 3, 2},
55 expected: [...]int{-3, -2, -1, 0, 1, 2, 3},
56 },
57 {
58 name: "asc0",
59 how: 0,
60 got: []int{1, -2, -3, 0, -1, 3, 2},
61 expected: []int{-3, -2, -1, 0, 1, 2, 3},
62 },
63 {
64 name: "desc",
65 how: -1,
66 got: []int{1, -2, -3, 0, -1, 3, 2},
67 expected: []int{3, 2, 1, 0, -1, -2, -3},
68 },
69 {
70 name: "asc float",
71 how: 42.3,
72 got: []int{1, -2, -3, 0, -1, 3, 2},
73 expected: []int{-3, -2, -1, 0, 1, 2, 3},
74 },
75 {
76 name: "no items",
77 how: 1,
78 got: []int{},
79 expected: []int{},
80 },
81 {
82 name: "one item",
83 how: 1,
84 got: []int{23},
85 expected: []int{23},
86 },
87 {
88 name: "func",
89 how: func(a, b int) bool {
90 if a == 0 || b == 0 {
91 return b == 0
92 }
93 return a > b
94 },
95 got: []int{1, -2, -3, 0, -1, 3, 2},
96 expected: []int{3, 2, 1, -1, -2, -3, 0},
97 },
98 {
99 name: "evenHigher",
100 how: func(a, b int) bool {
101 if (a%2 == 0) != (b%2 == 0) {
102 return a%2 != 0
103 }
104 return a < b
105 },
106 got: []int{-1, 1, 2, -3, 3, -2, 0},
107 expected: []int{-3, -1, 1, 3, -2, 0, 2},
108 },
109 {
110 name: "fields-path",
111 how: "s",
112 got: []sortTest1{{"c", 4, 2}, {"a", 8, 1}, {"b", 0, 3}},
113 expected: []sortTest1{{"a", 8, 1}, {"b", 0, 3}, {"c", 4, 2}},
114 },
115 {
116 name: "multiple fields-paths",
117 how: []string{"a", "-b", "c"},
118 got: []sortTest2{{1, 9, 5}, {2, 0, 0}, {1, 9, 4}, {1, 8, 0}},
119 expected: []sortTest2{{1, 9, 4}, {1, 9, 5}, {1, 8, 0}, {2, 0, 0}},
120 },
121 {
122 name: "invalid fields-path",
123 how: "",
124 got: []int{1, 2},
125 expected: []int{42, 42},
126 expectedErr: expectedError{
127 Message: mustBe("cannot sort items"),
128 Path: mustBe("DATA"),
129 Summary: mustBe("FIELDS_PATH cannot be empty"),
130 Under: mustContain("under operator Sort at "),
131 },
132 },
133 {
134 name: "bad usage",
135 how: 1,
136 got: []int{1, 2},
137 expected: 42,
138 expectedErr: expectedError{
139 Message: mustBe("bad usage of Sort operator"),
140 Path: mustBe("DATA"),
141 Summary: mustBe("usage: Sort(SORT_FUNC|int|string|[]string, TESTDEEP_OPERATOR|EXPECTED_VALUE), EXPECTED_VALUE must be a slice or an array not a int"),
142 Under: mustContain("under operator Sort at "),
143 },
144 },
145 {
146 name: "grepResolvePtr error",
147 got: (*int)(nil),
148 expected: td.Ignore(),
149 expectedErr: expectedError{
150 Message: mustBe("nil pointer"),
151 Got: mustBe("nil *int"),
152 Expected: mustBe("non-nil *slice OR *array"),
153 Under: mustContain("under operator Sort at "),
154 },
155 },
156 {
157 name: "grepBadKind",
158 got: 123,
159 expected: td.Ignore(),
160 expectedErr: expectedError{
161 Message: mustBe("bad kind"),
162 Got: mustBe("int"),
163 Expected: mustBe("slice OR array OR *slice OR *array"),
164 Under: mustContain("under operator Sort at "),
165 },
166 },
167 {
168 name: "erroneous operator expected",
169 how: 1,
170 got: []int{1, 2},
171 expected: td.JSON("{"),
172 expectedErr: expectedError{
173 Message: mustBe("bad usage of JSON operator"),
174 Path: mustMatch(`DATA<sorted>`), // always without .Iface
175 Summary: mustContain("JSON unmarshal error"),
176 Under: mustContain("under operator JSON at "),
177 },
178 },
179 }
180 for _, tc := range testCases {
181 t.Run(tc.name, func(t *testing.T) {
182 if tc.expectedErr == (expectedError{}) {
183 checkOK(t, tc.got, td.Sort(tc.how, tc.expected))
184 } else {
185 checkError(t, tc.got, td.Sort(tc.how, tc.expected), tc.expectedErr)
186 }
187 })
188 }
189
190 t.Run("JSON", func(t *testing.T) {
191 checkOK(t,
192 json.RawMessage(`["c","a","b"]`),
193 td.JSON(`Sort(1, ["a","b","c"])`))
194
195 checkOK(t,
196 json.RawMessage(`{"x": ["c","a","b"]}`),
197 td.JSON(`{"x": Sort(-1, ["c","b","a"])}`))
198
199 checkOK(t,
200 map[string][]string{"labels": {"c", "a", "b"}},
201 td.JSON(`{"labels": Sort(1, ["a", "b", "c"])}`))
202
203 type Person struct {
204 Name string `json:"name"`
205 Age int `json:"age"`
206 }
207 got := struct {
208 People []Person `json:"people"`
209 }{
210 People: []Person{
211 {"Brian", 22},
212 {"Bob", 19},
213 {"Stephen", 19},
214 {"Alice", 20},
215 {"Marcel", 25},
216 },
217 }
218 checkOK(t, got, td.JSON(`{
219 "people": Sort("name", [ // sort by name ascending
220 {"name": "Alice", "age": 20},
221 {"name": "Bob", "age": 19},
222 {"name": "Brian", "age": 22},
223 {"name": "Marcel", "age": 25},
224 {"name": "Stephen", "age": 19},
225 ])
226 }`))
227 checkOK(t, got, td.JSON(`{
228 "people": Sort([ "-age", "name" ], [ // sort by age desc, then by name asc
229 {"name": "Marcel", "age": 25},
230 {"name": "Brian", "age": 22},
231 {"name": "Alice", "age": 20},
232 {"name": "Bob", "age": 19},
233 {"name": "Stephen", "age": 19},
234 ])
235 }`))
236 })
237 }
238
239 func TestSortTypeBehind(t *testing.T) {
240 equalTypes(t, td.Sort(1, []int{}), nil)
241
242 // Erroneous op
243 equalTypes(t, td.Sort(func() {}, []int{}), nil)
244 }
245
246 func TestSortString(t *testing.T) {
247 test.EqualStr(t, td.Sort(nil, []int{}).String(), "Sort(<nil>, ([]int) {\n})")
248
249 test.EqualStr(t, td.Sort(1, []int{}).String(), "Sort(1, ([]int) {\n})")
250
251 test.EqualStr(t,
252 td.Sort(func(a, b int) bool { return true }, []int{}).String(),
253 "Sort(func(int, int) bool, ([]int) {\n})")
254
255 // Erroneous op
256 test.EqualStr(t, td.Sort(func() {}, []int{}).String(), "Sort(<ERROR>)")
257 }
258
259 // nolint: unused
260 func TestSorted(t *testing.T) {
261 firstBecomesLast := func(x any) (any, int) {
262 vx := reflect.ValueOf(x)
263 if vx.Kind() == reflect.Ptr {
264 vx = vx.Elem()
265 }
266 l := vx.Len()
267 if l <= 1 {
268 return nil, 0
269 }
270 if vx.Kind() == reflect.Array {
271 vx2 := reflect.New(vx.Type()).Elem()
272 reflect.Copy(vx2, vx)
273 vx = vx2
274 }
275 first := vx.Index(0).Interface()
276 reflect.Copy(vx, vx.Slice(1, l))
277 vx.Index(l - 1).Set(reflect.ValueOf(first))
278 return vx.Interface(), l
279 }
280
281 type nested3 struct {
282 val int
283 dummy int
284 }
285 type nested2 struct {
286 val int
287 n3 *nested3
288 }
289 type nested1 struct {
290 val int
291 n2 nested2
292 }
293 testCases := []struct {
294 name string
295 got any
296 sorted []any
297 expectedErr expectedError
298 }{
299 {
300 name: "slice",
301 got: []int{0, 1, 2, 2},
302 },
303 {
304 name: "*slice",
305 got: &[]int{0, 1, 2, 2},
306 },
307 {
308 name: "array",
309 got: [...]int{0, 1, 2, 2},
310 },
311 {
312 name: "*array",
313 got: ptr([...]int{0, 1, 2, 2}),
314 },
315 {
316 name: "asc",
317 got: []int{0, 1, 2, 2},
318 sorted: []any{1},
319 },
320 {
321 name: "asc",
322 got: []int{4, 3, 2, 2},
323 sorted: []any{-1},
324 },
325 {
326 name: "flatten struct field",
327 got: []struct{ name string }{{"a"}, {"b"}, {"c"}, {"c"}},
328 sorted: []any{"name"},
329 },
330 {
331 name: "struct field in slice",
332 got: []struct{ name string }{{"a"}, {"b"}, {"c"}, {"c"}},
333 sorted: []any{[]string{"name"}},
334 },
335 {
336 name: "flatten struct field desc",
337 got: []struct{ name string }{{"d"}, {"c"}, {"b"}, {"b"}},
338 sorted: []any{"-name"},
339 },
340 {
341 name: "flatten multiple struct fields",
342 got: []struct{ a, b, c int }{{1, 9, 4}, {1, 9, 5}, {1, 8, 0}, {2, 0, 0}},
343 sorted: []any{"a", "-b", "c"},
344 },
345 {
346 name: "nested fields-path",
347 got: []*nested1{
348 {1, nested2{1, &nested3{1, 8}}},
349 {1, nested2{1, &nested3{2, 7}}},
350 {1, nested2{2, &nested3{2, 6}}},
351 {2, nested2{2, &nested3{2, 5}}},
352 },
353 sorted: []any{"n2.n3.val", "n2.val", "val"},
354 },
355 {
356 name: "invalid fields-path",
357 got: []int{1, 2},
358 sorted: []any{""},
359 expectedErr: expectedError{
360 Message: mustBe("cannot sort items"),
361 Path: mustBe("DATA"),
362 Summary: mustBe("FIELDS_PATH cannot be empty"),
363 Under: mustContain("under operator Sorted at "),
364 },
365 },
366 {
367 name: "bad usage",
368 got: []int{1, 2},
369 sorted: []any{42, 23},
370 expectedErr: expectedError{
371 Message: mustBe("bad usage of Sorted operator"),
372 Path: mustBe("DATA"),
373 Summary: mustBe("usage: Sorted(SORT_FUNC|int|[]string|string...), string... expected but received int as 1st parameter"),
374 Under: mustContain("under operator Sorted at "),
375 },
376 },
377 {
378 name: "grepResolvePtr error",
379 got: (*int)(nil),
380 sorted: []any{1},
381 expectedErr: expectedError{
382 Message: mustBe("nil pointer"),
383 Got: mustBe("nil *int"),
384 Expected: mustBe("non-nil *slice OR *array"),
385 Under: mustContain("under operator Sorted at "),
386 },
387 },
388 {
389 name: "grepBadKind",
390 got: 123,
391 sorted: []any{1},
392 expectedErr: expectedError{
393 Message: mustBe("bad kind"),
394 Got: mustBe("int"),
395 Expected: mustBe("slice OR array OR *slice OR *array"),
396 Under: mustContain("under operator Sorted at "),
397 },
398 },
399 }
400 for _, tc := range testCases {
401 t.Run(tc.name, func(t *testing.T) {
402 if tc.expectedErr == (expectedError{}) {
403 checkOK(t, tc.got, td.Sorted(tc.sorted...))
404
405 // expect an error after moving first item at last position
406 if got, l := firstBecomesLast(tc.got); got != nil {
407 checkError(t, got, td.Sorted(tc.sorted...),
408 expectedError{
409 Message: mustBe(
410 fmt.Sprintf("not sorted, item #%d value is before #%d one while it should not",
411 l-1, l-2)),
412 Path: mustBe("DATA"),
413 Summary: mustMatch(
414 fmt.Sprintf(`(?s)^item #%d: .+\nitem #%d: `, l-2, l-1)),
415 })
416 }
417 return
418 }
419
420 checkError(t, tc.got, td.Sorted(tc.sorted...), tc.expectedErr)
421 })
422 }
423
424 t.Run("JSON", func(t *testing.T) {
425 checkOK(t,
426 json.RawMessage(`["a","b","c"]`),
427 td.JSON(`Sorted`))
428
429 checkOK(t,
430 json.RawMessage(`{"x": ["c","b","a"]}`),
431 td.JSON(`{ "x": Sorted(-1) }`))
432
433 checkOK(t,
434 map[string][]string{"labels": {"a", "b", "c"}},
435 td.JSON(`{ "labels": Sorted }`))
436
437 type Person struct {
438 Name string `json:"name"`
439 Age int `json:"age"`
440 }
441 got := struct {
442 People []Person `json:"people"`
443 }{
444 People: []Person{
445 {"Alice", 20},
446 {"Bob", 19},
447 {"Brian", 22},
448 {"Marcel", 25},
449 {"Stephen", 19},
450 },
451 }
452 // is sorted by name ascending
453 checkOK(t, got, td.JSON(`{ "people": Sorted("name") }`))
454
455 // is sorted by age desc, then by name asc
456 checkError(t, got, td.JSON(`{ "people": Sorted("-age", "name") }`),
457 expectedError{
458 Message: mustBe("not sorted, item #2 value is before #1 one while it should not"),
459 Path: mustBe(`DATA["people"]`),
460 Summary: mustMatch(`(?s)^item #1: .+"Bob".*\nitem #2: .+"Brian"`),
461 Under: mustContain("under operator Sorted at "),
462 })
463 })
464 }
465
466 func TestSortedTypeBehind(t *testing.T) {
467 equalTypes(t, td.Sorted(), nil)
468 equalTypes(t, td.Sorted(-1), nil)
469
470 // Erroneous op
471 equalTypes(t, td.Sorted(func() {}), nil)
472 }
473
474 func TestSortedString(t *testing.T) {
475 test.EqualStr(t, td.Sorted(nil).String(), "Sorted(<nil>)")
476 test.EqualStr(t, td.Sorted(1).String(), "Sorted(1)")
477 test.EqualStr(t, td.Sorted("a.b", "-d.e").String(), `Sorted(a.b, -d.e)`)
478
479 test.EqualStr(t,
480 td.Sorted(func(a, b int) bool { return true }).String(),
481 "Sorted(func(int, int) bool)")
482
483 // Erroneous op
484 test.EqualStr(t, td.Sorted(func() {}).String(), "Sorted(<ERROR>)")
485 }