jsoniter_any_int_test.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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. // object in php cannot convert to int
  31. "{}": 0,
  32. }
  33. func Test_read_any_to_int(t *testing.T) {
  34. should := require.New(t)
  35. // int
  36. for k, v := range intConvertMap {
  37. any := Get([]byte(k))
  38. should.Equal(v, any.ToInt(), fmt.Sprintf("origin val %v", k))
  39. }
  40. // int32
  41. for k, v := range intConvertMap {
  42. any := Get([]byte(k))
  43. should.Equal(int32(v), any.ToInt32(), fmt.Sprintf("original val is %v", k))
  44. }
  45. // int64
  46. for k, v := range intConvertMap {
  47. any := Get([]byte(k))
  48. should.Equal(int64(v), any.ToInt64(), fmt.Sprintf("original val is %v", k))
  49. }
  50. }
  51. var uintConvertMap = map[string]int{
  52. "321.1": 321,
  53. `"1.1"`: 1,
  54. `"-1.1"`: 1,
  55. "0.0": 0,
  56. "0": 0,
  57. `"0"`: 0,
  58. `"0.0"`: 0,
  59. "true": 1,
  60. "false": 0,
  61. `"true"`: 0,
  62. `"false"`: 0,
  63. `"true123"`: 0,
  64. `"123true"`: 123,
  65. `"1.2332e6"`: 1,
  66. `""`: 0,
  67. "+": 0,
  68. "-": 0,
  69. "[]": 0,
  70. "[1,2]": 1,
  71. "{}": 0,
  72. // TODO need to solve
  73. //"-1.1": 1,
  74. //"-321.1": 321,
  75. }
  76. func Test_read_any_to_uint(t *testing.T) {
  77. should := require.New(t)
  78. for k, v := range uintConvertMap {
  79. any := Get([]byte(k))
  80. should.Equal(uint64(v), any.ToUint64(), fmt.Sprintf("origin val %v", k))
  81. }
  82. for k, v := range uintConvertMap {
  83. any := Get([]byte(k))
  84. should.Equal(uint32(v), any.ToUint32(), fmt.Sprintf("origin val %v", k))
  85. }
  86. for k, v := range uintConvertMap {
  87. any := Get([]byte(k))
  88. should.Equal(uint32(v), any.ToUint32(), fmt.Sprintf("origin val %v", k))
  89. }
  90. }
  91. func Test_read_int64_as_any(t *testing.T) {
  92. should := require.New(t)
  93. any := Get([]byte("1234"))
  94. should.Equal(1234, any.ToInt())
  95. should.Equal(io.EOF, any.LastError())
  96. should.Equal("1234", any.ToString())
  97. should.True(any.ToBool())
  98. }
  99. func Test_int_lazy_any_get(t *testing.T) {
  100. should := require.New(t)
  101. any := Get([]byte("1234"))
  102. should.Equal(Invalid, any.Get(1, "2").ValueType())
  103. }