jsoniter_any_int_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. package jsoniter
  2. import (
  3. "fmt"
  4. "io"
  5. "testing"
  6. "github.com/json-iterator/go/require"
  7. )
  8. var intConvertMap = map[string]int{
  9. "321.1": 321,
  10. "-321.1": -321,
  11. `"1.1"`: 1,
  12. `"-1.1"`: -1,
  13. "0.0": 0,
  14. "0": 0,
  15. `"0"`: 0,
  16. `"0.0"`: 0,
  17. "-1.1": -1,
  18. "true": 1,
  19. "false": 0,
  20. `"true"`: 0,
  21. `"false"`: 0,
  22. `"true123"`: 0,
  23. `"123true"`: 123,
  24. `"1.2332e6"`: 1,
  25. `""`: 0,
  26. "+": 0,
  27. "-": 0,
  28. "[]": 0,
  29. "[1,2]": 1,
  30. }
  31. func Test_read_any_to_int(t *testing.T) {
  32. should := require.New(t)
  33. // int
  34. for k, v := range intConvertMap {
  35. any := Get([]byte(k))
  36. should.Equal(v, any.ToInt(), fmt.Sprintf("origin val %v", k))
  37. }
  38. // int32
  39. for k, v := range intConvertMap {
  40. any := Get([]byte(k))
  41. should.Equal(int32(v), any.ToInt32(), fmt.Sprintf("original val is %v", k))
  42. }
  43. // int64
  44. for k, v := range intConvertMap {
  45. any := Get([]byte(k))
  46. should.Equal(int64(v), any.ToInt64(), fmt.Sprintf("original val is %v", k))
  47. }
  48. }
  49. var uintConvertMap = map[string]int{
  50. "321.1": 321,
  51. `"1.1"`: 1,
  52. `"-1.1"`: 1,
  53. "0.0": 0,
  54. "0": 0,
  55. `"0"`: 0,
  56. `"0.0"`: 0,
  57. "true": 1,
  58. "false": 0,
  59. `"true"`: 0,
  60. `"false"`: 0,
  61. `"true123"`: 0,
  62. `"123true"`: 123,
  63. `"1.2332e6"`: 1,
  64. `""`: 0,
  65. "+": 0,
  66. "-": 0,
  67. "[]": 0,
  68. "[1,2]": 1,
  69. // TODO need to solve
  70. //"-1.1": 1,
  71. //"-321.1": 321,
  72. }
  73. func Test_read_any_to_uint(t *testing.T) {
  74. should := require.New(t)
  75. for k, v := range uintConvertMap {
  76. any := Get([]byte(k))
  77. should.Equal(uint64(v), any.ToUint64(), fmt.Sprintf("origin val %v", k))
  78. }
  79. for k, v := range uintConvertMap {
  80. any := Get([]byte(k))
  81. should.Equal(uint32(v), any.ToUint32(), fmt.Sprintf("origin val %v", k))
  82. }
  83. for k, v := range uintConvertMap {
  84. any := Get([]byte(k))
  85. should.Equal(uint32(v), any.ToUint32(), fmt.Sprintf("origin val %v", k))
  86. }
  87. }
  88. func Test_read_int64_as_any(t *testing.T) {
  89. should := require.New(t)
  90. any := Get([]byte("1234"))
  91. should.Equal(1234, any.ToInt())
  92. should.Equal(io.EOF, any.LastError())
  93. should.Equal("1234", any.ToString())
  94. should.True(any.ToBool())
  95. }
  96. func Test_int_lazy_any_get(t *testing.T) {
  97. should := require.New(t)
  98. any := Get([]byte("1234"))
  99. should.Equal(Invalid, any.Get(1, "2").ValueType())
  100. }