forked from shopspring/decimal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
null_decimal_json_test.go
98 lines (90 loc) · 2.55 KB
/
null_decimal_json_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
package decimal
import (
"encoding/json"
"testing"
)
func TestNullDecimalJSON(t *testing.T) {
for _, x := range testTable {
s := x.short
var doc struct {
Amount NullDecimal `json:"amount"`
}
docStr := `{"amount":"` + s + `"}`
docStrNumber := `{"amount":` + s + `}`
err := json.Unmarshal([]byte(docStr), &doc)
if err != nil {
t.Errorf("error unmarshaling %s: %v", docStr, err)
} else {
if !doc.Amount.Valid {
t.Errorf("expected %s to be valid (not NULL), got Valid = false", s)
}
if doc.Amount.Decimal.String() != s {
t.Errorf("expected %s, got %s (%s, %d)",
s, doc.Amount.Decimal.String(),
doc.Amount.Decimal.value.String(), doc.Amount.Decimal.exp)
}
}
out, err := json.Marshal(&doc)
if err != nil {
t.Errorf("error marshaling %+v: %v", doc, err)
} else if string(out) != docStr {
t.Errorf("expected %s, got %s", docStr, string(out))
}
// make sure unquoted marshalling works too
MarshalJSONWithoutQuotes = true
out, err = json.Marshal(&doc)
if err != nil {
t.Errorf("error marshaling %+v: %v", doc, err)
} else if string(out) != docStrNumber {
t.Errorf("expected %s, got %s", docStrNumber, string(out))
}
MarshalJSONWithoutQuotes = false
}
var doc struct {
Amount NullDecimal `json:"amount"`
}
docStr := `{"amount": null}`
err := json.Unmarshal([]byte(docStr), &doc)
if err != nil {
t.Errorf("error unmarshaling %s: %v", docStr, err)
} else if doc.Amount.Valid {
t.Errorf("expected null value to have Valid = false, got Valid = true and Decimal = %s (%s, %d)",
doc.Amount.Decimal.String(),
doc.Amount.Decimal.value.String(), doc.Amount.Decimal.exp)
}
expected := `{"amount":null}`
out, err := json.Marshal(&doc)
if err != nil {
t.Errorf("error marshaling %+v: %v", doc, err)
} else if string(out) != expected {
t.Errorf("expected %s, got %s", expected, string(out))
}
// make sure unquoted marshalling works too
MarshalJSONWithoutQuotes = true
expectedUnquoted := `{"amount":null}`
out, err = json.Marshal(&doc)
if err != nil {
t.Errorf("error marshaling %+v: %v", doc, err)
} else if string(out) != expectedUnquoted {
t.Errorf("expected %s, got %s", expectedUnquoted, string(out))
}
MarshalJSONWithoutQuotes = false
}
func TestNullDecimalBadJSON(t *testing.T) {
for _, testCase := range []string{
"]o_o[",
"{",
`{"amount":""`,
`{"amount":"nope"}`,
`{"amount":nope}`,
`0.333`,
} {
var doc struct {
Amount NullDecimal `json:"amount"`
}
err := json.Unmarshal([]byte(testCase), &doc)
if err == nil {
t.Errorf("expected error, got %+v", doc)
}
}
}