Skip to content

Commit

Permalink
Handle null and other literals correctly in merge. Fixes #160
Browse files Browse the repository at this point in the history
  • Loading branch information
evanphx committed Jan 12, 2024
1 parent 742691b commit a82b43d
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 31 deletions.
8 changes: 8 additions & 0 deletions v5/merge.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ func doMergePatch(docData, patchData []byte, mergeMerge bool) ([]byte, error) {
}

if isSyntaxError(patchErr) {
if json.Valid(patchData) {
return patchData, nil
}

return nil, errBadJSONPatch
}

Expand All @@ -154,6 +158,10 @@ func doMergePatch(docData, patchData []byte, mergeMerge bool) ([]byte, error) {
patchErr = json.Unmarshal(patchData, patchAry)

if patchErr != nil {
// Not an array either, a literal is the result directly.
if json.Valid(patchData) {
return patchData, nil
}
return nil, errBadJSONPatch
}

Expand Down
34 changes: 3 additions & 31 deletions v5/merge_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@ package jsonpatch

import (
"fmt"
"strings"
"testing"
)

func mergePatch(doc, patch string) string {
out, err := MergePatch([]byte(doc), []byte(patch))

if err != nil {
panic(err)
panic(fmt.Sprintf("%s: %s", err, patch))
}

return string(out)
Expand Down Expand Up @@ -166,8 +165,8 @@ var rfcTests = []struct {
{target: `{"a":[{"b":"c"}]}`, patch: `{"a":[1]}`, expected: `{"a":[1]}`},
{target: `["a","b"]`, patch: `["c","d"]`, expected: `["c","d"]`},
{target: `{"a":"b"}`, patch: `["c"]`, expected: `["c"]`},
// {target: `{"a":"foo"}`, patch: `null`, expected: `null`},
// {target: `{"a":"foo"}`, patch: `"bar"`, expected: `"bar"`},
{target: `{"a":"foo"}`, patch: `null`, expected: `null`},
{target: `{"a":"foo"}`, patch: `"bar"`, expected: `"bar"`},
{target: `{"e":null}`, patch: `{"a":1}`, expected: `{"a":1,"e":null}`},
{target: `[1,2]`, patch: `{"a":"b","c":null}`, expected: `{"a":"b"}`},
{target: `{}`, patch: `{"a":{"bb":{"ccc":null}}}`, expected: `{"a":{"bb":{}}}`},
Expand All @@ -183,33 +182,6 @@ func TestMergePatchRFCCases(t *testing.T) {
}
}

var rfcFailTests = `
{"a":"foo"} | null
{"a":"foo"} | "bar"
`

func TestMergePatchFailRFCCases(t *testing.T) {
tests := strings.Split(rfcFailTests, "\n")

for _, c := range tests {
if strings.TrimSpace(c) == "" {
continue
}

parts := strings.SplitN(c, "|", 2)

doc := strings.TrimSpace(parts[0])
pat := strings.TrimSpace(parts[1])

out, err := MergePatch([]byte(doc), []byte(pat))

if err != errBadJSONPatch {
t.Errorf("error not returned properly: %s, %s", err, string(out))
}
}

}

func TestResembleJSONArray(t *testing.T) {
testCases := []struct {
input []byte
Expand Down

0 comments on commit a82b43d

Please sign in to comment.