jsoniter_any_int_test.go 2.2 KB

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