git.lukeshu.com/go/lowmemjson@v0.3.9-0.20230723050957-72f6d13f6fb2/compat/json/borrowed_number_test.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 // 5 // SPDX-License-Identifier: BSD-3-Clause 6 7 package json 8 9 import ( 10 "regexp" 11 "testing" 12 ) 13 14 func TestNumberIsValid(t *testing.T) { 15 t.Parallel() // MODIFIED: added 16 // From: https://stackoverflow.com/a/13340826 17 var jsonNumberRegexp = regexp.MustCompile(`^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$`) 18 19 validTests := []string{ 20 "0", 21 "-0", 22 "1", 23 "-1", 24 "0.1", 25 "-0.1", 26 "1234", 27 "-1234", 28 "12.34", 29 "-12.34", 30 "12E0", 31 "12E1", 32 "12e34", 33 "12E-0", 34 "12e+1", 35 "12e-34", 36 "-12E0", 37 "-12E1", 38 "-12e34", 39 "-12E-0", 40 "-12e+1", 41 "-12e-34", 42 "1.2E0", 43 "1.2E1", 44 "1.2e34", 45 "1.2E-0", 46 "1.2e+1", 47 "1.2e-34", 48 "-1.2E0", 49 "-1.2E1", 50 "-1.2e34", 51 "-1.2E-0", 52 "-1.2e+1", 53 "-1.2e-34", 54 "0E0", 55 "0E1", 56 "0e34", 57 "0E-0", 58 "0e+1", 59 "0e-34", 60 "-0E0", 61 "-0E1", 62 "-0e34", 63 "-0E-0", 64 "-0e+1", 65 "-0e-34", 66 } 67 68 for _, test := range validTests { 69 if !isValidNumber(test) { 70 t.Errorf("%s should be valid", test) 71 } 72 73 var f float64 74 if err := Unmarshal([]byte(test), &f); err != nil { 75 t.Errorf("%s should be valid but Unmarshal failed: %v", test, err) 76 } 77 78 if !jsonNumberRegexp.MatchString(test) { 79 t.Errorf("%s should be valid but regexp does not match", test) 80 } 81 } 82 83 invalidTests := []string{ 84 "", 85 "invalid", 86 "1.0.1", 87 "1..1", 88 "-1-2", 89 "012a42", 90 "01.2", 91 "012", 92 "12E12.12", 93 "1e2e3", 94 "1e+-2", 95 "1e--23", 96 "1e", 97 "e1", 98 "1e+", 99 "1ea", 100 "1a", 101 "1.a", 102 "1.", 103 "01", 104 "1.e1", 105 } 106 107 for _, test := range invalidTests { 108 if isValidNumber(test) { 109 t.Errorf("%s should be invalid", test) 110 } 111 112 var f float64 113 if err := Unmarshal([]byte(test), &f); err == nil { 114 t.Errorf("%s should be invalid but unmarshal wrote %v", test, f) 115 } 116 117 if jsonNumberRegexp.MatchString(test) { 118 t.Errorf("%s should be invalid but matches regexp", test) 119 } 120 } 121 }