summaryrefslogtreecommitdiff
path: root/decode_test.go
diff options
context:
space:
mode:
authorLuke Shumaker <lukeshu@lukeshu.com>2023-02-17 19:21:37 -0700
committerLuke Shumaker <lukeshu@lukeshu.com>2023-02-25 00:47:52 -0700
commitd01fa91dcdfd428fb4b1c46b3961a1497c7a1102 (patch)
tree0724da76664e893e7ecfad2d8ce4ea1b05918598 /decode_test.go
parentf369aff688697a881833d86c13b18156e8376f08 (diff)
decode: Don't bail on type errors
Diffstat (limited to 'decode_test.go')
-rw-r--r--decode_test.go47
1 files changed, 47 insertions, 0 deletions
diff --git a/decode_test.go b/decode_test.go
index 456f363..c224f3a 100644
--- a/decode_test.go
+++ b/decode_test.go
@@ -48,3 +48,50 @@ func TestDecodeGrowing(t *testing.T) {
assert.NoError(t, dec.Decode(&x))
assert.ErrorIs(t, dec.Decode(&x), io.EOF)
}
+
+type testAry []int
+
+func (a *testAry) DecodeJSON(r io.RuneScanner) error {
+ return DecodeArray(r, func(r io.RuneScanner) error {
+ var x int
+ if err := NewDecoder(r).Decode(&x); err != nil {
+ return err
+ }
+ *a = append(*a, x)
+ return nil
+ })
+}
+
+type testObj map[string]int
+
+func (o *testObj) DecodeJSON(r io.RuneScanner) error {
+ *o = make(testObj)
+ var key string
+ return DecodeObject(r,
+ func(r io.RuneScanner) error {
+ return NewDecoder(r).Decode(&key)
+ },
+ func(r io.RuneScanner) error {
+ var val int
+ if err := NewDecoder(r).Decode(&val); err != nil {
+ return err
+ }
+ (*o)[key] = val
+ return nil
+ },
+ )
+}
+
+func TestDecodeTypeError(t *testing.T) {
+ t.Parallel()
+ type outType struct {
+ First int
+ Second testAry
+ Third testObj
+ }
+ var out outType
+ err := NewDecoder(strings.NewReader(`{"First": 1.2, "Second": [3], "Third": {"a":4}}`)).Decode(&out)
+ assert.EqualError(t, err,
+ `json: v["First"]: cannot decode JSON number 1.2 at input byte 9 into Go int: strconv.ParseInt: parsing "1.2": invalid syntax`)
+ assert.Equal(t, outType{First: 0, Second: testAry{3}, Third: testObj{"a": 4}}, out)
+}