-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index_test.go
102 lines (97 loc) · 1.76 KB
/
index_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package query
import (
"reflect"
"testing"
"github.com/google/go-cmp/cmp"
)
type indexExtractor struct {
v interface{}
}
func (f *indexExtractor) ExtractByIndex(_ int) (interface{}, bool) {
if f.v != nil {
return f.v, true
}
return nil, false
}
func TestIndex_Extract(t *testing.T) {
t.Run("found", func(t *testing.T) {
tests := map[string]struct {
index int
v interface{}
expect interface{}
}{
"slice": {
index: 0,
v: []int{
0, 1, 2,
},
expect: 0,
},
"array": {
index: 1,
v: [3]int{
0, 1, 2,
},
expect: 1,
},
"array pointer": {
index: 2,
v: &[3]int{
0, 1, 2,
},
expect: 2,
},
"index extractor": {
index: 10,
v: &indexExtractor{v: "value"},
expect: "value",
},
}
for name, test := range tests {
test := test
t.Run(name, func(t *testing.T) {
e := &Index{index: test.index}
v, ok := e.Extract(reflect.ValueOf(test.v))
if !ok {
t.Fatal("not found")
}
if diff := cmp.Diff(test.expect, v.Interface()); diff != "" {
t.Errorf("differs: (-want +got)\n%s", diff)
}
})
}
})
t.Run("not found", func(t *testing.T) {
tests := map[string]struct {
index int
v interface{}
}{
"target is nil": {
index: 0,
v: nil,
},
"slice has not index": {
index: 0,
v: []int{},
},
"array has not index": {
index: 1,
v: [1]int{0},
},
"index extractor returns false": {
index: 10,
v: &indexExtractor{},
},
}
for name, test := range tests {
test := test
t.Run(name, func(t *testing.T) {
e := &Index{index: test.index}
v, ok := e.Extract(reflect.ValueOf(test.v))
if ok {
t.Fatalf("unexpected value: %#v", v)
}
})
}
})
}