-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_test.go
More file actions
558 lines (480 loc) · 13.4 KB
/
create_test.go
File metadata and controls
558 lines (480 loc) · 13.4 KB
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
package jsonpatch
import (
"encoding/json"
"testing"
)
func TestCreatePatch_AddObjectMember(t *testing.T) {
original := []byte(`{"foo": "bar"}`)
modified := []byte(`{"foo": "bar", "baz": "qux"}`)
patch, err := CreatePatch(original, modified)
if err != nil {
t.Fatal(err)
}
// Apply the generated patch and verify the result
result, err := ApplyPatch(original, patch)
if err != nil {
t.Fatal(err)
}
assertJSONEqual(t, string(modified), string(result))
}
func TestCreatePatch_RemoveObjectMember(t *testing.T) {
original := []byte(`{"baz": "qux", "foo": "bar"}`)
modified := []byte(`{"foo": "bar"}`)
patch, err := CreatePatch(original, modified)
if err != nil {
t.Fatal(err)
}
result, err := ApplyPatch(original, patch)
if err != nil {
t.Fatal(err)
}
assertJSONEqual(t, string(modified), string(result))
}
func TestCreatePatch_ReplaceValue(t *testing.T) {
original := []byte(`{"baz": "qux", "foo": "bar"}`)
modified := []byte(`{"baz": "boo", "foo": "bar"}`)
patch, err := CreatePatch(original, modified)
if err != nil {
t.Fatal(err)
}
result, err := ApplyPatch(original, patch)
if err != nil {
t.Fatal(err)
}
assertJSONEqual(t, string(modified), string(result))
}
func TestCreatePatch_NestedObjects(t *testing.T) {
original := []byte(`{
"foo": {"bar": "baz", "waldo": "fred"},
"qux": {"corge": "grault"}
}`)
modified := []byte(`{
"foo": {"bar": "baz"},
"qux": {"corge": "grault", "thud": "fred"}
}`)
patch, err := CreatePatch(original, modified)
if err != nil {
t.Fatal(err)
}
result, err := ApplyPatch(original, patch)
if err != nil {
t.Fatal(err)
}
assertJSONEqual(t, string(modified), string(result))
}
func TestCreatePatch_ArrayModification(t *testing.T) {
original := []byte(`{"foo": ["bar", "baz"]}`)
modified := []byte(`{"foo": ["bar", "qux", "baz"]}`)
patch, err := CreatePatch(original, modified)
if err != nil {
t.Fatal(err)
}
result, err := ApplyPatch(original, patch)
if err != nil {
t.Fatal(err)
}
assertJSONEqual(t, string(modified), string(result))
}
func TestCreatePatch_ArrayRemoval(t *testing.T) {
original := []byte(`{"foo": ["bar", "qux", "baz"]}`)
modified := []byte(`{"foo": ["bar", "baz"]}`)
patch, err := CreatePatch(original, modified)
if err != nil {
t.Fatal(err)
}
result, err := ApplyPatch(original, patch)
if err != nil {
t.Fatal(err)
}
assertJSONEqual(t, string(modified), string(result))
}
func TestCreatePatch_TypeChange(t *testing.T) {
original := []byte(`{"foo": "bar"}`)
modified := []byte(`{"foo": 42}`)
patch, err := CreatePatch(original, modified)
if err != nil {
t.Fatal(err)
}
result, err := ApplyPatch(original, patch)
if err != nil {
t.Fatal(err)
}
assertJSONEqual(t, string(modified), string(result))
}
func TestCreatePatch_NullValue(t *testing.T) {
original := []byte(`{"foo": "bar"}`)
modified := []byte(`{"foo": null}`)
patch, err := CreatePatch(original, modified)
if err != nil {
t.Fatal(err)
}
result, err := ApplyPatch(original, patch)
if err != nil {
t.Fatal(err)
}
assertJSONEqual(t, string(modified), string(result))
}
func TestCreatePatch_ComplexDocument(t *testing.T) {
original := []byte(`{
"title": "Hello",
"author": {"name": "John", "email": "john@example.com"},
"tags": ["go", "json"],
"published": false
}`)
modified := []byte(`{
"title": "Hello World",
"author": {"name": "John", "email": "john@newdomain.com"},
"tags": ["go", "json", "patch"],
"published": true,
"views": 100
}`)
patch, err := CreatePatch(original, modified)
if err != nil {
t.Fatal(err)
}
result, err := ApplyPatch(original, patch)
if err != nil {
t.Fatal(err)
}
assertJSONEqual(t, string(modified), string(result))
}
func TestCreatePatch_IdenticalDocuments(t *testing.T) {
original := []byte(`{"foo": "bar", "baz": [1, 2, 3]}`)
patch, err := CreatePatch(original, original)
if err != nil {
t.Fatal(err)
}
if len(patch) != 0 {
t.Errorf("expected empty patch for identical documents, got %d operations", len(patch))
}
}
func TestCreatePatch_EmptyToNonEmpty(t *testing.T) {
original := []byte(`{}`)
modified := []byte(`{"foo": "bar", "baz": 42}`)
patch, err := CreatePatch(original, modified)
if err != nil {
t.Fatal(err)
}
result, err := ApplyPatch(original, patch)
if err != nil {
t.Fatal(err)
}
assertJSONEqual(t, string(modified), string(result))
}
func TestCreatePatch_NonEmptyToEmpty(t *testing.T) {
original := []byte(`{"foo": "bar", "baz": 42}`)
modified := []byte(`{}`)
patch, err := CreatePatch(original, modified)
if err != nil {
t.Fatal(err)
}
result, err := ApplyPatch(original, patch)
if err != nil {
t.Fatal(err)
}
assertJSONEqual(t, string(modified), string(result))
}
func TestCreatePatch_SpecialCharactersInKeys(t *testing.T) {
original := []byte(`{"a/b": 1, "c~d": 2}`)
modified := []byte(`{"a/b": 10, "c~d": 20}`)
patch, err := CreatePatch(original, modified)
if err != nil {
t.Fatal(err)
}
result, err := ApplyPatch(original, patch)
if err != nil {
t.Fatal(err)
}
assertJSONEqual(t, string(modified), string(result))
}
func TestCreatePatch_RootArrays(t *testing.T) {
original := []byte(`[1, 2, 3]`)
modified := []byte(`[1, 4, 3, 5]`)
patch, err := CreatePatch(original, modified)
if err != nil {
t.Fatal(err)
}
result, err := ApplyPatch(original, patch)
if err != nil {
t.Fatal(err)
}
assertJSONEqual(t, string(modified), string(result))
}
func TestMarshalPatch(t *testing.T) {
patch := Patch{
{Op: OpAdd, Path: "/foo"},
{Op: OpRemove, Path: "/bar"},
}
data, err := MarshalPatch(patch)
if err != nil {
t.Fatal(err)
}
// Verify it's valid JSON
var result []map[string]interface{}
if err := json.Unmarshal(data, &result); err != nil {
t.Fatal(err)
}
if len(result) != 2 {
t.Errorf("expected 2 operations, got %d", len(result))
}
}
func TestDecodePatch(t *testing.T) {
raw := []byte(`[
{"op": "add", "path": "/foo", "value": "bar"},
{"op": "remove", "path": "/baz"},
{"op": "replace", "path": "/qux", "value": 42},
{"op": "move", "from": "/a", "path": "/b"},
{"op": "copy", "from": "/c", "path": "/d"},
{"op": "test", "path": "/e", "value": true}
]`)
patch, err := DecodePatch(raw)
if err != nil {
t.Fatal(err)
}
if len(patch) != 6 {
t.Fatalf("expected 6 operations, got %d", len(patch))
}
expectedOps := []OpType{OpAdd, OpRemove, OpReplace, OpMove, OpCopy, OpTest}
for i, op := range patch {
if op.Op != expectedOps[i] {
t.Errorf("operation %d: expected %q, got %q", i, expectedOps[i], op.Op)
}
}
}
func TestDecodePatch_NonStringPathRejected(t *testing.T) {
tests := []struct {
name string
raw string
}{
{"path as number", `[{"op":"remove","path":123}]`},
{"path as object", `[{"op":"add","path":{},"value":"x"}]`},
{"path as array", `[{"op":"test","path":[],"value":true}]`},
{"path as boolean", `[{"op":"replace","path":false,"value":1}]`},
{"path as null", `[{"op":"remove","path":null}]`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := DecodePatch([]byte(tt.raw))
if err == nil {
t.Fatalf("expected DecodePatch to reject non-string path: %s", tt.raw)
}
})
}
}
func TestDecodePatch_NonStringFromRejected(t *testing.T) {
tests := []struct {
name string
raw string
}{
{"from as number", `[{"op":"move","from":123,"path":"/a"}]`},
{"from as object", `[{"op":"copy","from":{},"path":"/a"}]`},
{"from as array", `[{"op":"move","from":[],"path":"/a"}]`},
{"from as boolean", `[{"op":"copy","from":true,"path":"/a"}]`},
{"from as null", `[{"op":"move","from":null,"path":"/a"}]`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := DecodePatch([]byte(tt.raw))
if err == nil {
t.Fatalf("expected DecodePatch to reject non-string from: %s", tt.raw)
}
})
}
}
func TestDecodePatch_DuplicateMemberBehavior(t *testing.T) {
// Duplicate object members have undefined handling in JSON Patch (RFC 6902 Appendix A.13).
// Go's encoding/json keeps the last occurrence; this test documents and guards that behavior.
raw := []byte(`[{"op":"remove","path":"/first","path":"/second"}]`)
patch, err := DecodePatch(raw)
if err != nil {
t.Fatalf("expected decode to succeed with duplicate path key under encoding/json semantics: %v", err)
}
if len(patch) != 1 {
t.Fatalf("expected one operation, got %d", len(patch))
}
if patch[0].Path != "/second" {
t.Fatalf("expected last duplicate key to win, got path=%q", patch[0].Path)
}
}
func TestCreatePatch_InvalidOriginalJSON(t *testing.T) {
_, err := CreatePatch([]byte(`not json`), []byte(`{}`))
if err == nil {
t.Fatal("expected error for invalid original JSON")
}
}
// ---------------------------------------------------------------------------
// Operation.Validate() and HasFrom()
// ---------------------------------------------------------------------------
func TestValidate_StructLiteral(t *testing.T) {
// Struct literal without hasPath set — Validate should infer it.
raw := json.RawMessage(`"hello"`)
op := Operation{
Op: OpAdd,
Path: "/foo",
Value: &raw,
}
if err := op.Validate(); err != nil {
t.Fatalf("Validate() should succeed for well-formed struct literal: %v", err)
}
if op.cache == nil {
t.Fatal("expected cache to be populated after Validate()")
}
}
func TestValidate_MoveStructLiteral(t *testing.T) {
op := Operation{
Op: OpMove,
From: "/a",
Path: "/b",
}
if err := op.Validate(); err != nil {
t.Fatalf("Validate() should succeed: %v", err)
}
}
func TestValidate_CopyStructLiteralWithRootFrom(t *testing.T) {
// A struct literal with From="" is indistinguishable from a forgotten From
// field, so Validate must reject it. Callers who need root-pointer source
// must use NewCopyOperation("", "/dup") instead.
op := Operation{
Op: OpCopy,
From: "",
Path: "/dup",
}
if err := op.Validate(); err == nil {
t.Fatal("Validate() should fail for copy with unset From field")
}
}
func TestValidate_CopyConstructorWithRootFrom(t *testing.T) {
op := NewCopyOperation("", "/dup")
if err := op.Validate(); err != nil {
t.Fatalf("Validate() should succeed for copy constructed with root from: %v", err)
}
}
func TestValidate_RemoveStructLiteral(t *testing.T) {
op := Operation{
Op: OpRemove,
Path: "/foo",
}
if err := op.Validate(); err != nil {
t.Fatalf("Validate() should succeed: %v", err)
}
}
func TestValidate_MissingOp(t *testing.T) {
op := Operation{Path: "/foo"}
if err := op.Validate(); err == nil {
t.Fatal("expected error for missing op")
}
}
func TestValidate_InvalidPath(t *testing.T) {
raw := json.RawMessage(`1`)
op := Operation{
Op: OpAdd,
Path: "no-slash",
Value: &raw,
}
if err := op.Validate(); err == nil {
t.Fatal("expected error for invalid path without leading slash")
}
}
func TestValidate_CachesPointers(t *testing.T) {
raw := json.RawMessage(`"val"`)
op := Operation{
Op: OpReplace,
Path: "/a/b",
Value: &raw,
}
if err := op.Validate(); err != nil {
t.Fatal(err)
}
if op.cache == nil || op.cache.parsedPath.String() != "/a/b" {
got := ""
if op.cache != nil {
got = op.cache.parsedPath.String()
}
t.Errorf("expected cached path /a/b, got %q", got)
}
}
func TestHasFrom(t *testing.T) {
op1 := NewMoveOperation("/a", "/b")
if !op1.HasFrom() {
t.Error("expected HasFrom() true for NewMoveOperation")
}
op2 := Operation{Op: OpAdd, Path: "/x"}
if op2.HasFrom() {
t.Error("expected HasFrom() false for operation without from")
}
}
// ---------------------------------------------------------------------------
// Cached value behaviour
// ---------------------------------------------------------------------------
func TestCachedValue_DecodedPatchUsesCache(t *testing.T) {
patchJSON := []byte(`[{"op": "add", "path": "/foo", "value": {"nested": true}}]`)
patch, err := DecodePatch(patchJSON)
if err != nil {
t.Fatal(err)
}
if patch[0].cache == nil {
t.Fatal("expected cache to be populated after DecodePatch")
}
val, err := patch[0].GetValue()
if err != nil {
t.Fatal(err)
}
m, ok := val.(map[string]interface{})
if !ok {
t.Fatalf("expected map, got %T", val)
}
if m["nested"] != true {
t.Errorf("expected nested=true, got %v", m["nested"])
}
}
func TestCreatePatch_InvalidModifiedJSON(t *testing.T) {
_, err := CreatePatch([]byte(`{}`), []byte(`not json`))
if err == nil {
t.Fatal("expected error for invalid modified JSON")
}
}
func TestCreateAndApply_RoundTrip(t *testing.T) {
// A comprehensive round-trip test: create a patch from two documents,
// then apply it to the original and verify we get the modified version.
docs := []struct {
name string
original string
modified string
}{
{
"simple object",
`{"a": 1, "b": 2}`,
`{"a": 1, "b": 3, "c": 4}`,
},
{
"nested object",
`{"a": {"b": {"c": 1}}}`,
`{"a": {"b": {"c": 2, "d": 3}}}`,
},
{
"array",
`[1, 2, 3, 4, 5]`,
`[1, 3, 5, 7]`,
},
{
"mixed types",
`{"str": "hello", "num": 42, "bool": true, "null": null, "arr": [1,2], "obj": {"k":"v"}}`,
`{"str": "world", "num": 43, "bool": false, "null": "not null", "arr": [3], "obj": {"k":"v2","k2":"v3"}}`,
},
}
for _, tt := range docs {
t.Run(tt.name, func(t *testing.T) {
patch, err := CreatePatch([]byte(tt.original), []byte(tt.modified))
if err != nil {
t.Fatalf("CreatePatch failed: %v", err)
}
result, err := ApplyPatch([]byte(tt.original), patch)
if err != nil {
// Print the patch for debugging
patchJSON, _ := json.MarshalIndent(patch, "", " ")
t.Fatalf("ApplyPatch failed: %v\npatch: %s", err, patchJSON)
}
assertJSONEqual(t, tt.modified, string(result))
})
}
}