-
Notifications
You must be signed in to change notification settings - Fork 41
/
differ_test.go
445 lines (415 loc) · 9.58 KB
/
differ_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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
package jsondiff
import (
"bytes"
"encoding/json"
"fmt"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"testing"
)
var testNameReplacer = strings.NewReplacer(",", "", "(", "", ")", "")
type testcase struct {
Name string `json:"name"`
Before interface{} `json:"before"`
After interface{} `json:"after"`
Patch Patch `json:"patch"`
PartialPatch Patch `json:"partial_patch"`
Ignores []string `json:"ignores"`
SkipApplyTest bool `json:"skip_apply_test"`
}
type patchGetter func(tc *testcase) Patch
func TestRFCCases(t *testing.T) { runCasesFromFile(t, "testdata/tests/rfc.json", Factorize(), LCS()) } // https://datatracker.ietf.org/doc/html/rfc6902#appendix-A
func TestArrayCases(t *testing.T) { runCasesFromFile(t, "testdata/tests/array.json") }
func TestObjectCases(t *testing.T) { runCasesFromFile(t, "testdata/tests/object.json") }
func TestRootCases(t *testing.T) { runCasesFromFile(t, "testdata/tests/root.json") }
func TestDiffer_Reset(t *testing.T) {
d := &Differ{
ptr: pointer{
buf: make([]byte, 15),
sep: 15,
},
hashmap: map[uint64]jsonNode{
1: {},
},
patch: make([]Operation, 42),
}
d.Reset()
if l := len(d.patch); l != 0 {
t.Errorf("expected empty patch collection, got length %d", l)
}
if l := len(d.hashmap); l != 0 {
t.Errorf("expected cleared hashmap, got length %d", l)
}
if d.ptr.sep != 0 {
t.Errorf("expected reset ptr")
}
if l := len(d.ptr.buf); l != 0 {
t.Errorf("expected empty ptr buf, got length %d", l)
}
}
func TestOptions(t *testing.T) {
makeopts := func(opts ...Option) []Option { return opts }
for _, tc := range []struct {
testfile string
options []Option
}{
{"testdata/tests/options/invertible.json", makeopts(Invertible())},
{"testdata/tests/options/factorization.json", makeopts(Factorize())},
{"testdata/tests/options/rationalization.json", makeopts(Rationalize())},
{"testdata/tests/options/equivalence.json", makeopts(Equivalent())},
{"testdata/tests/options/ignore.json", makeopts()},
{"testdata/tests/options/lcs.json", makeopts(LCS(), Factorize())},
{"testdata/tests/options/all.json", makeopts(Factorize(), Rationalize(), Invertible(), Equivalent())},
} {
var (
ext = filepath.Ext(tc.testfile)
base = filepath.Base(tc.testfile)
name = strings.TrimSuffix(base, ext)
)
t.Run(name, func(t *testing.T) {
runCasesFromFile(t, tc.testfile, tc.options...)
})
}
}
func runCasesFromFile(t *testing.T, filename string, opts ...Option) {
t.Helper()
b, err := os.ReadFile(filename)
if err != nil {
t.Fatal(err)
}
var cases []testcase
if err := json.Unmarshal(b, &cases); err != nil {
t.Fatal(err)
}
runTestCases(t, cases, opts...)
}
func runTestCases(t *testing.T, cases []testcase, opts ...Option) {
t.Helper()
for _, tc := range cases {
name := testNameReplacer.Replace(tc.Name)
t.Run(name, func(t *testing.T) {
runTestCase(t, tc, func(tc *testcase) Patch {
return tc.Patch
}, opts...)
})
if tc.Ignores != nil {
name = fmt.Sprintf("%s_with_ignore", name)
xopts := append(opts, Ignores(tc.Ignores...)) //nolint:gocritic
t.Run(name, func(t *testing.T) {
runTestCase(t, tc, func(tc *testcase) Patch {
return tc.PartialPatch
}, xopts...)
})
}
}
}
func runTestCase(t *testing.T, tc testcase, pc patchGetter, opts ...Option) {
t.Helper()
afterBytes, err := json.Marshal(tc.After)
if err != nil {
t.Error(err)
}
d := &Differ{
targetBytes: afterBytes,
}
d = d.WithOpts(opts...)
d.Compare(tc.Before, tc.After)
patch, wantPatch := d.Patch(), pc(&tc)
if patch != nil {
t.Logf("\n%s", patch)
}
if len(patch) != len(wantPatch) {
t.Errorf("got %d operations, want %d", len(patch), len(wantPatch))
return
}
for i, op := range patch {
want := wantPatch[i]
if g, w := op.Type, want.Type; g != w {
t.Errorf("op #%d mismatch: op: got %q, want %q", i, g, w)
}
if g, w := op.Path, want.Path; g != w {
t.Errorf("op #%d mismatch: path: got %q, want %q", i, g, w)
}
switch want.Type {
case OperationCopy, OperationMove:
if g, w := op.From, want.From; g != w {
t.Errorf("op #%d mismatch: from: got %q, want %q", i, g, w)
}
case OperationAdd, OperationReplace:
if !reflect.DeepEqual(op.Value, want.Value) {
t.Errorf("op #%d mismatch: value: unequal", i)
}
}
}
// Unsupported cases:
// * the Ignores() option is enabled
// * explicitly disabled for individual test case
if d.opts.ignores != nil || tc.SkipApplyTest {
return
}
mustMarshal := func(v any) []byte {
t.Helper()
b, err := json.Marshal(v)
if err != nil {
t.Errorf("marshaling error: %s", err)
}
return b
}
// Validate that the patch is fundamentally correct by
// applying it to the source document, and compare the
// result with the expected document.
b, err := patch.apply(mustMarshal(tc.Before), false)
if err != nil {
t.Errorf("failed to apply patch: %s", err)
}
// Re-marshal the patched document to ensure it follows
// the Golang JSON convention of ordering map keys, and
// can be compared to the target document.
before, after := unmarshalMarshal(t, b), mustMarshal(tc.After)
if !bytes.Equal(before, after) {
t.Errorf("patch does not produce the expected changes")
t.Logf("got: %s", string(before))
t.Logf("want: %s", string(after))
}
}
func TestDiffer_unorderedDeepEqualSlice(t *testing.T) {
for _, tc := range []struct {
src, tgt []interface{}
equal bool
}{
{
src: []interface{}{1, 2, 3},
tgt: []interface{}{3, 2, 1},
equal: true,
},
{
src: []interface{}{1, 2, 3},
tgt: []interface{}{4, 3, 2, 1},
equal: false,
},
{
src: []interface{}{
"foo",
map[string]interface{}{"A": "AAA"},
map[string]interface{}{"B": "BBB"},
"foo",
"bar",
},
tgt: []interface{}{
"foo",
"foo",
map[string]interface{}{"A": "AAA"},
map[string]interface{}{"B": "BBB"},
"bar",
},
equal: true,
},
} {
d := Differ{}
eq := d.unorderedDeepEqualSlice(tc.src, tc.tgt)
if eq != tc.equal {
t.Errorf("equality mismatch, got %t, want %t", eq, tc.equal)
}
}
}
func Test_issue17(t *testing.T) {
type (
VolumeMount struct {
Name string `json:"name"`
MountPath string `json:"mountPath"`
}
Container struct {
VolumeMounts []VolumeMount `json:"volumeMounts,omitempty"`
}
)
src := Container{
VolumeMounts: []VolumeMount{{
Name: "name1",
MountPath: "/foo/bar/1",
}, {
Name: "name2",
MountPath: "/foo/bar/2",
}, {
Name: "name3",
MountPath: "/foo/bar/3",
}, {
Name: "name4",
MountPath: "/foo/bar/4",
}, {
Name: "name5",
MountPath: "/foo/bar/5",
}, {
Name: "name6",
MountPath: "/foo/bar/6",
}},
}
tgt := Container{
VolumeMounts: []VolumeMount{{
Name: "name1",
MountPath: "/foo/bar/1",
}, {
Name: "name2",
MountPath: "/foo/bar/2",
}, {
Name: "name4",
MountPath: "/foo/bar/4",
}, {
Name: "name5",
MountPath: "/foo/bar/5",
}, {
Name: "name6",
MountPath: "/foo/bar/6",
}},
}
patch, _ := Compare(src, tgt, LCS())
if len(patch) != 1 {
t.Errorf("expected a patch with 1 operation, got %d", len(patch))
}
b, _ := json.Marshal(patch)
t.Logf("%s", string(b))
}
func Test_issue29(t *testing.T) {
src := []byte(`{"a":{"b":[{"c":[4,5]},2,1]}}`)
tgt := []byte(`{"a":{"b":[{"c":[5,4]},1,2]}}`)
patch, err := CompareJSON(src, tgt, Equivalent())
if err != nil {
t.Error(err)
}
if len(patch) != 0 {
t.Errorf("expected 0 operations, got %d", len(patch))
}
t.Log(patch)
}
func Test_issue29_alt(t *testing.T) {
src := []byte(`{"a":{"b":[[7,6],2,[42,84]]}}`)
tgt := []byte(`{"a":{"b":[[6,7],1,[84,42]]}}`)
patch, err := CompareJSON(src, tgt, Equivalent())
if err != nil {
t.Error(err)
}
if len(patch) != 1 {
t.Errorf("expected 1 operations, got %d", len(patch))
t.Log(patch)
}
if op := patch[0]; op.Path != "/a/b/1" && op.Type != OperationReplace {
t.Errorf("expected replace operation at path /a/b/1, got %s at %s", op.Type, op.Path)
}
}
func Benchmark_sortStrings(b *testing.B) {
if testing.Short() {
b.Skip()
}
for _, v := range [][]string{
{ // 5
"medieval",
"bike",
"trust",
"sodium",
"hemisphere",
},
{ // 10
"general",
"lamp",
"journal",
"common",
"grind",
"hay",
"dismiss",
"sunrise",
"shoulder",
"certain",
},
{ // 15
"plant",
"instinct",
"infect",
"transaction",
"transport",
"beer",
"printer",
"neutral",
"collect",
"message",
"chaos",
"dynamic",
"justice",
"master",
"want",
},
{ // 20
"absorption",
"ditch",
"gradual",
"leftovers",
"lace",
"clash",
"fun",
"stereotype",
"lamp",
"deter",
"circle",
"lay",
"murder",
"grimace",
"jacket",
"have",
"ambiguous",
"pit",
"plug",
"notice",
},
{ // 25
"flesh",
"kidney",
"hard",
"carbon",
"ignorant",
"pocket",
"strategic",
"allow",
"advance",
"impulse",
"infinite",
"integrated",
"expenditure",
"technology",
"prevent",
"valid",
"revive",
"manager",
"sheep",
"kitchen",
"guest",
"dismissal",
"divide",
"bow",
"buffet",
},
} {
b.Run(fmt.Sprintf("sort.Strings-%d", len(v)), func(b *testing.B) {
for i := 0; i < b.N; i++ {
sort.Strings(v)
}
})
b.Run(fmt.Sprintf("sortStrings-%d", len(v)), func(b *testing.B) {
for i := 0; i < b.N; i++ {
sortStrings(v)
}
})
}
}
func unmarshalMarshal(t *testing.T, b []byte) []byte {
t.Helper()
var i interface{}
if err := json.Unmarshal(b, &i); err != nil {
t.Error(err)
}
b2, err := json.Marshal(i)
if err != nil {
t.Error(err)
}
return b2
}