jsoniter_object_test.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. package jsoniter
  2. import (
  3. "bytes"
  4. "fmt"
  5. "testing"
  6. "github.com/stretchr/testify/require"
  7. )
  8. func Test_empty_object(t *testing.T) {
  9. should := require.New(t)
  10. iter := ParseString(ConfigDefault, `{}`)
  11. field := iter.ReadObject()
  12. should.Equal("", field)
  13. iter = ParseString(ConfigDefault, `{}`)
  14. iter.ReadObjectCB(func(iter *Iterator, field string) bool {
  15. should.FailNow("should not call")
  16. return true
  17. })
  18. }
  19. func Test_one_field(t *testing.T) {
  20. should := require.New(t)
  21. iter := ParseString(ConfigDefault, `{"a": "stream"}`)
  22. field := iter.ReadObject()
  23. should.Equal("a", field)
  24. value := iter.ReadString()
  25. should.Equal("stream", value)
  26. field = iter.ReadObject()
  27. should.Equal("", field)
  28. iter = ParseString(ConfigDefault, `{"a": "stream"}`)
  29. should.True(iter.ReadObjectCB(func(iter *Iterator, field string) bool {
  30. should.Equal("a", field)
  31. iter.Skip()
  32. return true
  33. }))
  34. }
  35. func Test_two_field(t *testing.T) {
  36. should := require.New(t)
  37. iter := ParseString(ConfigDefault, `{ "a": "stream" , "c": "d" }`)
  38. field := iter.ReadObject()
  39. should.Equal("a", field)
  40. value := iter.ReadString()
  41. should.Equal("stream", value)
  42. field = iter.ReadObject()
  43. should.Equal("c", field)
  44. value = iter.ReadString()
  45. should.Equal("d", value)
  46. field = iter.ReadObject()
  47. should.Equal("", field)
  48. iter = ParseString(ConfigDefault, `{"field1": "1", "field2": 2}`)
  49. for field := iter.ReadObject(); field != ""; field = iter.ReadObject() {
  50. switch field {
  51. case "field1":
  52. iter.ReadString()
  53. case "field2":
  54. iter.ReadInt64()
  55. default:
  56. iter.ReportError("bind object", "unexpected field")
  57. }
  58. }
  59. }
  60. func Test_object_wrapper_any_get_all(t *testing.T) {
  61. should := require.New(t)
  62. type TestObject struct {
  63. Field1 []int
  64. Field2 []int
  65. }
  66. any := Wrap(TestObject{[]int{1, 2}, []int{3, 4}})
  67. should.Contains(any.Get('*', 0).ToString(), `"Field2":3`)
  68. should.Contains(any.Keys(), "Field1")
  69. should.Contains(any.Keys(), "Field2")
  70. should.NotContains(any.Keys(), "Field3")
  71. //should.Contains(any.GetObject()["Field1"].GetArray()[0], 1)
  72. }
  73. func Test_write_object(t *testing.T) {
  74. should := require.New(t)
  75. buf := &bytes.Buffer{}
  76. stream := NewStream(Config{IndentionStep: 2}.Froze(), buf, 4096)
  77. stream.WriteObjectStart()
  78. stream.WriteObjectField("hello")
  79. stream.WriteInt(1)
  80. stream.WriteMore()
  81. stream.WriteObjectField("world")
  82. stream.WriteInt(2)
  83. stream.WriteObjectEnd()
  84. stream.Flush()
  85. should.Nil(stream.Error)
  86. should.Equal("{\n \"hello\": 1,\n \"world\": 2\n}", buf.String())
  87. }
  88. func Test_write_val_zero_field_struct(t *testing.T) {
  89. should := require.New(t)
  90. type TestObject struct {
  91. }
  92. obj := TestObject{}
  93. str, err := MarshalToString(obj)
  94. should.Nil(err)
  95. should.Equal(`{}`, str)
  96. }
  97. func Test_write_val_one_field_struct(t *testing.T) {
  98. should := require.New(t)
  99. type TestObject struct {
  100. Field1 string `json:"field-1"`
  101. }
  102. obj := TestObject{"hello"}
  103. str, err := MarshalToString(obj)
  104. should.Nil(err)
  105. should.Equal(`{"field-1":"hello"}`, str)
  106. }
  107. func Test_mixed(t *testing.T) {
  108. should := require.New(t)
  109. type AA struct {
  110. ID int `json:"id"`
  111. Payload map[string]interface{} `json:"payload"`
  112. buf *bytes.Buffer
  113. }
  114. aa := AA{}
  115. err := UnmarshalFromString(` {"id":1, "payload":{"account":"123","password":"456"}}`, &aa)
  116. should.Nil(err)
  117. should.Equal(1, aa.ID)
  118. should.Equal("123", aa.Payload["account"])
  119. }
  120. func Test_omit_empty(t *testing.T) {
  121. should := require.New(t)
  122. type TestObject struct {
  123. Field1 string `json:"field-1,omitempty"`
  124. Field2 string `json:"field-2,omitempty"`
  125. Field3 string `json:"field-3,omitempty"`
  126. }
  127. obj := TestObject{}
  128. obj.Field2 = "hello"
  129. str, err := MarshalToString(&obj)
  130. should.Nil(err)
  131. should.Equal(`{"field-2":"hello"}`, str)
  132. }
  133. func Test_ignore_field_on_not_valid_type(t *testing.T) {
  134. should := require.New(t)
  135. type TestObject struct {
  136. Field1 string `json:"field-1,omitempty"`
  137. Field2 func() `json:"-"`
  138. }
  139. obj := TestObject{}
  140. obj.Field1 = "hello world"
  141. obj.Field2 = func() {}
  142. str, err := MarshalToString(&obj)
  143. should.Nil(err)
  144. should.Equal(`{"field-1":"hello world"}`, str)
  145. }
  146. func Test_recursive_struct(t *testing.T) {
  147. should := require.New(t)
  148. type TestObject struct {
  149. Field1 string
  150. Me *TestObject
  151. }
  152. obj := TestObject{}
  153. str, err := MarshalToString(obj)
  154. should.Nil(err)
  155. should.Contains(str, `"Field1":""`)
  156. should.Contains(str, `"Me":null`)
  157. err = UnmarshalFromString(str, &obj)
  158. should.Nil(err)
  159. }
  160. func Test_encode_anonymous_struct(t *testing.T) {
  161. should := require.New(t)
  162. type TestObject struct {
  163. Field string
  164. }
  165. str, err := MarshalToString(struct {
  166. TestObject
  167. Field int
  168. }{
  169. Field: 100,
  170. })
  171. should.Nil(err)
  172. should.Equal(`{"Field":100}`, str)
  173. }
  174. func Test_decode_anonymous_struct(t *testing.T) {
  175. should := require.New(t)
  176. type Inner struct {
  177. Key string `json:"key"`
  178. }
  179. type Outer struct {
  180. Inner
  181. }
  182. var outer Outer
  183. j := []byte("{\"key\":\"value\"}")
  184. should.Nil(Unmarshal(j, &outer))
  185. should.Equal("value", outer.Key)
  186. }
  187. func Test_multiple_level_anonymous_struct(t *testing.T) {
  188. type Level1 struct {
  189. Field1 string
  190. }
  191. type Level2 struct {
  192. Level1
  193. Field2 string
  194. }
  195. type Level3 struct {
  196. Level2
  197. Field3 string
  198. }
  199. should := require.New(t)
  200. obj := Level3{Level2{Level1{"1"}, "2"}, "3"}
  201. output, err := MarshalToString(obj)
  202. should.Nil(err)
  203. should.Equal(`{"Field1":"1","Field2":"2","Field3":"3"}`, output)
  204. }
  205. func Test_multiple_level_anonymous_struct_with_ptr(t *testing.T) {
  206. type Level1 struct {
  207. Field1 string
  208. Field2 string
  209. Field4 string
  210. }
  211. type Level2 struct {
  212. *Level1
  213. Field2 string
  214. Field3 string
  215. }
  216. type Level3 struct {
  217. *Level2
  218. Field3 string
  219. }
  220. should := require.New(t)
  221. obj := Level3{&Level2{&Level1{"1", "", "4"}, "2", ""}, "3"}
  222. output, err := MarshalToString(obj)
  223. should.Nil(err)
  224. should.Contains(output, `"Field1":"1"`)
  225. should.Contains(output, `"Field2":"2"`)
  226. should.Contains(output, `"Field3":"3"`)
  227. should.Contains(output, `"Field4":"4"`)
  228. }
  229. func Test_shadow_struct_field(t *testing.T) {
  230. should := require.New(t)
  231. type omit *struct{}
  232. type CacheItem struct {
  233. Key string `json:"key"`
  234. MaxAge int `json:"cacheAge"`
  235. }
  236. output, err := MarshalToString(struct {
  237. *CacheItem
  238. // Omit bad keys
  239. OmitMaxAge omit `json:"cacheAge,omitempty"`
  240. // Add nice keys
  241. MaxAge int `json:"max_age"`
  242. }{
  243. CacheItem: &CacheItem{
  244. Key: "value",
  245. MaxAge: 100,
  246. },
  247. MaxAge: 20,
  248. })
  249. should.Nil(err)
  250. should.Contains(output, `"key":"value"`)
  251. should.Contains(output, `"max_age":20`)
  252. }
  253. func Test_embedded_order(t *testing.T) {
  254. type A struct {
  255. Field2 string
  256. }
  257. type C struct {
  258. Field5 string
  259. }
  260. type B struct {
  261. Field4 string
  262. C
  263. Field6 string
  264. }
  265. type TestObject struct {
  266. Field1 string
  267. A
  268. Field3 string
  269. B
  270. Field7 string
  271. }
  272. should := require.New(t)
  273. s := TestObject{}
  274. output, err := MarshalToString(s)
  275. should.Nil(err)
  276. should.Equal(`{"Field1":"","Field2":"","Field3":"","Field4":"","Field5":"","Field6":"","Field7":""}`, output)
  277. }
  278. func Test_decode_nested(t *testing.T) {
  279. type StructOfString struct {
  280. Field1 string
  281. Field2 string
  282. }
  283. iter := ParseString(ConfigDefault, `[{"field1": "hello"}, null, {"field2": "world"}]`)
  284. slice := []*StructOfString{}
  285. iter.ReadVal(&slice)
  286. if len(slice) != 3 {
  287. fmt.Println(iter.Error)
  288. t.Fatal(len(slice))
  289. }
  290. if slice[0].Field1 != "hello" {
  291. fmt.Println(iter.Error)
  292. t.Fatal(slice[0])
  293. }
  294. if slice[1] != nil {
  295. fmt.Println(iter.Error)
  296. t.Fatal(slice[1])
  297. }
  298. if slice[2].Field2 != "world" {
  299. fmt.Println(iter.Error)
  300. t.Fatal(slice[2])
  301. }
  302. }
  303. func Test_decode_field_with_escape(t *testing.T) {
  304. should := require.New(t)
  305. type TestObject struct {
  306. Field1 string
  307. }
  308. var obj TestObject
  309. should.Nil(ConfigCompatibleWithStandardLibrary.Unmarshal([]byte(`{"Field\"1":"hello"}`), &obj))
  310. should.Equal("", obj.Field1)
  311. should.Nil(ConfigCompatibleWithStandardLibrary.Unmarshal([]byte(`{"\u0046ield1":"hello"}`), &obj))
  312. should.Equal("hello", obj.Field1)
  313. }