1
2
3
4
5
6
7 package json
8
9 import (
10 "regexp"
11 "testing"
12 )
13
14 func TestNumberIsValid(t *testing.T) {
15
16 var jsonNumberRegexp = regexp.MustCompile(`^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$`)
17
18 validTests := []string{
19 "0",
20 "-0",
21 "1",
22 "-1",
23 "0.1",
24 "-0.1",
25 "1234",
26 "-1234",
27 "12.34",
28 "-12.34",
29 "12E0",
30 "12E1",
31 "12e34",
32 "12E-0",
33 "12e+1",
34 "12e-34",
35 "-12E0",
36 "-12E1",
37 "-12e34",
38 "-12E-0",
39 "-12e+1",
40 "-12e-34",
41 "1.2E0",
42 "1.2E1",
43 "1.2e34",
44 "1.2E-0",
45 "1.2e+1",
46 "1.2e-34",
47 "-1.2E0",
48 "-1.2E1",
49 "-1.2e34",
50 "-1.2E-0",
51 "-1.2e+1",
52 "-1.2e-34",
53 "0E0",
54 "0E1",
55 "0e34",
56 "0E-0",
57 "0e+1",
58 "0e-34",
59 "-0E0",
60 "-0E1",
61 "-0e34",
62 "-0E-0",
63 "-0e+1",
64 "-0e-34",
65 }
66
67 for _, test := range validTests {
68 if !isValidNumber(test) {
69 t.Errorf("%s should be valid", test)
70 }
71
72 var f float64
73 if err := Unmarshal([]byte(test), &f); err != nil {
74 t.Errorf("%s should be valid but Unmarshal failed: %v", test, err)
75 }
76
77 if !jsonNumberRegexp.MatchString(test) {
78 t.Errorf("%s should be valid but regexp does not match", test)
79 }
80 }
81
82 invalidTests := []string{
83 "",
84 "invalid",
85 "1.0.1",
86 "1..1",
87 "-1-2",
88 "012a42",
89 "01.2",
90 "012",
91 "12E12.12",
92 "1e2e3",
93 "1e+-2",
94 "1e--23",
95 "1e",
96 "e1",
97 "1e+",
98 "1ea",
99 "1a",
100 "1.a",
101 "1.",
102 "01",
103 "1.e1",
104 }
105
106 for _, test := range invalidTests {
107 if isValidNumber(test) {
108 t.Errorf("%s should be invalid", test)
109 }
110
111 var f float64
112 if err := Unmarshal([]byte(test), &f); err == nil {
113 t.Errorf("%s should be invalid but unmarshal wrote %v", test, f)
114 }
115
116 if jsonNumberRegexp.MatchString(test) {
117 t.Errorf("%s should be invalid but matches regexp", test)
118 }
119 }
120 }
121
View as plain text