-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathjson_test.go
107 lines (92 loc) · 1.99 KB
/
json_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
104
105
106
107
package dragoman_test
import (
"cmp"
"slices"
"testing"
tcmp "github.com/google/go-cmp/cmp"
"github.com/modernice/dragoman"
)
func TestJSONDiff(t *testing.T) {
source := map[string]any{
"hello": "Hello, World!",
"bye": "Goodbye!",
"$contact": map[string]any{
"email": "hello@example.com",
"phone": "123-456-7890",
"response": map[string]any{
"message": "Hello!",
},
},
}
target := map[string]any{
"hello": "Hello, World!",
"$contact": map[string]any{
"email": "hello@example.com",
},
}
want := []dragoman.JSONPath{
{"bye"},
{"$contact", "phone"},
{"$contact", "response", "message"},
}
paths, err := dragoman.JSONDiff(source, target)
if err != nil {
t.Fatalf("JSONDiff(%s, %s): %v", source, target, err)
}
if !equalPaths(want, paths) {
t.Fatalf("JSONDiff(): got %v; want %v", paths, want)
}
}
func TestJSONExtract(t *testing.T) {
data := map[string]any{
"hello": "Hello, World!",
"bye": "Goodbye!",
"$contact": map[string]any{
"email": "hello@example.com",
"phone": "123-456-7890",
"response": map[string]any{
"message": "Hello!",
},
},
}
paths := []dragoman.JSONPath{
{"bye"},
{"$contact", "email"},
{"$contact", "response", "message"},
}
want := map[string]any{
"bye": "Goodbye!",
"$contact": map[string]any{
"email": "hello@example.com",
"response": map[string]any{
"message": "Hello!",
},
},
}
got, err := dragoman.JSONExtract(data, paths)
if err != nil {
t.Fatalf("JSONExtract(%s, %s): %v", data, paths, err)
}
if !tcmp.Equal(want, got) {
t.Fatalf("JSONExtract(): got %v; want %v", got, want)
}
}
func equalPaths(a, b []dragoman.JSONPath) bool {
if len(a) != len(b) {
return false
}
comparer := func(a, b dragoman.JSONPath) int {
if v := cmp.Compare(len(a), len(b)); v != 0 {
return v
}
for i := range a {
if v := cmp.Compare(a[i], b[i]); v != 0 {
return v
}
}
return 0
}
slices.SortFunc(a, comparer)
slices.SortFunc(b, comparer)
return tcmp.Equal(a, b)
}