-
Notifications
You must be signed in to change notification settings - Fork 138
/
update_test.go
103 lines (84 loc) · 2.22 KB
/
update_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package fastjson
import (
"testing"
)
func TestObjectDelSet(t *testing.T) {
var p Parser
var o *Object
o.Del("xx")
v, err := p.Parse(`{"fo\no": "bar", "x": [1,2,3]}`)
if err != nil {
t.Fatalf("unexpected error during parse: %s", err)
}
o, err = v.Object()
if err != nil {
t.Fatalf("cannot obtain object: %s", err)
}
// Delete x
o.Del("x")
if o.Len() != 1 {
t.Fatalf("unexpected number of items left; got %d; want %d", o.Len(), 1)
}
// Try deleting non-existing value
o.Del("xxx")
if o.Len() != 1 {
t.Fatalf("unexpected number of items left; got %d; want %d", o.Len(), 1)
}
// Set new value
vNew := MustParse(`{"foo":[1,2,3]}`)
o.Set("new_key", vNew)
// Delete item with escaped key
o.Del("fo\no")
if o.Len() != 1 {
t.Fatalf("unexpected number of items left; got %d; want %d", o.Len(), 1)
}
str := o.String()
strExpected := `{"new_key":{"foo":[1,2,3]}}`
if str != strExpected {
t.Fatalf("unexpected string representation for o: got %q; want %q", str, strExpected)
}
// Set and Del function as no-op on nil value
o = nil
o.Del("x")
o.Set("x", MustParse(`[3]`))
}
func TestValueDelSet(t *testing.T) {
var p Parser
v, err := p.Parse(`{"xx": 123, "x": [1,2,3]}`)
if err != nil {
t.Fatalf("unexpected error during parse: %s", err)
}
// Delete xx
v.Del("xx")
n := v.GetObject().Len()
if n != 1 {
t.Fatalf("unexpected number of items left; got %d; want %d", n, 1)
}
// Try deleting non-existing value in the array
va := v.Get("x")
va.Del("foobar")
// Delete middle element in the array
va.Del("1")
a := v.GetArray("x")
if len(a) != 2 {
t.Fatalf("unexpected number of items left in the array; got %d; want %d", len(a), 2)
}
// Update the first element in the array
vNew := MustParse(`"foobar"`)
va.Set("0", vNew)
// Add third element to the array
vNew = MustParse(`[3]`)
va.Set("3", vNew)
// Add invalid array index to the array
va.Set("invalid", MustParse(`"nonsense"`))
str := v.String()
strExpected := `{"x":["foobar",3,null,[3]]}`
if str != strExpected {
t.Fatalf("unexpected string representation for o: got %q; want %q", str, strExpected)
}
// Set and Del function as no-op on nil value
v = nil
v.Del("x")
v.Set("x", MustParse(`[]`))
v.SetArrayItem(1, MustParse(`[]`))
}