github.com/goshafaq/sonic@v0.0.0-20231026082336-871835fb94c6/ast/node_test.go (about) 1 /* 2 * Copyright 2021 ByteDance Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package ast 18 19 import ( 20 "bytes" 21 "encoding/json" 22 "errors" 23 "fmt" 24 "reflect" 25 "runtime" 26 "runtime/debug" 27 "strconv" 28 "testing" 29 30 "github.com/goshafaq/sonic/internal/native/types" 31 "github.com/goshafaq/sonic/internal/rt" 32 "github.com/stretchr/testify/assert" 33 "github.com/stretchr/testify/require" 34 ) 35 36 func TestNodeSortKeys(t *testing.T) { 37 var src = `{"b":1,"a":2,"c":3}` 38 root, err := NewSearcher(src).GetByPath() 39 if err != nil { 40 t.Fatal(err) 41 } 42 obj, err := root.MapUseNumber() 43 if err != nil { 44 t.Fatal(err) 45 } 46 exp, err := json.Marshal(obj) 47 if err != nil { 48 t.Fatal(err) 49 } 50 if err := root.SortKeys(true); err != nil { 51 t.Fatal(err) 52 } 53 act, err := root.MarshalJSON() 54 if err != nil { 55 t.Fatal(err) 56 } 57 assert.Equal(t, len(exp), len(act)) 58 assert.Equal(t, string(exp), string(act)) 59 60 src = `[[1], {"b":1,"a":2,"c":3}, [], {}, [{"b":1,"a":2,"c":3,"d":[],"e":{}}]]` 61 root, err = NewSearcher(src).GetByPath() 62 if err != nil { 63 t.Fatal(err) 64 } 65 vv, err := root.Interface() 66 if err != nil { 67 t.Fatal(err) 68 } 69 exp, err = json.Marshal(vv) 70 if err != nil { 71 t.Fatal(err) 72 } 73 if err := root.SortKeys(true); err != nil { 74 t.Fatal(err) 75 } 76 act, err = root.MarshalJSON() 77 if err != nil { 78 t.Fatal(err) 79 } 80 assert.Equal(t, string(exp), string(act)) 81 82 } 83 84 func BenchmarkNodeSortKeys(b *testing.B) { 85 root, err := NewSearcher(_TwitterJson).GetByPath() 86 if err != nil { 87 b.Fatal(err) 88 } 89 if err := root.LoadAll(); err != nil { 90 b.Fatal(err) 91 } 92 93 b.Run("single", func(b *testing.B) { 94 r := root.Get("statuses") 95 if r.Check() != nil { 96 b.Fatal(r.Error()) 97 } 98 b.SetBytes(int64(len(_TwitterJson))) 99 b.ResetTimer() 100 for i := 0; i < b.N; i++ { 101 _ = root.SortKeys(false) 102 } 103 }) 104 b.Run("recurse", func(b *testing.B) { 105 b.SetBytes(int64(len(_TwitterJson))) 106 b.ResetTimer() 107 for i := 0; i < b.N; i++ { 108 _ = root.SortKeys(true) 109 } 110 }) 111 } 112 113 //go:noinline 114 func stackObj() interface{} { 115 var a int = 1 116 return rt.UnpackEface(a).Pack() 117 } 118 119 func TestStackAny(t *testing.T) { 120 var obj = stackObj() 121 any := NewAny(obj) 122 fmt.Printf("any: %#v\n", any) 123 runtime.GC() 124 debug.FreeOSMemory() 125 println("finish GC") 126 buf, err := any.MarshalJSON() 127 println("finish marshal") 128 if err != nil { 129 t.Fatal(err) 130 } 131 if string(buf) != `1` { 132 t.Fatal(string(buf)) 133 } 134 } 135 136 func TestLoadAll(t *testing.T) { 137 e := Node{} 138 err := e.Load() 139 if err != nil { 140 t.Fatal(err) 141 } 142 err = e.LoadAll() 143 if err != nil { 144 t.Fatal(err) 145 } 146 147 root, err := NewSearcher(`{"a":{"1":[1],"2":2},"b":[{"1":1},2],"c":[1,2]}`).GetByPath() 148 if err != nil { 149 t.Fatal(err) 150 } 151 if err = root.Load(); err != nil { 152 t.Fatal(err) 153 } 154 if root.len() != 3 { 155 t.Fatal(root.len()) 156 } 157 158 c := root.Get("c") 159 if !c.IsRaw() { 160 t.Fatal(err) 161 } 162 err = c.LoadAll() 163 if err != nil { 164 t.Fatal(err) 165 } 166 if c.len() != 2 { 167 t.Fatal(c.len()) 168 } 169 c1 := c.nodeAt(0) 170 if n, err := c1.Int64(); err != nil || n != 1 { 171 t.Fatal(n, err) 172 } 173 174 a := root.pairAt(0) 175 if a.Key != "a" { 176 t.Fatal(a.Key) 177 } else if !a.Value.IsRaw() { 178 t.Fatal(a.Value.itype()) 179 } else if n, err := a.Value.Len(); n != 0 || err != nil { 180 t.Fatal(n, err) 181 } 182 if err := a.Value.Load(); err != nil { 183 t.Fatal(err) 184 } 185 if a.Value.len() != 2 { 186 t.Fatal(a.Value.len()) 187 } 188 a1 := a.Value.Get("1") 189 if !a1.IsRaw() { 190 t.Fatal(a1) 191 } 192 a.Value.LoadAll() 193 if a1.t != types.V_ARRAY || a1.len() != 1 { 194 t.Fatal(a1.t, a1.len()) 195 } 196 197 b := root.pairAt(1) 198 if b.Key != "b" { 199 t.Fatal(b.Key) 200 } else if !b.Value.IsRaw() { 201 t.Fatal(b.Value.itype()) 202 } else if n, err := b.Value.Len(); n != 0 || err != nil { 203 t.Fatal(n, err) 204 } 205 if err := b.Value.Load(); err != nil { 206 t.Fatal(err) 207 } 208 if b.Value.len() != 2 { 209 t.Fatal(b.Value.len()) 210 } 211 b1 := b.Value.Index(0) 212 if !b1.IsRaw() { 213 t.Fatal(b1) 214 } 215 b.Value.LoadAll() 216 if b1.t != types.V_OBJECT || b1.len() != 1 { 217 t.Fatal(a1.t, a1.len()) 218 } 219 } 220 221 func TestIndexPair(t *testing.T) { 222 root, _ := NewParser(`{"a":1,"b":2}`).Parse() 223 a := root.IndexPair(0) 224 if a == nil || a.Key != "a" { 225 t.Fatal(a) 226 } 227 b := root.IndexPair(1) 228 if b == nil || b.Key != "b" { 229 t.Fatal(b) 230 } 231 c := root.IndexPair(2) 232 if c != nil { 233 t.Fatal(c) 234 } 235 } 236 237 func TestIndexOrGet(t *testing.T) { 238 root, _ := NewParser(`{"a":1,"b":2}`).Parse() 239 a := root.IndexOrGet(0, "a") 240 if v, err := a.Int64(); err != nil || v != int64(1) { 241 t.Fatal(a) 242 } 243 a = root.IndexOrGet(0, "b") 244 if v, err := a.Int64(); err != nil || v != int64(2) { 245 t.Fatal(a) 246 } 247 a = root.IndexOrGet(0, "c") 248 if a.Valid() { 249 t.Fatal(a) 250 } 251 } 252 253 func TestTypeCast(t *testing.T) { 254 type tcase struct { 255 method string 256 node Node 257 exp interface{} 258 err error 259 } 260 var nonEmptyErr error = errors.New("") 261 a1 := NewAny(1) 262 lazyArray, _ := NewParser("[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]").Parse() 263 lazyObject, _ := NewParser(`{"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":16}`).Parse() 264 var cases = []tcase{ 265 {"Interface", Node{}, interface{}(nil), ErrUnsupportType}, 266 {"Interface", NewAny(NewNumber("1")), float64(1), nil}, 267 {"Interface", NewAny(int64(1)), int64(1), nil}, 268 {"Interface", NewNumber("1"), float64(1), nil}, 269 {"InterfaceUseNode", Node{}, Node{}, nil}, 270 {"InterfaceUseNode", a1, a1, nil}, 271 {"InterfaceUseNode", NewNumber("1"), NewNumber("1"), nil}, 272 {"InterfaceUseNumber", Node{}, interface{}(nil), ErrUnsupportType}, 273 {"InterfaceUseNumber", NewAny(1), 1, nil}, 274 {"InterfaceUseNumber", NewNumber("1"), json.Number("1"), nil}, 275 {"Map", Node{}, map[string]interface{}(nil), ErrUnsupportType}, 276 {"Map", NewAny(map[string]Node{"a": NewNumber("1")}), map[string]interface{}(nil), ErrUnsupportType}, 277 {"Map", NewAny(map[string]interface{}{"a": 1}), map[string]interface{}{"a": 1}, nil}, 278 {"Map", NewObject([]Pair{{"a", NewNumber("1")}}), map[string]interface{}{"a": float64(1.0)}, nil}, 279 {"MapUseNode", Node{}, map[string]Node(nil), ErrUnsupportType}, 280 {"MapUseNode", NewAny(map[string]interface{}{"a": 1}), map[string]Node(nil), ErrUnsupportType}, 281 {"MapUseNode", NewAny(map[string]Node{"a": NewNumber("1")}), map[string]Node{"a": NewNumber("1")}, nil}, 282 {"MapUseNode", NewObject([]Pair{{"a", NewNumber("1")}}), map[string]Node{"a": NewNumber("1")}, nil}, 283 {"MapUseNumber", Node{}, map[string]interface{}(nil), ErrUnsupportType}, 284 {"MapUseNumber", NewAny(map[string]interface{}{"a": 1}), map[string]interface{}{"a": 1}, nil}, 285 {"MapUseNumber", NewObject([]Pair{{"a", NewNumber("1")}}), map[string]interface{}{"a": json.Number("1")}, nil}, 286 {"Array", Node{}, []interface{}(nil), ErrUnsupportType}, 287 {"Array", NewAny([]interface{}{1}), []interface{}{1}, nil}, 288 {"Array", NewArray([]Node{NewNumber("1")}), []interface{}{float64(1.0)}, nil}, 289 {"ArrayUseNode", Node{}, []Node(nil), ErrUnsupportType}, 290 {"ArrayUseNode", NewAny([]interface{}{1}), []Node(nil), ErrUnsupportType}, 291 {"ArrayUseNode", NewAny([]Node{NewNumber("1")}), []Node{NewNumber("1")}, nil}, 292 {"ArrayUseNode", NewArray([]Node{NewNumber("1")}), []Node{NewNumber("1")}, nil}, 293 {"ArrayUseNumber", Node{}, []interface{}(nil), ErrUnsupportType}, 294 {"ArrayUseNumber", NewAny([]interface{}{1}), []interface{}{1}, nil}, 295 {"ArrayUseNumber", NewAny([]Node{NewNumber("1")}), []interface{}(nil), ErrUnsupportType}, 296 {"ArrayUseNumber", NewArray([]Node{NewNumber("1")}), []interface{}{json.Number("1")}, nil}, 297 {"Raw", Node{}, "", ErrNotExist}, 298 {"Raw", NewAny(""), `""`, nil}, 299 {"Raw", NewRaw(" "), "", nonEmptyErr}, 300 {"Raw", NewRaw(" [ ] "), "[ ]", nil}, 301 {"Raw", NewRaw("[ ]"), "[ ]", nil}, 302 {"Raw", NewRaw(` { "a" : [ true, -1.2e34 ] } `), `{ "a" : [ true, -1.2e34 ] }`, nil}, 303 {"Raw", NewRaw(` { "a" : [ true, -1.2e34 ] `), "", nonEmptyErr}, 304 {"Raw", NewRaw(` { "a" : [ true, -1.2e34 }`), "", nonEmptyErr}, 305 {"Raw", NewBool(true), "true", nil}, 306 {"Raw", NewNumber("-0.0"), "-0.0", nil}, 307 {"Raw", NewString(""), `""`, nil}, 308 {"Raw", NewBytes([]byte("hello, world")), `"aGVsbG8sIHdvcmxk"`, nil}, 309 {"Bool", Node{}, false, ErrUnsupportType}, 310 {"Bool", NewAny(true), true, nil}, 311 {"Bool", NewAny(false), false, nil}, 312 {"Bool", NewAny(int(0)), false, nil}, 313 {"Bool", NewAny(int8(1)), true, nil}, 314 {"Bool", NewAny(int16(1)), true, nil}, 315 {"Bool", NewAny(int32(1)), true, nil}, 316 {"Bool", NewAny(int64(1)), true, nil}, 317 {"Bool", NewAny(uint(1)), true, nil}, 318 {"Bool", NewAny(uint16(1)), true, nil}, 319 {"Bool", NewAny(uint32(1)), true, nil}, 320 {"Bool", NewAny(uint64(1)), true, nil}, 321 {"Bool", NewAny(float64(0)), false, nil}, 322 {"Bool", NewAny(float32(1)), true, nil}, 323 {"Bool", NewAny(float64(1)), true, nil}, 324 {"Bool", NewAny(json.Number("0")), false, nil}, 325 {"Bool", NewAny(json.Number("1")), true, nil}, 326 {"Bool", NewAny(json.Number("1.1")), true, nil}, 327 {"Bool", NewAny(json.Number("+x1.1")), false, nonEmptyErr}, 328 {"Bool", NewAny(string("0")), false, nil}, 329 {"Bool", NewAny(string("t")), true, nil}, 330 {"Bool", NewAny([]byte{0}), false, nonEmptyErr}, 331 {"Bool", NewRaw("true"), true, nil}, 332 {"Bool", NewRaw("false"), false, nil}, 333 {"Bool", NewRaw("null"), false, nil}, 334 {"Bool", NewString(`true`), true, nil}, 335 {"Bool", NewString(`false`), false, nil}, 336 {"Bool", NewString(``), false, nonEmptyErr}, 337 {"Bool", NewNumber("2"), true, nil}, 338 {"Bool", NewNumber("-2.1"), true, nil}, 339 {"Bool", NewNumber("-x-2.1"), false, nonEmptyErr}, 340 {"Int64", NewRaw("true"), int64(1), nil}, 341 {"Int64", NewRaw("false"), int64(0), nil}, 342 {"Int64", NewRaw("\"1\""), int64(1), nil}, 343 {"Int64", NewRaw("\"1.1\""), int64(1), nil}, 344 {"Int64", NewRaw("\"1.0\""), int64(1), nil}, 345 {"Int64", NewNumber("+x.0"), int64(0), nonEmptyErr}, 346 {"Int64", NewAny(false), int64(0), nil}, 347 {"Int64", NewAny(true), int64(1), nil}, 348 {"Int64", NewAny(int(1)), int64(1), nil}, 349 {"Int64", NewAny(int8(1)), int64(1), nil}, 350 {"Int64", NewAny(int16(1)), int64(1), nil}, 351 {"Int64", NewAny(int32(1)), int64(1), nil}, 352 {"Int64", NewAny(int64(1)), int64(1), nil}, 353 {"Int64", NewAny(uint(1)), int64(1), nil}, 354 {"Int64", NewAny(uint8(1)), int64(1), nil}, 355 {"Int64", NewAny(uint32(1)), int64(1), nil}, 356 {"Int64", NewAny(uint64(1)), int64(1), nil}, 357 {"Int64", NewAny(float32(1)), int64(1), nil}, 358 {"Int64", NewAny(float64(1)), int64(1), nil}, 359 {"Int64", NewAny("1"), int64(1), nil}, 360 {"Int64", NewAny("1.1"), int64(1), nil}, 361 {"Int64", NewAny("+1x.1"), int64(0), nonEmptyErr}, 362 {"Int64", NewAny(json.Number("1")), int64(1), nil}, 363 {"Int64", NewAny(json.Number("1.1")), int64(1), nil}, 364 {"Int64", NewAny(json.Number("+1x.1")), int64(0), nonEmptyErr}, 365 {"Int64", NewAny([]byte{0}), int64(0), ErrUnsupportType}, 366 {"Int64", Node{}, int64(0), ErrUnsupportType}, 367 {"Int64", NewRaw("0"), int64(0), nil}, 368 {"Int64", NewRaw("null"), int64(0), nil}, 369 {"StrictInt64", NewRaw("true"), int64(0), ErrUnsupportType}, 370 {"StrictInt64", NewRaw("false"), int64(0), ErrUnsupportType}, 371 {"StrictInt64", NewAny(int(0)), int64(0), nil}, 372 {"StrictInt64", NewAny(int8(0)), int64(0), nil}, 373 {"StrictInt64", NewAny(int16(0)), int64(0), nil}, 374 {"StrictInt64", NewAny(int32(0)), int64(0), nil}, 375 {"StrictInt64", NewAny(int64(0)), int64(0), nil}, 376 {"StrictInt64", NewAny(uint(0)), int64(0), nil}, 377 {"StrictInt64", NewAny(uint8(0)), int64(0), nil}, 378 {"StrictInt64", NewAny(uint32(0)), int64(0), nil}, 379 {"StrictInt64", NewAny(uint64(0)), int64(0), nil}, 380 {"StrictInt64", Node{}, int64(0), ErrUnsupportType}, 381 {"StrictInt64", NewRaw("0"), int64(0), nil}, 382 {"StrictInt64", NewRaw("null"), int64(0), ErrUnsupportType}, 383 {"Float64", NewRaw("true"), float64(1), nil}, 384 {"Float64", NewRaw("false"), float64(0), nil}, 385 {"Float64", NewRaw("\"1.0\""), float64(1.0), nil}, 386 {"Float64", NewRaw("\"xx\""), float64(0), nonEmptyErr}, 387 {"Float64", Node{}, float64(0), ErrUnsupportType}, 388 {"Float64", NewAny(false), float64(0), nil}, 389 {"Float64", NewAny(true), float64(1), nil}, 390 {"Float64", NewAny(int(1)), float64(1), nil}, 391 {"Float64", NewAny(int8(1)), float64(1), nil}, 392 {"Float64", NewAny(int16(1)), float64(1), nil}, 393 {"Float64", NewAny(int32(1)), float64(1), nil}, 394 {"Float64", NewAny(int64(1)), float64(1), nil}, 395 {"Float64", NewAny(uint(1)), float64(1), nil}, 396 {"Float64", NewAny(uint8(1)), float64(1), nil}, 397 {"Float64", NewAny(uint32(1)), float64(1), nil}, 398 {"Float64", NewAny(uint64(1)), float64(1), nil}, 399 {"Float64", NewAny(float32(1)), float64(1), nil}, 400 {"Float64", NewAny(float64(1)), float64(1), nil}, 401 {"Float64", NewAny("1.1"), float64(1.1), nil}, 402 {"Float64", NewAny("+1x.1"), float64(0), nonEmptyErr}, 403 {"Float64", NewAny(json.Number("0")), float64(0), nil}, 404 {"Float64", NewAny(json.Number("x")), float64(0), nonEmptyErr}, 405 {"Float64", NewAny([]byte{0}), float64(0), ErrUnsupportType}, 406 {"Float64", NewRaw("0.0"), float64(0.0), nil}, 407 {"Float64", NewRaw("1"), float64(1.0), nil}, 408 {"Float64", NewRaw("null"), float64(0.0), nil}, 409 {"StrictFloat64", NewRaw("true"), float64(0), ErrUnsupportType}, 410 {"StrictFloat64", NewRaw("false"), float64(0), ErrUnsupportType}, 411 {"StrictFloat64", Node{}, float64(0), ErrUnsupportType}, 412 {"StrictFloat64", NewAny(float32(0)), float64(0), nil}, 413 {"StrictFloat64", NewAny(float64(0)), float64(0), nil}, 414 {"StrictFloat64", NewRaw("0.0"), float64(0.0), nil}, 415 {"StrictFloat64", NewRaw("null"), float64(0.0), ErrUnsupportType}, 416 {"Number", Node{}, json.Number(""), ErrUnsupportType}, 417 {"Number", NewAny(false), json.Number("0"), nil}, 418 {"Number", NewAny(true), json.Number("1"), nil}, 419 {"Number", NewAny(int(1)), json.Number("1"), nil}, 420 {"Number", NewAny(int8(1)), json.Number("1"), nil}, 421 {"Number", NewAny(int16(1)), json.Number("1"), nil}, 422 {"Number", NewAny(int32(1)), json.Number("1"), nil}, 423 {"Number", NewAny(int64(1)), json.Number("1"), nil}, 424 {"Number", NewAny(uint(1)), json.Number("1"), nil}, 425 {"Number", NewAny(uint8(1)), json.Number("1"), nil}, 426 {"Number", NewAny(uint32(1)), json.Number("1"), nil}, 427 {"Number", NewAny(uint64(1)), json.Number("1"), nil}, 428 {"Number", NewAny(float32(1)), json.Number("1"), nil}, 429 {"Number", NewAny(float64(1)), json.Number("1"), nil}, 430 {"Number", NewAny("1.1"), json.Number("1.1"), nil}, 431 {"Number", NewAny("+1x.1"), json.Number(""), nonEmptyErr}, 432 {"Number", NewAny(json.Number("0")), json.Number("0"), nil}, 433 {"Number", NewAny(json.Number("x")), json.Number("x"), nil}, 434 {"Number", NewAny(json.Number("+1x.1")), json.Number("+1x.1"), nil}, 435 {"Number", NewAny([]byte{0}), json.Number(""), ErrUnsupportType}, 436 {"Number", NewRaw("x"), json.Number(""), nonEmptyErr}, 437 {"Number", NewRaw("0.0"), json.Number("0.0"), nil}, 438 {"Number", NewRaw("\"1\""), json.Number("1"), nil}, 439 {"Number", NewRaw("\"1.1\""), json.Number("1.1"), nil}, 440 {"Number", NewRaw("\"0.x0\""), json.Number(""), nonEmptyErr}, 441 {"Number", NewRaw("{]"), json.Number(""), nonEmptyErr}, 442 {"Number", NewRaw("true"), json.Number("1"), nil}, 443 {"Number", NewRaw("false"), json.Number("0"), nil}, 444 {"Number", NewRaw("null"), json.Number("0"), nil}, 445 {"StrictNumber", NewRaw("true"), json.Number(""), ErrUnsupportType}, 446 {"StrictNumber", NewRaw("false"), json.Number(""), ErrUnsupportType}, 447 {"StrictNumber", Node{}, json.Number(""), ErrUnsupportType}, 448 {"StrictNumber", NewAny(json.Number("0")), json.Number("0"), nil}, 449 {"StrictNumber", NewRaw("0.0"), json.Number("0.0"), nil}, 450 {"StrictNumber", NewRaw("null"), json.Number(""), ErrUnsupportType}, 451 {"String", Node{}, "", ErrUnsupportType}, 452 {"String", NewAny(`\u263a`), `\u263a`, nil}, 453 {"String", NewRaw(`"\u263a"`), `☺`, nil}, 454 {"String", NewString(`\u263a`), `\u263a`, nil}, 455 {"String", NewRaw(`0.0`), "0.0", nil}, 456 {"String", NewRaw(`true`), "true", nil}, 457 {"String", NewRaw(`false`), "false", nil}, 458 {"String", NewRaw(`null`), "", nil}, 459 {"String", NewAny(false), "false", nil}, 460 {"String", NewAny(true), "true", nil}, 461 {"String", NewAny(int(1)), "1", nil}, 462 {"String", NewAny(int8(1)), "1", nil}, 463 {"String", NewAny(int16(1)), "1", nil}, 464 {"String", NewAny(int32(1)), "1", nil}, 465 {"String", NewAny(int64(1)), "1", nil}, 466 {"String", NewAny(uint(1)), "1", nil}, 467 {"String", NewAny(uint8(1)), "1", nil}, 468 {"String", NewAny(uint32(1)), "1", nil}, 469 {"String", NewAny(uint64(1)), "1", nil}, 470 {"String", NewAny(float32(1)), "1", nil}, 471 {"String", NewAny(float64(1)), "1", nil}, 472 {"String", NewAny("1.1"), "1.1", nil}, 473 {"String", NewAny("+1x.1"), "+1x.1", nil}, 474 {"String", NewAny(json.Number("0")), ("0"), nil}, 475 {"String", NewAny(json.Number("x")), ("x"), nil}, 476 {"String", NewAny([]byte{0}), (""), ErrUnsupportType}, 477 {"StrictString", Node{}, "", ErrUnsupportType}, 478 {"StrictString", NewAny(`\u263a`), `\u263a`, nil}, 479 {"StrictString", NewRaw(`"\u263a"`), `☺`, nil}, 480 {"StrictString", NewString(`\u263a`), `\u263a`, nil}, 481 {"StrictString", NewRaw(`0.0`), "", ErrUnsupportType}, 482 {"StrictString", NewRaw(`true`), "", ErrUnsupportType}, 483 {"StrictString", NewRaw(`false`), "", ErrUnsupportType}, 484 {"StrictString", NewRaw(`null`), "", ErrUnsupportType}, 485 {"Len", Node{}, 0, nil}, 486 {"Len", NewAny(0), 0, ErrUnsupportType}, 487 {"Len", NewNull(), 0, nil}, 488 {"Len", NewRaw(`"1"`), 1, nil}, 489 {"Len", NewRaw(`[1]`), 0, nil}, 490 {"Len", NewArray([]Node{NewNull()}), 1, nil}, 491 {"Len", lazyArray, 0, nil}, 492 {"Len", NewRaw(`{"a":1}`), 0, nil}, 493 {"Len", lazyObject, 0, nil}, 494 {"Cap", Node{}, 0, nil}, 495 {"Cap", NewAny(0), 0, ErrUnsupportType}, 496 {"Cap", NewNull(), 0, nil}, 497 {"Cap", NewRaw(`[1]`), _DEFAULT_NODE_CAP, nil}, 498 {"Cap", NewObject([]Pair{{"", NewNull()}}), _DEFAULT_NODE_CAP, nil}, 499 {"Cap", NewRaw(`{"a":1}`), _DEFAULT_NODE_CAP, nil}, 500 } 501 lazyArray.skipAllIndex() 502 lazyObject.skipAllKey() 503 cases = append(cases, 504 tcase{"Len", lazyArray, 17, nil}, 505 tcase{"Len", lazyObject, 17, nil}, 506 tcase{"Cap", lazyArray, _DEFAULT_NODE_CAP * 3, nil}, 507 tcase{"Cap", lazyObject, _DEFAULT_NODE_CAP * 3, nil}, 508 ) 509 510 for i, c := range cases { 511 fmt.Println(i, c) 512 rt := reflect.ValueOf(&c.node) 513 m := rt.MethodByName(c.method) 514 rets := m.Call([]reflect.Value{}) 515 if len(rets) != 2 { 516 t.Error(i, rets) 517 } 518 if !reflect.DeepEqual(rets[0].Interface(), c.exp) { 519 t.Error(i, rets[0].Interface(), c.exp) 520 } 521 v := rets[1].Interface() 522 if c.err == nonEmptyErr { 523 if reflect.ValueOf(v).IsNil() { 524 t.Error(i, v) 525 } 526 } else if v != c.err { 527 t.Error(i, v) 528 } 529 } 530 } 531 532 func TestCheckError_Nil(t *testing.T) { 533 nill := (*Node)(nil) 534 if nill.Valid() || nill.Check() == nil { 535 t.Fail() 536 } 537 if nill.Get("").Check() == nil { 538 t.Fatal() 539 } 540 if nill.GetByPath("").Check() == nil { 541 t.Fatal() 542 } 543 if nill.Index(1).Check() == nil { 544 t.Fatal() 545 } 546 if nill.IndexOrGet(1, "a").Check() == nil { 547 t.Fatal() 548 } 549 if nill.IndexPair(1) != nil { 550 t.Fatal() 551 } 552 if _, err := nill.Set("", Node{}); err == nil { 553 t.Fatal() 554 } 555 if _, err := nill.SetByIndex(1, Node{}); err == nil { 556 t.Fatal() 557 } 558 if _, err := nill.SetAny("", 1); err == nil { 559 t.Fatal() 560 } 561 if _, err := nill.SetAnyByIndex(1, 1); err == nil { 562 t.Fatal() 563 } 564 if _, err := nill.Unset(""); err == nil { 565 t.Fatal() 566 } 567 if _, err := nill.UnsetByIndex(1); err == nil { 568 t.Fatal() 569 } 570 if err := nill.Add(Node{}); err == nil { 571 t.Fatal() 572 } 573 if err := nill.AddAny(1); err == nil { 574 t.Fatal() 575 } 576 } 577 578 func TestCheckError_None(t *testing.T) { 579 nill := Node{} 580 if !nill.Valid() || nill.Check() != nil { 581 t.Fail() 582 } 583 if nill.Get("").Check() == nil { 584 t.Fatal() 585 } 586 if nill.GetByPath("").Check() == nil { 587 t.Fatal() 588 } 589 if nill.Index(1).Check() == nil { 590 t.Fatal() 591 } 592 if nill.IndexOrGet(1, "a").Check() == nil { 593 t.Fatal() 594 } 595 if nill.IndexPair(1) != nil { 596 t.Fatal() 597 } 598 nill = Node{} 599 if _, err := nill.Set("a", Node{}); err != nil { 600 t.Fatal() 601 } 602 nill = Node{} 603 if _, err := nill.SetByIndex(0, Node{}); err != nil { 604 t.Fatal() 605 } 606 nill = Node{} 607 if _, err := nill.SetByIndex(1, Node{}); err == nil { 608 t.Fatal() 609 } 610 nill = Node{} 611 if _, err := nill.SetAny("a", 1); err != nil { 612 t.Fatal() 613 } 614 nill = Node{} 615 if _, err := nill.SetAnyByIndex(0, 1); err != nil { 616 t.Fatal() 617 } 618 nill = Node{} 619 if _, err := nill.SetAnyByIndex(1, 1); err == nil { 620 t.Fatal() 621 } 622 nill = Node{} 623 if _, err := nill.Unset(""); err == nil { 624 t.Fatal() 625 } 626 nill = Node{} 627 if _, err := nill.UnsetByIndex(1); err == nil { 628 t.Fatal() 629 } 630 nill = Node{} 631 if err := nill.Add(Node{}); err != nil { 632 t.Fatal() 633 } 634 nill = Node{} 635 if err := nill.AddAny(1); err != nil { 636 t.Fatal() 637 } 638 } 639 640 func TestCheckError_Error(t *testing.T) { 641 nill := newError(types.ERR_EOF, "") 642 if nill.Valid() || nill.Check() == nil { 643 t.Fail() 644 } 645 if nill.Get("").Check() == nil { 646 t.Fatal() 647 } 648 if nill.GetByPath("").Check() == nil { 649 t.Fatal() 650 } 651 if nill.Index(1).Check() == nil { 652 t.Fatal() 653 } 654 if nill.IndexOrGet(1, "a").Check() == nil { 655 t.Fatal() 656 } 657 if nill.IndexPair(1) != nil { 658 t.Fatal() 659 } 660 if _, err := nill.Set("", Node{}); err == nil { 661 t.Fatal() 662 } 663 if _, err := nill.SetByIndex(1, Node{}); err == nil { 664 t.Fatal() 665 } 666 if _, err := nill.SetAny("", 1); err == nil { 667 t.Fatal() 668 } 669 if _, err := nill.SetAnyByIndex(1, 1); err == nil { 670 t.Fatal() 671 } 672 if _, err := nill.Unset(""); err == nil { 673 t.Fatal() 674 } 675 if _, err := nill.UnsetByIndex(1); err == nil { 676 t.Fatal() 677 } 678 if err := nill.Add(Node{}); err == nil { 679 t.Fatal() 680 } 681 if err := nill.AddAny(1); err == nil { 682 t.Fatal() 683 } 684 } 685 686 func TestCheckError_Empty(t *testing.T) { 687 empty := Node{} 688 if !empty.Valid() || empty.Check() != nil || empty.Error() != "" { 689 t.Fatal() 690 } 691 692 n := newRawNode("[hello]", types.V_ARRAY) 693 n.parseRaw(false) 694 if n.Check() != nil { 695 t.Fatal(n.Check()) 696 } 697 n = newRawNode("[hello]", types.V_ARRAY) 698 n.parseRaw(true) 699 p := NewParser("[hello]") 700 p.noLazy = true 701 p.skipValue = false 702 _, x := p.Parse() 703 if n.Error() != newSyntaxError(p.syntaxError(x)).Error() { 704 t.Fatal(n.Check()) 705 } 706 707 s, err := NewParser(`{"a":{}, "b":talse, "c":{}}`).Parse() 708 if err != 0 { 709 t.Fatal(err) 710 } 711 712 root := s.GetByPath() 713 // fmt.Println(root.Check()) 714 a := root.Get("a") 715 if a.Check() != nil { 716 t.Fatal(a.Check()) 717 } 718 c := root.Get("c") 719 if c.Check() == nil { 720 t.Fatal() 721 } 722 fmt.Println(c.Check()) 723 724 _, e := a.Properties() 725 if e != nil { 726 t.Fatal(e) 727 } 728 exist, e := a.Set("d", newRawNode("x", types.V_OBJECT)) 729 if exist || e != nil { 730 t.Fatal(err) 731 } 732 if a.len() != 1 { 733 t.Fail() 734 } 735 d := a.Get("d").Get("") 736 if d.Check() == nil { 737 t.Fatal(d) 738 } 739 exist, e = a.Set("e", newRawNode("[}", types.V_ARRAY)) 740 if e != nil { 741 t.Fatal(e) 742 } 743 if a.len() != 2 { 744 t.Fail() 745 } 746 d = a.Index(1).Index(0) 747 if d.Check() == nil { 748 t.Fatal(d) 749 } 750 751 it, e := root.Interface() 752 if e == nil { 753 t.Fatal(it) 754 } 755 fmt.Println(e) 756 } 757 758 func TestIndex(t *testing.T) { 759 root, derr := NewParser(_TwitterJson).Parse() 760 if derr != 0 { 761 t.Fatalf("decode failed: %v", derr.Error()) 762 } 763 status := root.GetByPath("statuses", 0) 764 x, _ := status.Index(4).String() 765 y, _ := status.Get("id_str").String() 766 if x != y { 767 t.Fail() 768 } 769 } 770 771 func TestUnset(t *testing.T) { 772 root, derr := NewParser(_TwitterJson).Parse() 773 if derr != 0 { 774 t.Fatalf("decode failed: %v", derr.Error()) 775 } 776 entities := root.GetByPath("statuses", 0, "entities") 777 if !entities.Exists() || entities.Check() != nil { 778 t.Fatal(entities.Check().Error()) 779 } 780 exist, err := entities.Unset("urls") // NOTICE: Unset() won't change node.Len() here 781 if !exist || err != nil { 782 t.Fatal() 783 } 784 e := entities.Get("urls") 785 if e.Exists() { 786 t.Fatal() 787 } 788 if entities.len() != 3 { 789 t.Fatal(entities.len()) 790 } 791 out, err := entities.MarshalJSON() 792 require.NoError(t, err) 793 println(string(out)) 794 buf := bytes.NewBuffer(nil) 795 require.NoError(t, json.Compact(buf, out)) 796 require.Equal(t, 797 `{"hashtags":[{"text":"freebandnames","indices":[20,34]}],"user_mentions":[]}`, buf.String()) 798 799 entities.Set("urls", NewString("a")) 800 e = entities.Get("urls") 801 x, _ := e.String() 802 if !e.Exists() || x != "a" { 803 t.Fatal() 804 } 805 806 out, err = entities.MarshalJSON() 807 require.NoError(t, err) 808 buf = bytes.NewBuffer(nil) 809 json.Compact(buf, out) 810 require.Equal(t, 811 `{"hashtags":[{"text":"freebandnames","indices":[20,34]}],"user_mentions":[],"urls":"a"}`, buf.String()) 812 813 exist, err = entities.UnsetByIndex(entities.len() - 1) 814 if !exist || err != nil { 815 t.Fatal() 816 } 817 e = entities.Get("urls") 818 if e.Exists() { 819 t.Fatal() 820 } 821 822 hashtags := entities.Get("hashtags").Index(0) 823 hashtags.Set("text2", newRawNode(`{}`, types.V_OBJECT)) 824 exist, err = hashtags.Unset("indices") // NOTICE: Unset() won't change node.Len() here 825 if !exist || err != nil || hashtags.len() != 3 { 826 t.Fatal(hashtags.len()) 827 } 828 y, _ := hashtags.Get("text").String() 829 if y != "freebandnames" { 830 t.Fatal() 831 } 832 if hashtags.Get("text2").Type() != V_OBJECT { 833 t.Fatal() 834 } 835 836 ums := entities.Get("user_mentions") 837 ums.Add(NewNull()) 838 ums.Add(NewBool(true)) 839 ums.Add(NewBool(false)) 840 if ums.len() != 3 { 841 t.Fatal() 842 } 843 exist, err = ums.UnsetByIndex(2) 844 if !exist || err != nil { 845 t.Fatal() 846 } 847 v1, _ := ums.Index(0).Interface() 848 v2, _ := ums.Index(1).Interface() // NOTICE: unseted index 1 still can be find here 849 v3, _ := ums.Index(2).Interface() 850 if v1 != nil { 851 t.Fatal() 852 } 853 if v2 != true { 854 t.Fatal() 855 } 856 if v3 != nil { 857 t.Fatal() 858 } 859 out, err = entities.MarshalJSON() 860 require.NoError(t, err) 861 require.Equal(t, 862 `{"hashtags":[{"text":"freebandnames","text2":{}}],"user_mentions":[null,true]}`, string(out)) 863 864 } 865 866 // func TestUnsafeNode(t *testing.T) { 867 // str, loop := getTestIteratorSample(_DEFAULT_NODE_CAP) 868 869 // root, err := NewSearcher(str).GetByPath("array") 870 // if err != nil { 871 // t.Fatal(err) 872 // } 873 // a, _ := root.UnsafeArray() 874 // if len(a) != loop { 875 // t.Fatalf("exp:%v, got:%v", loop, len(a)) 876 // } 877 // for i := int64(0); i<int64(loop); i++{ 878 // in := a[i] 879 // x, _ := in.Int64() 880 // if x != i { 881 // t.Fatalf("exp:%v, got:%v", i, x) 882 // } 883 // } 884 885 // root, err = NewSearcher(str).GetByPath("object") 886 // if err != nil { 887 // t.Fatal(err) 888 // } 889 // b, _ := root.UnsafeMap() 890 // if len(b) != loop { 891 // t.Fatalf("exp:%v, got:%v", loop, len(b)) 892 // } 893 // for i := int64(0); i<int64(loop); i++ { 894 // k := `k`+strconv.Itoa(int(i)) 895 // if k != b[i].Key { 896 // t.Fatalf("unexpected element: %#v", b[i]) 897 // } 898 // x, _ := b[i].Value.Int64() 899 // if x != i { 900 // t.Fatalf("exp:%v, got:%v", i, x) 901 // } 902 // } 903 // } 904 905 func TestUseNode(t *testing.T) { 906 str, loop := getTestIteratorSample(_DEFAULT_NODE_CAP) 907 root, e := NewParser(str).Parse() 908 if e != 0 { 909 t.Fatal(e) 910 } 911 _, er := root.InterfaceUseNode() 912 if er != nil { 913 t.Fatal(er) 914 } 915 916 root, err := NewSearcher(str).GetByPath("array") 917 if err != nil { 918 t.Fatal(err) 919 } 920 a, _ := root.ArrayUseNode() 921 if len(a) != loop { 922 t.Fatalf("exp:%v, got:%v", loop, len(a)) 923 } 924 for i := int64(0); i < int64(loop); i++ { 925 in := a[i] 926 a, _ := in.Int64() 927 if a != i { 928 t.Fatalf("exp:%v, got:%v", i, a) 929 } 930 } 931 932 root, err = NewSearcher(str).GetByPath("array") 933 if err != nil { 934 t.Fatal(err) 935 } 936 x, _ := root.InterfaceUseNode() 937 a = x.([]Node) 938 if len(a) != loop { 939 t.Fatalf("exp:%v, got:%v", loop, len(a)) 940 } 941 for i := int64(0); i < int64(loop); i++ { 942 in := a[i] 943 a, _ := in.Int64() 944 if a != i { 945 t.Fatalf("exp:%v, got:%v", i, a) 946 } 947 } 948 949 root, err = NewSearcher(str).GetByPath("object") 950 if err != nil { 951 t.Fatal(err) 952 } 953 b, _ := root.MapUseNode() 954 if len(b) != loop { 955 t.Fatalf("exp:%v, got:%v", loop, len(b)) 956 } 957 for i := int64(0); i < int64(loop); i++ { 958 k := `k` + strconv.Itoa(int(i)) 959 xn, ok := b[k] 960 if !ok { 961 t.Fatalf("unexpected element: %#v", xn) 962 } 963 a, _ := xn.Int64() 964 if a != i { 965 t.Fatalf("exp:%v, got:%v", i, a) 966 } 967 } 968 969 root, err = NewSearcher(str).GetByPath("object") 970 if err != nil { 971 t.Fatal(err) 972 } 973 x, _ = root.InterfaceUseNode() 974 b = x.(map[string]Node) 975 if len(b) != loop { 976 t.Fatalf("exp:%v, got:%v", loop, len(b)) 977 } 978 for i := int64(0); i < int64(loop); i++ { 979 k := `k` + strconv.Itoa(int(i)) 980 xn, ok := b[k] 981 if !ok { 982 t.Fatalf("unexpected element: %#v", xn) 983 } 984 a, _ := xn.Int64() 985 if a != i { 986 t.Fatalf("exp:%v, got:%v", i, a) 987 } 988 } 989 } 990 991 func TestUseNumber(t *testing.T) { 992 str, _ := getTestIteratorSample(_DEFAULT_NODE_CAP) 993 root, e := NewParser(str).Parse() 994 if e != 0 { 995 t.Fatal(e) 996 } 997 _, er := root.InterfaceUseNumber() 998 if er != nil { 999 t.Fatal(er) 1000 } 1001 1002 node, err := NewParser("1061346755812312312313").Parse() 1003 if err != 0 { 1004 t.Fatal(err) 1005 } 1006 if node.Type() != V_NUMBER { 1007 t.Fatalf("wrong type: %v", node.Type()) 1008 } 1009 x, _ := node.InterfaceUseNumber() 1010 iv := x.(json.Number) 1011 if iv.String() != "1061346755812312312313" { 1012 t.Fatalf("exp:%#v, got:%#v", "1061346755812312312313", iv.String()) 1013 } 1014 x, _ = node.Interface() 1015 ix := x.(float64) 1016 if ix != float64(1061346755812312312313) { 1017 t.Fatalf("exp:%#v, got:%#v", float64(1061346755812312312313), ix) 1018 } 1019 xj, _ := node.Number() 1020 ij, _ := xj.Int64() 1021 jj, _ := json.Number("1061346755812312312313").Int64() 1022 if ij != jj { 1023 t.Fatalf("exp:%#v, got:%#v", jj, ij) 1024 } 1025 } 1026 1027 func TestMap(t *testing.T) { 1028 node, err := NewParser(`{"a":-0, "b":1, "c":-1.2, "d":-1.2e-10}`).Parse() 1029 if err != 0 { 1030 t.Fatal(err) 1031 } 1032 m, _ := node.Map() 1033 assert.Equal(t, m, map[string]interface{}{ 1034 "a": float64(0), 1035 "b": float64(1), 1036 "c": -1.2, 1037 "d": -1.2e-10, 1038 }) 1039 m1, _ := node.MapUseNumber() 1040 assert.Equal(t, m1, map[string]interface{}{ 1041 "a": json.Number("-0"), 1042 "b": json.Number("1"), 1043 "c": json.Number("-1.2"), 1044 "d": json.Number("-1.2e-10"), 1045 }) 1046 } 1047 1048 func TestArray(t *testing.T) { 1049 node, err := NewParser(`[-0, 1, -1.2, -1.2e-10]`).Parse() 1050 if err != 0 { 1051 t.Fatal(err) 1052 } 1053 m, _ := node.Array() 1054 assert.Equal(t, m, []interface{}{ 1055 float64(0), 1056 float64(1), 1057 -1.2, 1058 -1.2e-10, 1059 }) 1060 m1, _ := node.ArrayUseNumber() 1061 assert.Equal(t, m1, []interface{}{ 1062 json.Number("-0"), 1063 json.Number("1"), 1064 json.Number("-1.2"), 1065 json.Number("-1.2e-10"), 1066 }) 1067 } 1068 1069 func TestNodeRaw(t *testing.T) { 1070 root, derr := NewSearcher(_TwitterJson).GetByPath("search_metadata") 1071 if derr != nil { 1072 t.Fatalf("decode failed: %v", derr.Error()) 1073 } 1074 val, _ := root.Raw() 1075 var comp = `{ 1076 "max_id": 250126199840518145, 1077 "since_id": 24012619984051000, 1078 "refresh_url": "?since_id=250126199840518145&q=%23freebandnames&result_type=mixed&include_entities=1", 1079 "next_results": "?max_id=249279667666817023&q=%23freebandnames&count=4&include_entities=1&result_type=mixed", 1080 "count": 4, 1081 "completed_in": 0.035, 1082 "since_id_str": "24012619984051000", 1083 "query": "%23freebandnames", 1084 "max_id_str": "250126199840518145" 1085 }` 1086 if val != comp { 1087 t.Fatalf("exp: %+v, got: %+v", comp, val) 1088 } 1089 1090 root, derr = NewSearcher(_TwitterJson).GetByPath("statuses", 0, "entities", "hashtags") 1091 if derr != nil { 1092 t.Fatalf("decode failed: %v", derr.Error()) 1093 } 1094 val, _ = root.Raw() 1095 comp = `[ 1096 { 1097 "text": "freebandnames", 1098 "indices": [ 1099 20, 1100 34 1101 ] 1102 } 1103 ]` 1104 if val != comp { 1105 t.Fatalf("exp: \n%s\n, got: \n%s\n", comp, val) 1106 } 1107 1108 var data = `{"k1" : { "a" : "bc"} , "k2" : [1,2 ] , "k3":{} , "k4":[]}` 1109 root, derr = NewSearcher(data).GetByPath("k1") 1110 if derr != nil { 1111 t.Fatalf("decode failed: %v", derr.Error()) 1112 } 1113 val, _ = root.Raw() 1114 comp = `{ "a" : "bc"}` 1115 if val != comp { 1116 t.Fatalf("exp: %+v, got: %+v", comp, val) 1117 } 1118 1119 root, derr = NewSearcher(data).GetByPath("k2") 1120 if derr != nil { 1121 t.Fatalf("decode failed: %v", derr.Error()) 1122 } 1123 val, _ = root.Raw() 1124 comp = `[1,2 ]` 1125 if val != comp { 1126 t.Fatalf("exp: %+v, got: %+v", comp, val) 1127 } 1128 1129 root, derr = NewSearcher(data).GetByPath("k3") 1130 if derr != nil { 1131 t.Fatalf("decode failed: %v", derr.Error()) 1132 } 1133 val, _ = root.Raw() 1134 comp = `{}` 1135 if val != comp { 1136 t.Fatalf("exp: %+v, got: %+v", comp, val) 1137 } 1138 1139 root, derr = NewSearcher(data).GetByPath("k4") 1140 if derr != nil { 1141 t.Fatalf("decode failed: %v", derr.Error()) 1142 } 1143 val, _ = root.Raw() 1144 comp = `[]` 1145 if val != comp { 1146 t.Fatalf("exp: %+v, got: %+v", comp, val) 1147 } 1148 } 1149 1150 func TestNodeGet(t *testing.T) { 1151 root, derr := NewParser(_TwitterJson).Parse() 1152 if derr != 0 { 1153 t.Fatalf("decode failed: %v", derr.Error()) 1154 } 1155 val, _ := root.Get("search_metadata").Get("max_id").Int64() 1156 if val != int64(250126199840518145) { 1157 t.Fatalf("exp: %+v, got: %+v", 250126199840518145, val) 1158 } 1159 } 1160 1161 func TestNodeIndex(t *testing.T) { 1162 root, derr := NewParser(_TwitterJson).Parse() 1163 if derr != 0 { 1164 t.Fatalf("decode failed: %v", derr.Error()) 1165 } 1166 val, _ := root.Get("statuses").Index(3).Get("id_str").String() 1167 if val != "249279667666817024" { 1168 t.Fatalf("exp: %+v, got: %+v", "249279667666817024", val) 1169 } 1170 } 1171 1172 func TestNodeGetByPath(t *testing.T) { 1173 root, derr := NewParser(_TwitterJson).Parse() 1174 if derr != 0 { 1175 t.Fatalf("decode failed: %v", derr.Error()) 1176 } 1177 val, _ := root.GetByPath("statuses", 3, "id_str").String() 1178 if val != "249279667666817024" { 1179 t.Fatalf("exp: %+v, got: %+v", "249279667666817024", val) 1180 } 1181 } 1182 1183 func TestNodeSet(t *testing.T) { 1184 empty := Node{} 1185 err := empty.Add(Node{}) 1186 if err != nil { 1187 t.Fatal(err) 1188 } 1189 empty2 := empty.Index(0) 1190 if empty2.Check() != nil { 1191 t.Fatal(err) 1192 } 1193 exist, err := empty2.SetByIndex(1, Node{}) 1194 if exist || err == nil { 1195 t.Fatal(exist, err) 1196 } 1197 empty3 := empty.Index(0) 1198 if empty3.Check() != nil { 1199 t.Fatal(err) 1200 } 1201 exist, err = empty3.Set("a", NewNumber("-1")) 1202 if exist || err != nil { 1203 t.Fatal(exist, err) 1204 } 1205 if n, e := empty.Index(0).Get("a").Int64(); e != nil || n != -1 { 1206 t.Fatal(n, e) 1207 } 1208 1209 empty = NewNull() 1210 err = empty.Add(NewNull()) 1211 if err != nil { 1212 t.Fatal(err) 1213 } 1214 empty2 = empty.Index(0) 1215 if empty2.Check() != nil { 1216 t.Fatal(err) 1217 } 1218 exist, err = empty2.SetByIndex(1, NewNull()) 1219 if exist || err == nil { 1220 t.Fatal(exist, err) 1221 } 1222 empty3 = empty.Index(0) 1223 if empty3.Check() != nil { 1224 t.Fatal(err) 1225 } 1226 exist, err = empty3.Set("a", NewNumber("-1")) 1227 if exist || err != nil { 1228 t.Fatal(exist, err) 1229 } 1230 if n, e := empty.Index(0).Get("a").Int64(); e != nil || n != -1 { 1231 t.Fatal(n, e) 1232 } 1233 1234 root, derr := NewParser(_TwitterJson).Parse() 1235 if derr != 0 { 1236 t.Fatalf("decode failed: %v", derr.Error()) 1237 } 1238 app, _ := NewParser("111").Parse() 1239 root.GetByPath("statuses", 3).Set("id_str", app) 1240 val, _ := root.GetByPath("statuses", 3, "id_str").Int64() 1241 if val != 111 { 1242 t.Fatalf("exp: %+v, got: %+v", 111, val) 1243 } 1244 for i, _ := root.GetByPath("statuses", 3).Cap(); i >= 0; i-- { 1245 root.GetByPath("statuses", 3).Set("id_str"+strconv.Itoa(i), app) 1246 } 1247 val, _ = root.GetByPath("statuses", 3, "id_str0").Int64() 1248 if val != 111 { 1249 t.Fatalf("exp: %+v, got: %+v", 111, val) 1250 } 1251 1252 nroot, derr := NewParser(`{"a":[0.1,true,0,"name",{"b":"c"}]}`).Parse() 1253 if derr != 0 { 1254 t.Fatalf("decode failed: %v", derr.Error()) 1255 } 1256 root.GetByPath("statuses", 3).Set("id_str2", nroot) 1257 val2, _ := root.GetByPath("statuses", 3, "id_str2", "a", 4, "b").String() 1258 if val2 != "c" { 1259 t.Fatalf("exp:%+v, got:%+v", "c", val2) 1260 } 1261 } 1262 1263 func TestNodeAny(t *testing.T) { 1264 empty := Node{} 1265 _, err := empty.SetAny("any", map[string]interface{}{"a": []int{0}}) 1266 if err != nil { 1267 t.Fatal(err) 1268 } 1269 if m, err := empty.Get("any").Interface(); err != nil { 1270 t.Fatal(err) 1271 } else if v, ok := m.(map[string]interface{}); !ok { 1272 t.Fatal(v) 1273 } 1274 if buf, err := empty.MarshalJSON(); err != nil { 1275 t.Fatal(err) 1276 } else if string(buf) != `{"any":{"a":[0]}}` { 1277 t.Fatal(string(buf)) 1278 } 1279 if _, err := empty.Set("any2", Node{}); err != nil { 1280 t.Fatal(err) 1281 } 1282 if err := empty.Get("any2").AddAny(nil); err != nil { 1283 t.Fatal(err) 1284 } 1285 if buf, err := empty.MarshalJSON(); err != nil { 1286 t.Fatal(err) 1287 } else if string(buf) != `{"any":{"a":[0]},"any2":[null]}` { 1288 t.Fatal(string(buf)) 1289 } 1290 if _, err := empty.Get("any2").SetAnyByIndex(0, NewNumber("-0.0")); err != nil { 1291 t.Fatal(err) 1292 } 1293 if buf, err := empty.MarshalJSON(); err != nil { 1294 t.Fatal(err) 1295 } else if string(buf) != `{"any":{"a":[0]},"any2":[-0.0]}` { 1296 t.Fatal(string(buf)) 1297 } 1298 } 1299 1300 func TestNodeSetByIndex(t *testing.T) { 1301 root, derr := NewParser(_TwitterJson).Parse() 1302 if derr != 0 { 1303 t.Fatalf("decode failed: %v", derr.Error()) 1304 } 1305 app, _ := NewParser("111").Parse() 1306 st := root.GetByPath("statuses") 1307 st.SetByIndex(0, app) 1308 st = root.GetByPath("statuses") 1309 val := st.Index(0) 1310 x, _ := val.Int64() 1311 if x != 111 { 1312 t.Fatalf("exp: %+v, got: %+v", 111, val) 1313 } 1314 1315 nroot, derr := NewParser(`{"a":[0.1,true,0,"name",{"b":"c"}]}`).Parse() 1316 if derr != 0 { 1317 t.Fatalf("decode failed: %v", derr.Error()) 1318 } 1319 root.GetByPath("statuses").SetByIndex(0, nroot) 1320 val2, _ := root.GetByPath("statuses", 0, "a", 4, "b").String() 1321 if val2 != "c" { 1322 t.Fatalf("exp:%+v, got:%+v", "c", val2) 1323 } 1324 } 1325 1326 func TestNodeAdd(t *testing.T) { 1327 root, derr := NewParser(_TwitterJson).Parse() 1328 if derr != 0 { 1329 t.Fatalf("decode failed: %v", derr.Error()) 1330 } 1331 app, _ := NewParser("111").Parse() 1332 1333 for i, _ := root.GetByPath("statuses").Cap(); i >= 0; i-- { 1334 root.GetByPath("statuses").Add(app) 1335 } 1336 val, _ := root.GetByPath("statuses", 4).Int64() 1337 if val != 111 { 1338 t.Fatalf("exp: %+v, got: %+v", 111, val) 1339 } 1340 val, _ = root.GetByPath("statuses", root.GetByPath("statuses").len()-1).Int64() 1341 if val != 111 { 1342 t.Fatalf("exp: %+v, got: %+v", 111, val) 1343 } 1344 1345 nroot, derr := NewParser(`{"a":[0.1,true,0,"name",{"b":"c"}]}`).Parse() 1346 if derr != 0 { 1347 t.Fatalf("decode failed: %v", derr.Error()) 1348 } 1349 root.GetByPath("statuses").Add(nroot) 1350 val2, _ := root.GetByPath("statuses", root.GetByPath("statuses").len()-1, "a", 4, "b").String() 1351 if val2 != "c" { 1352 t.Fatalf("exp:%+v, got:%+v", "c", val2) 1353 } 1354 } 1355 1356 func BenchmarkLoadNode(b *testing.B) { 1357 b.Run("Interface()", func(b *testing.B) { 1358 b.SetBytes(int64(len(_TwitterJson))) 1359 b.ResetTimer() 1360 for i := 0; i < b.N; i++ { 1361 root, err := NewSearcher(_TwitterJson).GetByPath("statuses", 0) 1362 if err != nil { 1363 b.Fatal(err) 1364 } 1365 _, _ = root.Interface() 1366 } 1367 }) 1368 1369 b.Run("LoadAll()", func(b *testing.B) { 1370 b.SetBytes(int64(len(_TwitterJson))) 1371 b.ResetTimer() 1372 for i := 0; i < b.N; i++ { 1373 root, err := NewSearcher(_TwitterJson).GetByPath("statuses", 0) 1374 if err != nil { 1375 b.Fatal(err) 1376 } 1377 _ = root.LoadAll() 1378 } 1379 }) 1380 1381 b.Run("InterfaceUseNode()", func(b *testing.B) { 1382 b.SetBytes(int64(len(_TwitterJson))) 1383 b.ResetTimer() 1384 for i := 0; i < b.N; i++ { 1385 root, err := NewSearcher(_TwitterJson).GetByPath("statuses", 0) 1386 if err != nil { 1387 b.Fatal(err) 1388 } 1389 _, _ = root.InterfaceUseNode() 1390 } 1391 }) 1392 1393 b.Run("Load()", func(b *testing.B) { 1394 b.SetBytes(int64(len(_TwitterJson))) 1395 b.ResetTimer() 1396 for i := 0; i < b.N; i++ { 1397 root, err := NewSearcher(_TwitterJson).GetByPath("statuses", 0) 1398 if err != nil { 1399 b.Fatal(err) 1400 } 1401 _ = root.Load() 1402 } 1403 }) 1404 } 1405 1406 func BenchmarkLoadNode_Parallel(b *testing.B) { 1407 b.Run("Interface()", func(b *testing.B) { 1408 b.SetBytes(int64(len(_TwitterJson))) 1409 b.ResetTimer() 1410 b.RunParallel(func(pb *testing.PB) { 1411 for pb.Next() { 1412 root, err := NewSearcher(_TwitterJson).GetByPath("statuses", 0) 1413 if err != nil { 1414 b.Fatal(err) 1415 } 1416 _, _ = root.Interface() 1417 } 1418 }) 1419 }) 1420 1421 b.Run("LoadAll()", func(b *testing.B) { 1422 b.SetBytes(int64(len(_TwitterJson))) 1423 b.ResetTimer() 1424 b.RunParallel(func(pb *testing.PB) { 1425 for pb.Next() { 1426 root, err := NewSearcher(_TwitterJson).GetByPath("statuses", 0) 1427 if err != nil { 1428 b.Fatal(err) 1429 } 1430 _ = root.LoadAll() 1431 } 1432 }) 1433 }) 1434 1435 b.Run("InterfaceUseNode()", func(b *testing.B) { 1436 b.SetBytes(int64(len(_TwitterJson))) 1437 b.ResetTimer() 1438 b.RunParallel(func(pb *testing.PB) { 1439 for pb.Next() { 1440 root, err := NewSearcher(_TwitterJson).GetByPath("statuses", 0) 1441 if err != nil { 1442 b.Fatal(err) 1443 } 1444 _, _ = root.InterfaceUseNode() 1445 } 1446 }) 1447 }) 1448 1449 b.Run("Load()", func(b *testing.B) { 1450 b.SetBytes(int64(len(_TwitterJson))) 1451 b.ResetTimer() 1452 b.RunParallel(func(pb *testing.PB) { 1453 for pb.Next() { 1454 root, err := NewSearcher(_TwitterJson).GetByPath("statuses", 0) 1455 if err != nil { 1456 b.Fatal(err) 1457 } 1458 _ = root.Load() 1459 } 1460 }) 1461 }) 1462 } 1463 1464 func BenchmarkNodeGetByPath(b *testing.B) { 1465 root, derr := NewParser(_TwitterJson).Parse() 1466 if derr != 0 { 1467 b.Fatalf("decode failed: %v", derr.Error()) 1468 } 1469 _, _ = root.GetByPath("statuses", 3, "entities", "hashtags", 0, "text").String() 1470 b.ResetTimer() 1471 1472 b.RunParallel(func(pb *testing.PB) { 1473 for pb.Next() { 1474 _, _ = root.GetByPath("statuses", 3, "entities", "hashtags", 0, "text").String() 1475 } 1476 }) 1477 } 1478 1479 func BenchmarkStructGetByPath(b *testing.B) { 1480 var root = _TwitterStruct{} 1481 err := json.Unmarshal([]byte(_TwitterJson), &root) 1482 if err != nil { 1483 b.Fatalf("unmarshal failed: %v", err) 1484 } 1485 1486 b.ResetTimer() 1487 1488 b.RunParallel(func(pb *testing.PB) { 1489 for pb.Next() { 1490 _ = root.Statuses[3].Entities.Hashtags[0].Text 1491 } 1492 }) 1493 } 1494 1495 func BenchmarkNodeIndex(b *testing.B) { 1496 root, derr := NewParser(_TwitterJson).Parse() 1497 if derr != 0 { 1498 b.Fatalf("decode failed: %v", derr.Error()) 1499 } 1500 node := root.Get("statuses").Index(3).Get("entities").Get("hashtags").Index(0) 1501 node.Set("test1", NewNumber("1")) 1502 node.Set("test2", NewNumber("2")) 1503 node.Set("test3", NewNumber("3")) 1504 node.Set("test4", NewNumber("4")) 1505 node.Set("test5", NewNumber("5")) 1506 b.ResetTimer() 1507 for i := 0; i < b.N; i++ { 1508 node.Index(2) 1509 } 1510 } 1511 1512 func BenchmarkStructIndex(b *testing.B) { 1513 type T struct { 1514 A Node 1515 B Node 1516 C Node 1517 D Node 1518 E Node 1519 } 1520 var obj = new(T) 1521 b.ResetTimer() 1522 for i := 0; i < b.N; i++ { 1523 _ = obj.C 1524 } 1525 } 1526 1527 func BenchmarkSliceIndex(b *testing.B) { 1528 var obj = []Node{Node{}, Node{}, Node{}, Node{}, Node{}} 1529 b.ResetTimer() 1530 for i := 0; i < b.N; i++ { 1531 _ = obj[2] 1532 } 1533 } 1534 1535 func BenchmarkMapIndex(b *testing.B) { 1536 var obj = map[string]interface{}{"test1": Node{}, "test2": Node{}, "test3": Node{}, "test4": Node{}, "test5": Node{}} 1537 b.ResetTimer() 1538 for i := 0; i < b.N; i++ { 1539 for k := range obj { 1540 if k == "test3" { 1541 break 1542 } 1543 } 1544 } 1545 } 1546 1547 func BenchmarkNodeGet(b *testing.B) { 1548 var N = 5 1549 var half = "test" + strconv.Itoa(N/2+1) 1550 root, derr := NewParser(_TwitterJson).Parse() 1551 if derr != 0 { 1552 b.Fatalf("decode failed: %v", derr.Error()) 1553 } 1554 node := root.Get("statuses").Index(3).Get("entities").Get("hashtags").Index(0) 1555 for i := 0; i < N; i++ { 1556 node.Set("test"+strconv.Itoa(i), NewNumber(strconv.Itoa(i))) 1557 } 1558 1559 b.ResetTimer() 1560 for i := 0; i < b.N; i++ { 1561 _ = node.Get(half) 1562 } 1563 } 1564 1565 func BenchmarkSliceGet(b *testing.B) { 1566 var obj = []string{"test1", "test2", "test3", "test4", "test5"} 1567 str := "test3" 1568 b.ResetTimer() 1569 for i := 0; i < b.N; i++ { 1570 for _, k := range obj { 1571 if k == str { 1572 break 1573 } 1574 } 1575 } 1576 } 1577 1578 func BenchmarkMapGet(b *testing.B) { 1579 root, derr := NewParser(_TwitterJson).Parse() 1580 if derr != 0 { 1581 b.Fatalf("decode failed: %v", derr.Error()) 1582 } 1583 node := root.Get("statuses").Index(3).Get("entities").Get("hashtags").Index(0) 1584 node.Set("test1", NewNumber("1")) 1585 node.Set("test2", NewNumber("2")) 1586 node.Set("test3", NewNumber("3")) 1587 node.Set("test4", NewNumber("4")) 1588 node.Set("test5", NewNumber("5")) 1589 m, _ := node.Map() 1590 b.ResetTimer() 1591 for i := 0; i < b.N; i++ { 1592 _ = m["test3"] 1593 } 1594 } 1595 1596 func BenchmarkNodeSet(b *testing.B) { 1597 root, derr := NewParser(_TwitterJson).Parse() 1598 if derr != 0 { 1599 b.Fatalf("decode failed: %v", derr.Error()) 1600 } 1601 node := root.Get("statuses").Index(3).Get("entities").Get("hashtags").Index(0) 1602 node.Set("test1", NewNumber("1")) 1603 node.Set("test2", NewNumber("2")) 1604 node.Set("test3", NewNumber("3")) 1605 node.Set("test4", NewNumber("4")) 1606 node.Set("test5", NewNumber("5")) 1607 n := NewNull() 1608 b.ResetTimer() 1609 for i := 0; i < b.N; i++ { 1610 node.Set("test3", n) 1611 } 1612 } 1613 1614 func BenchmarkMapSet(b *testing.B) { 1615 root, derr := NewParser(_TwitterJson).Parse() 1616 if derr != 0 { 1617 b.Fatalf("decode failed: %v", derr.Error()) 1618 } 1619 node := root.Get("statuses").Index(3).Get("entities").Get("hashtags").Index(0) 1620 node.Set("test1", NewNumber("1")) 1621 node.Set("test2", NewNumber("2")) 1622 node.Set("test3", NewNumber("3")) 1623 node.Set("test4", NewNumber("4")) 1624 node.Set("test5", NewNumber("5")) 1625 m, _ := node.Map() 1626 n := NewNull() 1627 b.ResetTimer() 1628 for i := 0; i < b.N; i++ { 1629 m["test3"] = n 1630 } 1631 } 1632 1633 func BenchmarkNodeSetByIndex(b *testing.B) { 1634 root, derr := NewParser(_TwitterJson).Parse() 1635 if derr != 0 { 1636 b.Fatalf("decode failed: %v", derr.Error()) 1637 } 1638 node := root.Get("statuses").Index(3).Get("entities").Get("hashtags") 1639 node.Add(NewNumber("1")) 1640 node.Add(NewNumber("2")) 1641 node.Add(NewNumber("3")) 1642 node.Add(NewNumber("4")) 1643 node.Add(NewNumber("5")) 1644 n := NewNull() 1645 b.ResetTimer() 1646 for i := 0; i < b.N; i++ { 1647 node.SetByIndex(2, n) 1648 } 1649 } 1650 1651 func BenchmarkSliceSetByIndex(b *testing.B) { 1652 root, derr := NewParser(_TwitterJson).Parse() 1653 if derr != 0 { 1654 b.Fatalf("decode failed: %v", derr.Error()) 1655 } 1656 node := root.Get("statuses").Index(3).Get("entities").Get("hashtags") 1657 node.Add(NewNumber("1")) 1658 node.Add(NewNumber("2")) 1659 node.Add(NewNumber("3")) 1660 node.Add(NewNumber("4")) 1661 node.Add(NewNumber("5")) 1662 m, _ := node.Array() 1663 n := NewNull() 1664 b.ResetTimer() 1665 for i := 0; i < b.N; i++ { 1666 m[2] = n 1667 } 1668 } 1669 1670 func BenchmarkStructSetByIndex(b *testing.B) { 1671 type T struct { 1672 A Node 1673 B Node 1674 C Node 1675 D Node 1676 E Node 1677 } 1678 var obj = new(T) 1679 n := NewNull() 1680 b.ResetTimer() 1681 for i := 0; i < b.N; i++ { 1682 obj.C = n 1683 } 1684 } 1685 1686 func BenchmarkNodeUnset(b *testing.B) { 1687 root, derr := NewParser(_TwitterJson).Parse() 1688 if derr != 0 { 1689 b.Fatalf("decode failed: %v", derr.Error()) 1690 } 1691 node := root.Get("statuses").Index(3).Get("entities").Get("hashtags").Index(0) 1692 node.Set("test1", NewNumber("1")) 1693 node.Set("test2", NewNumber("2")) 1694 node.Set("test3", NewNumber("3")) 1695 node.Set("test4", NewNumber("4")) 1696 node.Set("test5", NewNumber("5")) 1697 b.ResetTimer() 1698 for i := 0; i < b.N; i++ { 1699 node.Unset("test3") 1700 } 1701 } 1702 1703 func BenchmarkMapUnset(b *testing.B) { 1704 root, derr := NewParser(_TwitterJson).Parse() 1705 if derr != 0 { 1706 b.Fatalf("decode failed: %v", derr.Error()) 1707 } 1708 node := root.Get("statuses").Index(3).Get("entities").Get("hashtags").Index(0) 1709 node.Set("test1", NewNumber("1")) 1710 node.Set("test2", NewNumber("2")) 1711 node.Set("test3", NewNumber("3")) 1712 node.Set("test4", NewNumber("4")) 1713 node.Set("test5", NewNumber("5")) 1714 m, _ := node.Map() 1715 b.ResetTimer() 1716 for i := 0; i < b.N; i++ { 1717 delete(m, "test3") 1718 } 1719 } 1720 1721 func BenchmarkNodUnsetByIndex(b *testing.B) { 1722 root, derr := NewParser(_TwitterJson).Parse() 1723 if derr != 0 { 1724 b.Fatalf("decode failed: %v", derr.Error()) 1725 } 1726 node := root.Get("statuses").Index(3).Get("entities").Get("hashtags") 1727 node.Add(NewNumber("1")) 1728 node.Add(NewNumber("2")) 1729 node.Add(NewNumber("3")) 1730 node.Add(NewNumber("4")) 1731 node.Add(NewNumber("5")) 1732 b.ResetTimer() 1733 for i := 0; i < b.N; i++ { 1734 node.UnsetByIndex(2) 1735 } 1736 } 1737 1738 func BenchmarkSliceUnsetByIndex(b *testing.B) { 1739 root, derr := NewParser(_TwitterJson).Parse() 1740 if derr != 0 { 1741 b.Fatalf("decode failed: %v", derr.Error()) 1742 } 1743 node := root.Get("statuses").Index(3).Get("entities").Get("hashtags") 1744 node.Add(NewNumber("1")) 1745 node.Add(NewNumber("2")) 1746 node.Add(NewNumber("3")) 1747 node.Add(NewNumber("4")) 1748 node.Add(NewNumber("5")) 1749 m, _ := node.Array() 1750 b.ResetTimer() 1751 for i := 0; i < b.N; i++ { 1752 for i := 3; i < 5; i++ { 1753 m[i-1] = m[i] 1754 } 1755 } 1756 } 1757 1758 func BenchmarkNodeAdd(b *testing.B) { 1759 n := NewObject([]Pair{{"test", NewNumber("1")}}) 1760 b.ResetTimer() 1761 for i := 0; i < b.N; i++ { 1762 node := NewArray([]Node{}) 1763 node.Add(n) 1764 } 1765 } 1766 1767 func BenchmarkSliceAdd(b *testing.B) { 1768 n := NewObject([]Pair{{"test", NewNumber("1")}}) 1769 b.ResetTimer() 1770 for i := 0; i < b.N; i++ { 1771 node := []Node{} 1772 node = append(node, n) 1773 } 1774 } 1775 1776 func BenchmarkMapAdd(b *testing.B) { 1777 n := NewObject([]Pair{{"test", NewNumber("1")}}) 1778 b.ResetTimer() 1779 for i := 0; i < b.N; i++ { 1780 node := map[string]Node{} 1781 node["test3"] = n 1782 } 1783 }