You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

133 lines
2.2 KiB

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