| 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 sort_test |
| 8 |
|
| 9 |
import ( |
| 10 |
"reflect" |
| 11 |
"sort" |
| 12 |
"testing" |
| 13 |
|
| 14 |
tdsort "github.com/maxatome/go-testdeep/internal/sort" |
| 15 |
) |
| 16 |
|
| 17 |
func TestMapEach(t *testing.T) { |
| 18 |
m := map[string]int{"a": 1, "b": 2, "c": 3} |
| 19 |
|
| 20 |
t.Run("full", func(t *testing.T) { |
| 21 |
type kv struct { |
| 22 |
key string |
| 23 |
value int |
| 24 |
} |
| 25 |
var s []kv |
| 26 |
ok := tdsort.MapEach(reflect.ValueOf(m), func(k, v reflect.Value) bool { |
| 27 |
s = append(s, kv{ |
| 28 |
key: k.Interface().(string), |
| 29 |
value: v.Interface().(int), |
| 30 |
}) |
| 31 |
return true |
| 32 |
}) |
| 33 |
if !ok { |
| 34 |
t.Error("MapEach returned false") |
| 35 |
} |
| 36 |
|
| 37 |
sort.Slice(s, func(i, j int) bool { return s[i].key < s[j].key }) |
| 38 |
|
| 39 |
if len(s) != 3 || |
| 40 |
s[0] != (kv{key: "a", value: 1}) || |
| 41 |
s[1] != (kv{key: "b", value: 2}) || |
| 42 |
s[2] != (kv{key: "c", value: 3}) { |
| 43 |
t.Errorf("MapEach failed: %v", s) |
| 44 |
} |
| 45 |
}) |
| 46 |
|
| 47 |
t.Run("short circuit", func(t *testing.T) { |
| 48 |
called := 0 |
| 49 |
ok := tdsort.MapEach(reflect.ValueOf(m), func(k, v reflect.Value) bool { |
| 50 |
called++ |
| 51 |
return false |
| 52 |
}) |
| 53 |
if ok { |
| 54 |
t.Error("MapEach returned true") |
| 55 |
} |
| 56 |
if called != 1 { |
| 57 |
t.Errorf("MapEach callback called %d times instead of 1", called) |
| 58 |
} |
| 59 |
}) |
| 60 |
} |