-
Notifications
You must be signed in to change notification settings - Fork 27
/
response_test.go
323 lines (300 loc) · 9.95 KB
/
response_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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
package ofxgo
import (
"bytes"
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"testing"
"github.com/aclindsa/xml"
)
// Attempt to find a method on the provided Value called 'Equal' which is a
// receiver for the Value, takes one argument of the same type, and returns
// one bool. equalMethodOf() returns the nil value if the method couldn't be
// found.
func equalMethodOf(v reflect.Value) reflect.Value {
if equalMethod, ok := v.Type().MethodByName("Equal"); ok {
if !equalMethod.Func.IsNil() &&
equalMethod.Type.NumIn() == 2 &&
equalMethod.Type.In(0) == v.Type() &&
equalMethod.Type.In(1) == v.Type() &&
equalMethod.Type.NumOut() == 1 &&
equalMethod.Type.Out(0).Kind() == reflect.Bool {
return v.MethodByName("Equal")
}
}
return reflect.ValueOf(nil)
}
// Attempt to return a string representation of the value appropriate for its
// type by finding a method on the provided Value called 'String' which is a
// receiver for the Value, and returns one string. stringMethodOf() returns
// fmt.Sprintf("%s", v) if it can't find a String method.
func valueToString(v reflect.Value) string {
if equalMethod, ok := v.Type().MethodByName("String"); ok {
if !equalMethod.Func.IsNil() &&
equalMethod.Type.NumIn() == 1 &&
equalMethod.Type.In(0) == v.Type() &&
equalMethod.Type.NumOut() == 1 &&
equalMethod.Type.Out(0).Kind() == reflect.String {
out := v.MethodByName("String").Call([]reflect.Value{})
return out[0].String()
}
}
return fmt.Sprintf("%s", v)
}
// Recursively check that the expected and actual Values are equal in value.
// If the two Values are equal in type and contain an appropriate Equal()
// method (see equalMethodOf()), that method is used for comparison. The
// provided testing.T is failed with a message if any inequality is found.
func checkEqual(t *testing.T, fieldName string, expected, actual reflect.Value) {
if expected.IsValid() && !actual.IsValid() {
t.Fatalf("%s: %s was unexpectedly nil\n", t.Name(), fieldName)
} else if !expected.IsValid() && actual.IsValid() {
t.Fatalf("%s: Expected %s to be nil (it wasn't)\n", t.Name(), fieldName)
} else if !expected.IsValid() && !actual.IsValid() {
return
}
if expected.Type() != actual.Type() {
t.Fatalf("%s: Expected %s type for %s, found %s\n", t.Name(), expected.Type(), fieldName, actual.Type())
}
equalMethod := equalMethodOf(expected)
if equalMethod.IsValid() {
in := []reflect.Value{actual}
out := equalMethod.Call(in)
if !out[0].Bool() {
t.Fatalf("%s: %s !Equal(): expected '%s', got '%s'\n", t.Name(), fieldName, valueToString(expected), valueToString(actual))
}
return
}
switch expected.Kind() {
case reflect.Array:
for i := 0; i < expected.Len(); i++ {
checkEqual(t, fmt.Sprintf("%s[%d]", fieldName, i), expected.Index(i), actual.Index(i))
}
case reflect.Slice:
if !expected.IsNil() && actual.IsNil() {
t.Fatalf("%s: %s was unexpectedly nil\n", t.Name(), fieldName)
} else if expected.IsNil() && !actual.IsNil() {
t.Fatalf("%s: Expected %s to be nil (it wasn't)\n", t.Name(), fieldName)
}
if expected.Len() != actual.Len() {
t.Fatalf("%s: Expected len(%s) to to be %d, was %d\n", t.Name(), fieldName, expected.Len(), actual.Len())
}
for i := 0; i < expected.Len(); i++ {
checkEqual(t, fmt.Sprintf("%s[%d]", fieldName, i), expected.Index(i), actual.Index(i))
}
case reflect.Interface:
if !expected.IsNil() && actual.IsNil() {
t.Fatalf("%s: %s was unexpectedly nil\n", t.Name(), fieldName)
} else if expected.IsNil() && !actual.IsNil() {
t.Fatalf("%s: Expected %s to be nil (it wasn't)\n", t.Name(), fieldName)
}
checkEqual(t, fieldName, expected.Elem(), actual.Elem())
case reflect.Ptr:
checkEqual(t, fieldName, expected.Elem(), actual.Elem())
case reflect.Struct:
structType := expected.Type()
for i, n := 0, expected.NumField(); i < n; i++ {
field := structType.Field(i)
// skip XMLName fields so we can be lazy and not fill them out in
// testing code
var xmlname xml.Name
if field.Name == "XMLName" && field.Type == reflect.TypeOf(xmlname) {
continue
}
// Construct a new field name for this field, containing the parent
// fieldName
newFieldName := fieldName
if fieldName != "" {
newFieldName = fieldName + "."
}
newFieldName = newFieldName + field.Name
checkEqual(t, newFieldName, expected.Field(i), actual.Field(i))
}
case reflect.String:
if expected.String() != actual.String() {
t.Fatalf("%s: %s expected to be '%s', found '%s'\n", t.Name(), fieldName, expected.String(), actual.String())
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if expected.Uint() != actual.Uint() {
t.Fatalf("%s: %s expected to be '%s', found '%s'\n", t.Name(), fieldName, valueToString(expected), valueToString(actual))
}
default:
t.Fatalf("%s: %s has unexpected type that didn't provide an Equal() method: %s\n", t.Name(), fieldName, expected.Type().Name())
}
}
func checkResponsesEqual(t *testing.T, expected, actual *Response) {
checkEqual(t, "", reflect.ValueOf(expected), reflect.ValueOf(actual))
}
func checkResponseRoundTrip(t *testing.T, response *Response) {
b, err := response.Marshal()
if err != nil {
t.Fatalf("Unexpected error re-marshaling OFX response: %s\n", err)
}
roundtripped, err := ParseResponse(b)
if err != nil {
t.Fatalf("Unexpected error re-parsing OFX response: %s\n", err)
}
checkResponsesEqual(t, response, roundtripped)
}
// Ensure that these samples both parse without errors, and can be converted
// back and forth without changing.
func TestValidSamples(t *testing.T) {
fn := func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
} else if ext := filepath.Ext(path); ext != ".ofx" && ext != ".qfx" {
return nil
}
file, err := os.Open(path)
if err != nil {
t.Fatalf("Unexpected error opening %s: %s\n", path, err)
}
response, err := ParseResponse(file)
if err != nil {
t.Fatalf("Unexpected error parsing OFX response in %s: %s\n", path, err)
}
checkResponseRoundTrip(t, response)
return nil
}
filepath.Walk("samples/valid_responses", fn)
filepath.Walk("samples/busted_responses", fn)
}
func TestInvalidResponse(t *testing.T) {
// in this example, the severity is invalid due to mixed upper and lower case letters
const invalidResponse = `OFXHEADER:100
DATA:OFXSGML
VERSION:102
SECURITY:NONE
ENCODING:USASCII
CHARSET:1252
COMPRESSION:NONE
OLDFILEUID:NONE
NEWFILEUID:NONE
<OFX>
<SIGNONMSGSRSV1>
<SONRS>
<STATUS>
<CODE>0</CODE>
<SEVERITY>Info</SEVERITY>
</STATUS>
<LANGUAGE>ENG</LANGUAGE>
</SONRS>
</SIGNONMSGSRSV1>
<BANKMSGSRSV1>
<STMTTRNRS>
<TRNUID>0</TRNUID>
<STATUS>
<CODE>0</CODE>
<SEVERITY>Info</SEVERITY>
</STATUS>
</STMTTRNRS>
</BANKMSGSRSV1>
</OFX>
`
const expectedErr = "Validation failed: Invalid STATUS>SEVERITY; Invalid STATUS>SEVERITY"
t.Run("parse response", func(t *testing.T) {
resp, err := ParseResponse(bytes.NewReader([]byte(invalidResponse)))
expectedErr := "Validation failed: Invalid STATUS>SEVERITY; Invalid STATUS>SEVERITY"
if err == nil {
t.Fatalf("ParseResponse should fail with %q, found nil", expectedErr)
}
if _, ok := err.(errInvalid); !ok {
t.Errorf("ParseResponse should return an error with type ErrInvalid, found %T", err)
}
if err.Error() != expectedErr {
t.Errorf("ParseResponse should fail with %q, found %v", expectedErr, err)
}
if resp == nil {
t.Errorf("Response must not be nil if only validation errors are present")
}
})
t.Run("parse failed", func(t *testing.T) {
resp, err := ParseResponse(bytes.NewReader(nil))
if err == nil {
t.Error("ParseResponse should fail to decode")
}
if resp != nil {
t.Errorf("ParseResponse should return a nil response, found: %v", resp)
}
})
t.Run("decode, then validate response", func(t *testing.T) {
resp, err := DecodeResponse(bytes.NewReader([]byte(invalidResponse)))
if err != nil {
t.Errorf("Unexpected error: %s", err.Error())
}
if resp == nil {
t.Fatal("Response should not be nil from successful decode")
}
valid, err := resp.Valid()
if valid {
t.Error("Response should not be valid")
}
if err == nil {
t.Fatalf("response.Valid() should fail with %q, found nil", expectedErr)
}
if _, ok := err.(errInvalid); !ok {
t.Errorf("response.Valid() should return an error of type ErrInvalid, found: %T", err)
}
if err.Error() != expectedErr {
t.Errorf("response.Valid() should return an error with message %q, but found %q", expectedErr, err.Error())
}
})
}
func TestErrInvalidError(t *testing.T) {
expectedErr := `Validation failed: A; B; C`
actualErr := errInvalid{
errors.New("A"),
errors.New("B"),
errors.New("C"),
}.Error()
if expectedErr != actualErr {
t.Errorf("Unexpected invalid error message to be %q, but was: %s", expectedErr, actualErr)
}
}
func TestErrInvalidAddErr(t *testing.T) {
t.Run("nil error should be a no-op", func(t *testing.T) {
var errs errInvalid
errs.AddErr(nil)
if len(errs) != 0 {
t.Errorf("Nil err should not be added")
}
})
t.Run("adds an error normally", func(t *testing.T) {
var errs errInvalid
errs.AddErr(errors.New("some error"))
})
t.Run("adding the same type should flatten the errors", func(t *testing.T) {
var errs errInvalid
errs.AddErr(errInvalid{
errors.New("A"),
errors.New("B"),
})
errs.AddErr(errInvalid{
errors.New("C"),
})
if len(errs) != 3 {
t.Errorf("Errors should be flattened like [A, B, C], but found: %+v", errs)
}
})
}
func TestErrInvalidErrOrNil(t *testing.T) {
var errs errInvalid
if err := errs.ErrOrNil(); err != nil {
t.Errorf("No added errors should return nil, found: %v", err)
}
someError := errors.New("some error")
errs.AddErr(someError)
err := errs.ErrOrNil()
if err == nil {
t.Fatal("Expected an error, found nil.")
}
if _, ok := err.(errInvalid); !ok {
t.Fatalf("Expected err to be of type errInvalid, found: %T", err)
}
errInv := err.(errInvalid)
if len(errInv) != 1 || errInv[0] != someError {
t.Errorf("Expected ErrOrNil to return itself, found: %v", err)
}
}