Debian Codegraph @

internal/anchors/types_test.go

raw
1 // Copyright (c) 2020-2022, 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 anchors_test
8
9 import (
10 "strings"
11 "testing"
12
13 "github.com/maxatome/go-testdeep/internal/anchors"
14 )
15
16 func TestAddAnchorableStructType(t *testing.T) {
17 oldAnchorableTypes := anchors.AnchorableTypes
18 defer func() { anchors.AnchorableTypes = oldAnchorableTypes }()
19
20 type ok struct{ index int }
21 type notComparable struct{ s []int } //nolint: unused
22
23 // Usage error cases
24 for i, fn := range []any{
25 12,
26 func(x ...int) {},
27 func(x, y int) {},
28 func(x int) (int, int) { return 0, 0 },
29 func(x byte) int { return 0 },
30 func(x int) int { return 0 },
31 } {
32 err := anchors.AddAnchorableStructType(fn)
33 if err == nil {
34 t.Fatalf("#%d function should return an error", i)
35 }
36 if !strings.HasPrefix(err.Error(), "usage: ") {
37 t.Errorf("#%d function returned: `%s` instead of usage", i, err)
38 }
39 }
40
41 // Not comparable struct
42 err := anchors.AddAnchorableStructType(func(nextAnchor int) notComparable {
43 return notComparable{}
44 })
45 if err == nil {
46 t.Fatal("function should return an error")
47 }
48 if err.Error() != "type anchors_test.notComparable is not comparable, it cannot be anchorable" {
49 t.Errorf("function returned: `%s` instead of not comparable error", err)
50 }
51
52 // Comparable struct => OK
53 err = anchors.AddAnchorableStructType(func(nextAnchor int) ok {
54 return ok{index: 1000 + nextAnchor}
55 })
56 if err != nil {
57 t.Fatalf("AddAnchorableStructType failed: %s", err)
58 }
59 if len(anchors.AnchorableTypes) != 2 {
60 t.Fatalf("Bad number of anchored type: got=%d expected=2",
61 len(anchors.AnchorableTypes))
62 }
63 }