forked from ipfs/go-ipfs-cmds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaybeerror_test.go
110 lines (95 loc) · 2.53 KB
/
maybeerror_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
103
104
105
106
107
108
109
110
package cmds
import (
"encoding/json"
"io"
"reflect"
"strings"
"testing"
"github.com/ipfs/go-ipfs-cmdkit"
)
type Foo struct {
Bar int
}
type Bar struct {
Foo string
}
type ValueError struct {
Error error
Value interface{}
}
type anyTestCase struct {
Value interface{}
JSON string
Decoded []ValueError
}
func TestMaybeError(t *testing.T) {
testcases := []anyTestCase{
{
Value: &Foo{},
JSON: `{"Bar":23}{"Bar":42}{"Message":"some error", "Type": "error"}`,
Decoded: []ValueError{
ValueError{Error: nil, Value: &Foo{23}},
ValueError{Error: nil, Value: &Foo{42}},
ValueError{Error: nil, Value: cmdkit.Error{Message: "some error", Code: 0}},
},
},
{
Value: Foo{},
JSON: `{"Bar":23}{"Bar":42}{"Message":"some error", "Type": "error"}`,
Decoded: []ValueError{
ValueError{Error: nil, Value: &Foo{23}},
ValueError{Error: nil, Value: &Foo{42}},
ValueError{Error: nil, Value: cmdkit.Error{Message: "some error", Code: 0}},
},
},
{
Value: &Bar{},
JSON: `{"Foo":""}{"Foo":"Qmabc"}{"Message":"some error", "Type": "error"}`,
Decoded: []ValueError{
ValueError{Error: nil, Value: &Bar{""}},
ValueError{Error: nil, Value: &Bar{"Qmabc"}},
ValueError{Error: nil, Value: cmdkit.Error{Message: "some error", Code: 0}},
},
},
{
Value: Bar{},
JSON: `{"Foo":""}{"Foo":"Qmabc"}{"Message":"some error", "Type": "error"}`,
Decoded: []ValueError{
ValueError{Error: nil, Value: &Bar{""}},
ValueError{Error: nil, Value: &Bar{"Qmabc"}},
ValueError{Error: nil, Value: cmdkit.Error{Message: "some error", Code: 0}},
},
},
{
JSON: `{"Foo":"bar", "i": 4}"some string"5{"Message":"some error", "Type": "error"}`,
Decoded: []ValueError{
ValueError{Error: nil, Value: map[string]interface{}{"Foo": "bar", "i": 4.0}},
ValueError{Error: nil, Value: "some string"},
ValueError{Error: nil, Value: 5.0},
ValueError{Error: nil, Value: cmdkit.Error{Message: "some error", Code: 0}},
},
},
}
for _, tc := range testcases {
r := strings.NewReader(tc.JSON)
d := json.NewDecoder(r)
var err error
for _, dec := range tc.Decoded {
m := &MaybeError{Value: tc.Value}
err = d.Decode(m)
if err != dec.Error {
t.Fatalf("error is %v, expected %v", err, dec.Error)
}
rx := m.Get()
ex := dec.Value
if !reflect.DeepEqual(ex, rx) {
t.Errorf("value is %#v(%T), expected %#v(%T)", rx, rx, ex, ex)
}
}
m := &MaybeError{Value: tc.Value}
err = d.Decode(m)
if err != io.EOF {
t.Fatal("data left in decoder:", m.Get())
}
}
}